安卓前台服务不断抛出“java.lang.IllegalArgumentException: Service not registered”异常

9

我的项目需要一个 Android 前台服务持续运行(即使应用程序被销毁)。 为此,我有以下代码片段:

build.gradle

implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'
implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.google.android.gms:play-services-places:16.0.0'
implementation 'com.google.android.libraries.places:places:1.1.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.android.gms:play-services-ads:17.2.0'

清单权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

MainActivity.java

@Override
public void onCreate() {
    Intent intent = new Intent(getApplicationContext(), MyService.class);
    if (!isMyServiceRunning(MyService.class, MainActivity.this)) {
        intent.setAction(MYConstants.ACTION_START_GPS_SERVICE);
        intent.setAction(MyConstants.ACTION_START_GPS_SERVICE);
        startService(intent);
        Log.i(TAG, "MyService call made.");
    }
}

MyService.java

public class MyService extends Service {
       @Override
       public void onCreate() {
           super.onCreate();
           if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
               startServiceWithNotification();
           } else{
               startForeground(9999, new Notification());
           }
       }

       @Override
       public int onStartCommand(Intent intent, int flags, int startId) {
            super.onStartCommand(intent, flags, startId);
            return START_STICKY;
       }

       @Override
       public void onTaskRemoved(Intent rootIntent){
          stopMyService();
          Intent broadcastIntent = new Intent(this, MyBroadcastReceiver.class);
          sendBroadcast(broadcastIntent);
       }

       @Override
       public void onDestroy() {
           stopMyService();
           super.onDestroy();
      }

      @Override
      public IBinder onBind(Intent intent) {
           // Used only in case of bound services.
           return null;
     }

     void stopMyService() {
          stopForeground(true);
          stopSelf();
     }

     @RequiresApi(Build.VERSION_CODES.O)
     void startServiceWithNotification() {
        String channelId = "com.mypackage.myapp";
        String channelName = "Your Service";

        NotificationChannel chan;

        chan = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager mNotificationManager = (NotificationManager) 
               getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.createNotificationChannel(chan);


        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, 
              channelId);

        Notification notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("App is running in background")
            .setPriority(NotificationManager.IMPORTANCE_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build();
        startForeground(10000, notification);
    }
}

MyBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    Intent intent =  new Intent(context, MyService.class);
    intent.setAction(MYConstants.ACTION_START_GPS_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(intent);
        Log.i(TAG, "MyService call made.");
    } else {
        context.startService(intent);
    }
}

这个应用程序运行正常,即使在应用程序被销毁后,前台服务也可以正常运行并执行它的预期任务,但我一直看到一个警告作为IllegalArgumentException而出现。以下是异常信息:

D/EGL_emulation: eglMakeCurrent: 0xdda12a20: ver 3 0 (tinfo 0xdda81230)
W/System: A resource failed to call close. 
W/ConnectionTracker: Exception thrown while unbinding
   java.lang.IllegalArgumentException: Service not registered: ll@85f600c
       at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:1731)
       at android.app.ContextImpl.unbindService(ContextImpl.java:1755)
       at android.content.ContextWrapper.unbindService(ContextWrapper.java:735)
       at ce.b(:com.google.android.gms.dynamite_measurementdynamite@201817068@20.18.17 (100700-0):1)
       at ce.a(:com.google.android.gms.dynamite_measurementdynamite@201817068@20.18.17 (100700-0):5)
       at lm.A(:com.google.android.gms.dynamite_measurementdynamite@201817068@20.18.17 (100700-0):10)
       at kx.a(:com.google.android.gms.dynamite_measurementdynamite@201817068@20.18.17 (100700-0):3)
       at dx.run(:com.google.android.gms.dynamite_measurementdynamite@201817068@20.18.17 (100700- 
          0):2)
       at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
       at java.util.concurrent.FutureTask.run(FutureTask.java:266)
       at iv.run(:com.google.android.gms.dynamite_measurementdynamite@201817068@20.18.17 (100700- 
         0):15)
 W/.myapp: Reducing the number of considered missed Gc histogram windows from 186 to 100
 W/System: A resource failed to call close. 

有人能帮助我理解为什么会一直抛出这个异常,以及如何解决它吗?


2
这似乎不是来自你的代码,并且似乎与你的应用程序没有太多关系。你是否在使用Play Services库? - CommonsWare
@CommonsWare,我正在使用Android GPS_SERVICE(不确定是否被视为Play服务),我已经在我的清单文件中更新了目前我正在使用的所有权限。这些信息有用吗(说实话,我对Android编程还是很新手)? - mang4521
“不确定这是否被视为Play服务” - 不是。如果在您的模块的build.gradle文件中有属于com.google.android.gms组的依赖项,则表示您正在使用Play服务。或者,您可能具有来自其他人的依赖项,这些依赖项反过来使用Play服务依赖项。 - CommonsWare
1
Play服务一直记录着各种信息,包括许多它们处理的内部异常。除非你的应用程序崩溃了,否则不必担心这些异常。 - CommonsWare
我是一个简单的人 - 我看到@CommonsWare的答案就直接去做了 - nibbana
显示剩余5条评论
1个回答

11

正如@CommonsWare在上面的评论中建议的那样,这里观察到的异常是由Play服务记录的,这很常见,并不是应用程序的后果。 除非这些异常导致了严重的问题(比如应用程序崩溃),否则就不应该将这些异常视为痛点。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接