Android 前台服务始终抛出“java.lang.IllegalArgumentException:服务未注册”异常

2023-11-26

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

构建.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);
    }
}

该应用程序按预期工作,前台服务运行良好,即使在应用程序被销毁后也能正常执行其预期的操作,但我始终看到Warning as an 非法参数异常运行应用程序时。例外情况附在下面:

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@[email protected] (100700-0):1)
       at ce.a(:com.google.android.gms.dynamite_measurementdynamite@[email protected] (100700-0):5)
       at lm.A(:com.google.android.gms.dynamite_measurementdynamite@[email protected] (100700-0):10)
       at kx.a(:com.google.android.gms.dynamite_measurementdynamite@[email protected] (100700-0):3)
       at dx.run(:com.google.android.gms.dynamite_measurementdynamite@[email protected] (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@[email protected] (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. 

有人可以帮我理解为什么总是抛出这个异常以及如何解决这个问题吗?


正如 @CommonsWare 在上面的评论中所建议的,这里观察到的异常是由 Play Services 记录的,这很常见,并不是应用程序的结果。 除非异常导致严重问题(例如应用程序崩溃),否则不应将此类异常视为痛点。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android 前台服务始终抛出“java.lang.IllegalArgumentException:服务未注册”异常 的相关文章

随机推荐

  • 订阅 WCF 服务中的事件

    我需要对 WCF 服务的功能进行一些实时报告 该服务在 Windows 应用程序中自托管 我的要求是当客户端调用某些方法时向主机应用程序报告 实时 我对该任务的最初想法是在服务代码中发布 NotifyNow 事件 并在我的调用应用程序中订阅
  • 如何备份sqlite数据库?

    正确的做法是什么 我只复制 sq3 文件吗 如果网站上有用户并且文件在复制时正在写入怎么办 sqlite3 命令行工具具有以下功能 backup点命令 您可以通过以下方式连接到您的数据库 sqlite3 my database sq3 并运
  • C# 中的 [Serialized] 和 [Serialized()] 之间有区别吗?

    我遇到过使用这两种表示法的示例 我找不到任何关于它的信息来说明哪一个是常见的 为什么允许使用两种符号 以及两者之间是否确实存在任何细微的差异 有人有主意吗 不 没有功能差异 你问为什么有两种不同的风格 为了简洁起见 允许使用第一个符号 允许
  • Lastpass 如何知道 Chrome 中当前的 URL

    在 Android 版 Chrome 中浏览时 如果 Lastpass 将 URL 识别为与您关联的登录详细信息 则会弹出建议 它如何知道 Chrome 正在查看哪个 URL 我知道 Lastpass 使用无障碍服务 但我想知道它如何从 C
  • google.protobuf.Empty 对于向后兼容性有危险吗?

    The spec for google protobuf Empty states 可以重复使用的通用空消息 以避免定义重复 API 中的空消息 一个典型的例子就是用它作为请求 或 API 方法的响应类型 我一直在内部提倡使用空消息包装器来
  • C++ 字符串文字的安全性和可靠性如何?

    所以 我想更好地掌握 C 中的字符串文字是如何工作的 我最关心的是您将字符串文字的地址分配给指针并传递它的情况 例如 char advice Don t stick your hands in the toaster 现在假设我只是在程序运
  • React router v6 如何在 axios 拦截器中使用“navigate”重定向

    import axios from axios import useNavigate from react router dom export const api axios create baseURL http 127 0 0 1 80
  • 如何生成每个点之间距离最小的 3 维随机点?

    我将在 matlab 中用这个特定字符生成 10 6 个随机点 这些点应该位于半径为 25 的球体内部 它们是 3 D 的 因此我们有 x y z 或 r theta phi 每个点之间有一个最小距离 首先 我决定生成点 然后检查距离 然后
  • each() 方法中的 jQuery 选择器

    假设我有一个如下所示的 HTML div class aaa span 1 span div div class aaa span 2 span div div class aaa span 3 span div div class aaa
  • WPF-Window Topmost 仅适用于自己的应用程序?

    我的 WPF 应用程序中的启动屏幕 加载窗口设置为最上面 真 现在 即使您切换到另一个应用程序 该窗口也会位于所有其他窗口之上 因为加载需要一些时间 我不想要这种行为 如果我设置最上面 假 窗口根本不在最上面 但是 如果您在使用另一个应用程
  • 从小部件刷新显示?

    我正在尝试通过小部件设置屏幕亮度 我们知道这很容易实现 因为大量的小部件已经做到了这一点 但是如何 在我从小部件调用的服务中 我这样做是为了设置亮度 Settings System putInt this getContentResolve
  • Visual Studio Code $psise 等价物

    我正在寻找一种在 VSCode 中复制 psISE 功能的方法 至少在编辑器中发现打开的活动文件的文件名 作为背景 我正在尝试迁移到使用 VSCode 进行 powershell 编辑而不是 ISE 因为 VSCode 是未来 我们在迁移某
  • 执行子进程失败

    我尝试通过 Python 调用带有多个参数的进程 执行批处理文件本身对我来说效果很好 但将其翻译成 Python 让我尖叫 这是批处理文件的内容 C Program Files bin cspybat C Program Files bin
  • 将数组作为参数传递给 JAX-RS 资源

    我有很多参数要使用 JAX RS 传递到服务器 有没有办法通过 URL 或 AarryList 来传递 您在这里有几个选择 选项 1 具有多个值的查询参数 You can为单个查询参数提供多个简单值 例如 您的查询字符串可能如下所示 PUT
  • Django 如何在类上而不是函数上使用“receiver”装饰器

    使用 Django 信号receiver装饰器我有以下功能 receiver post save def action signal sender instance created kwargs pass 是否可以使用receiver类上的
  • openpyxl 单元格样式报告不正确

    使用Python库openpyxl我正在读取在 excel 2007 中创建的 XLSX 文件 除了单元格 A1 之外 它是空的 单元格 A1 为黄色 并且其中写入了值 test 我可以轻松地从该单元格检索值 但是当我尝试确定填充颜色时 我
  • 如何从另一个 Spring Boot 应用程序访问一个 Spring Boot 应用程序的内存 h2 数据库

    在我的项目中 我创建了 3 个 Spring Boot 应用程序 第一个 Spring Boot 应用程序具有 h2 嵌入式数据库 现在我想直接从我的第二个和第三个 Spring Boot 应用程序访问此数据库 而无需编写任何服务来获取此数
  • 无法创建 Android 虚拟设备

    由于某种原因 当我尝试创建 AVD 时 确定 按钮不可单击 有谁知道我做错了什么 仅仅是因为 CPU ABI 说 没有为此目标安装系统映像 您需要安装系统映像 在 Android SDK 管理器中 检查您是否已安装 ARM EABI v7a
  • 尽管数据未更改,但某些片段观察者在从返回堆栈弹出后触发

    我在 Kotlin 中的嵌套片段中遇到一些问题 我用 ViewModel 嵌套了片段 从后退按钮恢复片段后 再次按下 viewModel LiveData 触发器上的所有观察者 尽管我的数据没有更改 首先 我用谷歌搜索并尝试在归档变量中定义
  • Android 前台服务始终抛出“java.lang.IllegalArgumentException:服务未注册”异常

    我的项目需要一个android前台服务 to 连续运行 即使在应用程序被销毁之后 为此 我有以下代码片段 构建 gradle implementation fileTree dir libs include jar noinspection