报错:Context.startForegroundService() did not then call Service.startForeground?

原文链接: https://blog.csdn.net/sinat_20059415/article/details/80584487

前言:最近在处理Android O的应用crash和anr问题,其中遇到比较多的就是“Context.startForegroundService() did not then call Service.startForeground()”,将自己的处理心得总结回顾一下。

 

demo:https://github.com/happyjiatai/demo_csdn/tree/master/demo_42_startforegroundservice

-------------------------------------------------------6月21日更新------------------------------------------------------

PS:我比较注重报错及解决,有愿意看代码弄清代码层次的前因后果的下面这篇写的很好

https://blog.csdn.net/lylddinghffw/article/details/80366791

-------------------------------------------------------6月21日更新------------------------------------------------------

 

1.报错堆栈

startForegroundService相关报错堆栈分为两种:

1)

  1. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: FATAL EXCEPTION: main
  2. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: Process: packageName,,,,,,,,,,,,,,,,,,,,,,,,, PID: 3986
  3. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: java.lang.RuntimeException: java.lang.IllegalStateException: Not allowed to start service Intent { flg=0x1000000 cmp=packagename/.servicename (has extras) }: app is in background uid UidRecord{52db80 u2357s1000 TRNB bg:+2m42s199ms idle procs:3 seq(0,0,0)}
  4. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:112)
  5. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:106)
  6. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.os.Looper.loop(Looper.java:168)
  7. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6555)
  8. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
  9. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
  10. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)
  11. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { flg=0x1000000 cmp=packagename/.servicename (has extras) }: app is in background uid UidRecord{52db80 u2357s1000 TRNB bg:+2m42s199ms idle procs:3 seq(0,0,0)}
  12. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1522)
  13. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.ContextImpl.startService(ContextImpl.java:1478)
  14. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.content.ContextWrapper.startService(ContextWrapper.java:661)
  15. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at packageName.ConnectionChangeJobService.onStartJob(ConnectionChangeJobService.java:102)
  16. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.job.JobService$1.onStartJob(JobService.java:71)
  17. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:108)
  18. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: ... 6 more

 

2)

 

  1. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: Process: packagename, PID: 13768
  2. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
  3. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1803)
  4. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:106)
  5. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: at android.os.Looper.loop(Looper.java:168)
  6. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6555)
  7. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
  8. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
  9. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)

 

在解决问题之前先打一下基础,看一下Android O对后台的限制。

 

 

2.Android O 后台执行限制

2.1 后台执行限制

Android 8.0 为提高电池续航时间而引入的变更之一是,当您的应用进入已缓存状态时,如果没有活动的组件,系统将解除应用具有的所有唤醒锁。

此外,为提高设备性能,系统会限制未在前台运行的应用的某些行为。具体而言:

现在,在后台运行的应用对后台服务的访问受到限制。
应用无法使用其清单注册大部分隐式广播(即,并非专门针对此应用的广播)。
默认情况下,这些限制仅适用于针对 O 的应用。不过,用户可以从 Settings 屏幕为任意应用启用这些限制,即使应用并不是以 O 为目标平台。

Android 8.0 还对特定函数做出了以下变更:


如果针对 Android 8.0 的应用尝试在不允许其创建后台服务的情况下使用 startService() 函数,则该函数将引发一个 IllegalStateException。(对应于堆栈一的报错)

 

新的 Context.startForegroundService() 函数将启动一个前台服务。现在,即使应用在后台运行,系统也允许其调用 Context.startForegroundService()。不过,应用必须在创建服务后的五秒内调用该服务的 startForeground() 函数。(对应于堆栈二的报错,需要补充)

 

 

2.2 后台服务限制

在后台中运行的服务会消耗设备资源,这可能降低用户体验。 为了缓解这一问题,系统对这些服务施加了一些限制。

系统可以区分 前台 和 后台 应用。 (用于服务限制目的的后台定义与内存管理使用的定义不同;一个应用按照内存管理的定义可能处于后台,但按照能够启动服务的定义又处于前台。)如果满足以下任意条件,应用将被视为处于前台:
 

  • 具有可见 Activity(不管该 Activity 已启动还是已暂停)。
  • 具有前台服务。
  • 另一个前台应用已关联到该应用(不管是通过绑定到其中一个服务,还是通过使用其中一个内容提供程序)。 例如,如果另一个应用绑定到该应用的服务,那么该应用处于前台:


    IME
    壁纸服务
    通知侦听器
    语音或文本服务
    如果以上条件均不满足,应用将被视为处于后台。

绑定服务不受影响
这些规则不会对绑定服务产生任何影响。 如果您的应用定义了绑定服务,则不管应用是否处于前台,其他组件都可以绑定到该服务。

处于前台时,应用可以自由创建和运行前台服务与后台服务。 进入后台时,在一个持续数分钟的时间窗内,应用仍可以创建和使用服务。

在该时间窗结束后,应用将被视为处于 空闲 状态。 此时,系统将停止应用的后台服务,就像应用已经调用服务的“Service.stopSelf()”方法。

在这些情况下,后台应用将被置于一个临时白名单中并持续数分钟。 位于白名单中时,应用可以无限制地启动服务,并且其后台服务也可以运行。

处理对用户可见的任务时,应用将被置于白名单中,例如:

处理一条高优先级 Firebase 云消息传递 (FCM) 消息。

接收广播,例如短信/彩信消息。

从通知执行 PendingIntent。

在很多情况下,您的应用都可以使用 JobScheduler 作业替换后台服务。 例如,CoolPhotoApp 需要检查用户是否已经从朋友那里收到共享的照片,即使该应用未在前台运行。

之前,应用使用一种会检查其云存储的后台服务。 为了迁移到 Android 8.0,开发者使用一个计划作业替换了这种后台服务,该作业将按一定周期启动,查询服务器,然后退出。

在 Android 8.0 之前,创建前台服务的方式通常是先创建一个后台服务,然后将该服务推到前台。

Android 8.0 有一项复杂功能;系统不允许后台应用创建后台服务。 因此,Android 8.0 引入了一种全新的方法,即 Context.startForegroundService(),以在前台启动新服务。

在系统创建服务后,应用有五秒的时间来调用该服务的 startForeground() 方法以显示新服务的用户可见通知。
 

如果应用在此时间限制内未调用 startForeground(),则系统将停止服务并声明此应用为 ANR。

 

3. 报错解决方案

3.1 堆栈一报错解决方案

将 调用 startService启动Service 改为调用 startForegroundService,这只是第一步,后续步骤请参考堆栈二报错解决方案。

 

  1. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: FATAL EXCEPTION: main
  2. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: Process: packageName,,,,,,,,,,,,,,,,,,,,,,,,, PID: 3986
  3. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: java.lang.RuntimeException: java.lang.IllegalStateException: Not allowed to start service Intent { flg=0x1000000 cmp=packagename/.servicename (has extras) }: app is in background uid UidRecord{52db80 u2357s1000 TRNB bg:+2m42s199ms idle procs:3 seq(0,0,0)}
  4. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:112)
  5. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:106)
  6. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.os.Looper.loop(Looper.java:168)
  7. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6555)
  8. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
  9. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
  10. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)
  11. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { flg=0x1000000 cmp=com.mediatek.providers.drm/.DrmSyncTimeService (has extras) }: app is in background uid UidRecord{52db80 u2357s1000 TRNB bg:+2m42s199ms idle procs:3 seq(0,0,0)}
  12. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1522)
  13. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.ContextImpl.startService(ContextImpl.java:1478)
  14. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.content.ContextWrapper.startService(ContextWrapper.java:661)
  15. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at com.mediatek.providers.drm.ConnectionChangeJobService.onStartJob(ConnectionChangeJobService.java:102)
  16. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.job.JobService$1.onStartJob(JobService.java:71)
  17. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:108)
  18. 05-28 17:49:49.693516 3986 3986 E AndroidRuntime: ... 6 more

 

3.2 堆栈二报错解决方案

 

堆栈二简单来看就是调用了startForegroundService后需要在Service里继续调用Service.startForeground()即可,但有种情况是即使调用了还是报一样的错。

 

  1. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: Process: packagename, PID: 13768
  2. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
  3. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1803)
  4. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:106)
  5. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: at android.os.Looper.loop(Looper.java:168)
  6. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6555)
  7. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
  8. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
  9. 06-11 15:48:15.602772 13768 13768 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)

如果认真debug,会发现Service启动的时候不会报错,在Service.stopSelf的时候报错,并且catch不到异常。5s内不停止服务还会有anr问题。

原因:

看下面的代码,有种豁然开朗学到什么东西的感觉,但是Google把这条路封掉了,Google本意就是让没有可见通知的应用不可以偷偷启动服务在后台干着见不得人的事,怎么可能留下后门。

  1. Notification notification = new Notification.Builder(mContext).build();
  2. startForeground(0, notification);
  3. * @param id The identifier for this notification as per
  4. * {@link NotificationManager#notify(int, Notification)
  5. * NotificationManager.notify(int, Notification)}; must not be 0.
  6. * @param notification The Notification to be displayed.
  7. *
  8. * @see #stopForeground(boolean)
  9. */
  10. public final void startForeground(int id, Notification notification) {

结合Service的startForeground api,其中重点强调了must not be 0,即禁止是0,既然使用了0,就不要怪Google让应用crash了。但是是在Service.stopSelf时crash,代码分析见后文框架修改解决方案。

 

3.2.1 正统解决方案

正统解决方案肯定是Google让怎么做就怎么做呀,Google让新建一个通知那就新建一个通知。

写了一个demo,包含正确方式(btn1)和错误方式(btn2)

activity:

  1. package com.example.demo_42_startforegroundservice;
  2. import android.content.Intent;
  3. import android.support.v7.app.AppCompatActivity;
  4. import android.os.Bundle;
  5. import android.util.Log;
  6. import android.view.View;
  7. import android.widget.Button;
  8. public class MainActivity extends AppCompatActivity {
  9. private static final String TAG = "jiatai";
  10. @Override
  11. protected void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.activity_main);
  14. Button btn = findViewById(R.id.btn);
  15. Button btn2 = findViewById(R.id.btn2);
  16. btn.setOnClickListener(new View.OnClickListener() {
  17. @Override
  18. public void onClick(View v) {
  19. Log.d(TAG, "start service");
  20. Intent intent = new Intent(MainActivity.this,MyService.class);
  21. intent.putExtra("type",1);
  22. startForegroundService(intent);
  23. }
  24. });
  25. btn2.setOnClickListener(new View.OnClickListener() {
  26. @Override
  27. public void onClick(View v) {
  28. Log.d(TAG, "start service");
  29. Intent intent = new Intent(MainActivity.this,MyService.class);
  30. intent.putExtra("type",2);
  31. startForegroundService(intent);
  32. }
  33. });
  34. }
  35. }

Service:

  1. package com.example.demo_42_startforegroundservice;
  2. import android.app.Notification;
  3. import android.app.NotificationChannel;
  4. import android.app.NotificationManager;
  5. import android.app.Service;
  6. import android.content.Context;
  7. import android.content.Intent;
  8. import android.graphics.Color;
  9. import android.os.Handler;
  10. import android.os.IBinder;
  11. import android.os.Message;
  12. import android.util.Log;
  13. import android.widget.Toast;
  14. public class MyService extends Service {
  15. private static final String TAG = "jiatai";
  16. private MyHandler handler;
  17. public MyService() {
  18. }
  19. @Override
  20. public IBinder onBind(Intent intent) {
  21. // TODO: Return the communication channel to the service.
  22. throw new UnsupportedOperationException("Not yet implemented");
  23. }
  24. @Override
  25. public void onCreate() {
  26. super.onCreate();
  27. Log.d(TAG, "service oncreate");
  28. handler = new MyHandler();
  29. }
  30. @Override
  31. public int onStartCommand(Intent intent, int flags, final int startId) {
  32. int type = intent.getIntExtra("type",1);
  33. Log.d(TAG, "the create notification type is " + type + "----" + (type == 1 ? "true" : "false"));
  34. if(type == 1){
  35. createNotificationChannel();
  36. }else{
  37. createErrorNotification();
  38. }
  39. new Thread(){
  40. @Override
  41. public void run() {
  42. super.run();
  43. try {
  44. Thread.sleep(5000);
  45. } catch (InterruptedException e) {
  46. e.printStackTrace();
  47. }
  48. handler.sendEmptyMessage(startId);
  49. }
  50. }.start();
  51. return super.onStartCommand(intent, flags, startId);
  52. }
  53. private void createErrorNotification() {
  54. Notification notification = new Notification.Builder(this).build();
  55. startForeground(0, notification);
  56. }
  57. private void createNotificationChannel() {
  58. NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  59. // 通知渠道的id
  60. String id = "my_channel_01";
  61. // 用户可以看到的通知渠道的名字.
  62. CharSequence name = getString(R.string.channel_name);
  63. // 用户可以看到的通知渠道的描述
  64. String description = getString(R.string.channel_description);
  65. int importance = NotificationManager.IMPORTANCE_HIGH;
  66. NotificationChannel mChannel = new NotificationChannel(id, name, importance);
  67. // 配置通知渠道的属性
  68. mChannel.setDescription(description);
  69. // 设置通知出现时的闪灯(如果 android 设备支持的话)
  70. mChannel.enableLights(true); mChannel.setLightColor(Color.RED);
  71. // 设置通知出现时的震动(如果 android 设备支持的话)
  72. mChannel.enableVibration(true);
  73. mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
  74. // 最后在notificationmanager中创建该通知渠道 //
  75. mNotificationManager.createNotificationChannel(mChannel);
  76. // 为该通知设置一个id
  77. int notifyID = 1;
  78. // 通知渠道的id
  79. String CHANNEL_ID = "my_channel_01";
  80. // Create a notification and set the notification channel.
  81. Notification notification = new Notification.Builder(this)
  82. .setContentTitle("New Message") .setContentText("You've received new messages.")
  83. .setSmallIcon(R.drawable.ic_launcher_foreground)
  84. .setChannelId(CHANNEL_ID)
  85. .build();
  86. startForeground(1,notification);
  87. }
  88. private class MyHandler extends Handler{
  89. @Override
  90. public void handleMessage(Message msg) {
  91. super.handleMessage(msg);
  92. stopSelf(msg.what);
  93. }
  94. }
  95. @Override
  96. public void onDestroy() {
  97. super.onDestroy();
  98. Log.d(TAG, "5s onDestroy");
  99. Toast.makeText(this, "this service destroy", 1).show();
  100. stopForeground(true);
  101. }
  102. }

效果图:

贴一下btn2 报错堆栈:

 

  1. 06-16 09:52:12.109 783-907/system_process I/AnrManager: ANR in com.example.demo_42_startforegroundservice, time=689836
  2. Reason: Context.startForegroundService() did not then call Service.startForeground()
  3. Load: 10.13 / 9.55 / 5.83
  4. Android time :[2018-06-16 09:52:12.10] [694.364]
  1. --------- beginning of crash
  2. 06-16 09:52:12.132 7015-7015/com.example.demo_42_startforegroundservice E/AndroidRuntime: FATAL EXCEPTION: main
  3. Process: com.example.demo_42_startforegroundservice, PID: 7015
  4. android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
  5. at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1803)
  6. at android.os.Handler.dispatchMessage(Handler.java:106)
  7. at android.os.Looper.loop(Looper.java:168)
  8. at android.app.ActivityThread.main(ActivityThread.java:6555)
  9. at java.lang.reflect.Method.invoke(Native Method)
  10. at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
  11. at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)

 

Google有点狠,crash+anr来了个全套,anr其实是我将Service延迟到了5s做完导致的,5s内如果没有正统的调用startForeground就会anr。

 

 

PS: 网上所传的notification隐藏是否可以?

有的需求是启动服务,但是又不想有通知,这和Google定的规则有冲突呀,有没有什么办法呢?网上2年前的方案是启动两个Service,一个Service干活,另外一个Service把通知隐藏掉。

Android O Google应该考虑到这个漏洞了:

  1. private void cancelForegroundNotificationLocked(ServiceRecord r) {
  2. if (r.foregroundId != 0) {
  3. // First check to see if this app has any other active foreground services
  4. // with the same notification ID. If so, we shouldn't actually cancel it,
  5. // because that would wipe away the notification that still needs to be shown
  6. // due the other service.
  7. ServiceMap sm = getServiceMapLocked(r.userId);
  8. if (sm != null) {
  9. for (int i = sm.mServicesByName.size()-1; i >= 0; i--) {
  10. ServiceRecord other = sm.mServicesByName.valueAt(i);
  11. if (other != r && other.foregroundId == r.foregroundId
  12. && other.packageName.equals(r.packageName)) {
  13. // Found one! Abort the cancel.
  14. return;
  15. }
  16. }
  17. }
  18. r.cancelNotification();
  19. }
  20. }

如果前台服务的通知还有被占用,那就别想用其他服务把它干掉了。

 

3.2.2 框架规避方案

修改方案(仅供参考):ActiveServices.java如下加一个packageName的crash的规避,anr同理,发出消息的地方可以修改为不发出timeout消息,也可以在startForeground的时候就移除。(如果Service耗时小于5s,Service在stop流程的时候会将anr消息移除,可不修改)

  1. // Check to see if the service had been started as foreground, but being
  2. // brought down before actually showing a notification. That is not allowed.
  3. if (r.fgRequired) {
  4. Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
  5. + r);
  6. r.fgRequired = false;
  7. r.fgWaiting = false;
  8. mAm.mHandler.removeMessages(
  9. ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
  10. if (r.app != null && !"packageName".equals(r.packageName)) {
  11. Message msg = mAm.mHandler.obtainMessage(
  12. ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
  13. msg.obj = r.app;
  14. mAm.mHandler.sendMessage(msg);
  15. }
  16. }

 

 

 

修改原理:

编译一个service.jar,打印报错堆栈

  1. 01-01 07:02:17.669 918 1334 W ActivityManager: Bringing down service while still waiting for start foreground: ServiceRecord{2d44a2d u0 packageName/.servicename}
  2. 01-01 07:02:17.669 918 1334 W ActivityManager: java.lang.Throwable
  3. 01-01 07:02:17.669 918 1334 W ActivityManager: at com.android.server.am.ActiveServices.bringDownServiceLocked(ActiveServices.java:2612)
  4. 01-01 07:02:17.669 918 1334 W ActivityManager: at com.android.server.am.ActiveServices.bringDownServiceIfNeededLocked(ActiveServices.java:2559)
  5. 01-01 07:02:17.669 918 1334 W ActivityManager: at com.android.server.am.ActiveServices.stopServiceTokenLocked(ActiveServices.java:792)
  6. 01-01 07:02:17.669 918 1334 W ActivityManager: at com.android.server.am.ActivityManagerService.stopServiceToken(ActivityManagerService.java:18789)
  7. 01-01 07:02:17.669 918 1334 W ActivityManager: at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:759)
  8. 01-01 07:02:17.669 918 1334 W ActivityManager: at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3080)
  9. 01-01 07:02:17.669 918 1334 W ActivityManager: at android.os.Binder.execTransact(Binder.java:697)

找到对应抛出Context.startForegroundService() did not then call Service.startForeground()的逻辑代码:

ActiveServices.java bringDownServiceLocked

  1. // Check to see if the service had been started as foreground, but being
  2. // brought down before actually showing a notification. That is not allowed.
  3. if (r.fgRequired) {
  4. Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
  5. + r);
  6. r.fgRequired = false;
  7. r.fgWaiting = false;
  8. mAm.mHandler.removeMessages(
  9. ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
  10. if (r.app != null) {
  11. Message msg = mAm.mHandler.obtainMessage(
  12. ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
  13. msg.obj = r.app;
  14. mAm.mHandler.sendMessage(msg);
  15. }
  16. }

走到这里面继而会由ams发出一个service_foreground_crash_msg的消息,导致crash。

至于为嘛会走到这里呢,都是id = 0 的过,既没有走前台服务的流程也没有将r.fgRequired设为false,anr的msg也没有移除掉。

  1. private void setServiceForegroundInnerLocked(ServiceRecord r, int id,
  2. Notification notification, int flags) {
  3. if (id != 0) {
  4. if (notification == null) {
  5. throw new IllegalArgumentException("null notification");
  6. }
  7. // Instant apps need permission to create foreground services.
  8. ...
  9. if (r.fgRequired) {
  10. if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
  11. Slog.i(TAG, "Service called startForeground() as required: " + r);
  12. }
  13. r.fgRequired = false;
  14. r.fgWaiting = false;
  15. mAm.mHandler.removeMessages(
  16. ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
  17. }
  18. if (r.foregroundId != id) {
  19. cancelForegroundNotificationLocked(r);
  20. r.foregroundId = id;
  21. }
  22. notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
  23. r.foregroundNoti = notification;
  24. if (!r.isForeground) {
  25. final ServiceMap smap = getServiceMapLocked(r.userId);
  26. if (smap != null) {
  27. ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
  28. if (active == null) {
  29. active = new ActiveForegroundApp();
  30. active.mPackageName = r.packageName;
  31. active.mUid = r.appInfo.uid;
  32. active.mShownWhileScreenOn = mScreenOn;
  33. if (r.app != null) {
  34. active.mAppOnTop = active.mShownWhileTop =
  35. r.app.uidRecord.curProcState
  36. <= ActivityManager.PROCESS_STATE_TOP;
  37. }
  38. active.mStartTime = active.mStartVisibleTime
  39. = SystemClock.elapsedRealtime();
  40. smap.mActiveForegroundApps.put(r.packageName, active);
  41. requestUpdateActiveForegroundAppsLocked(smap, 0);
  42. }
  43. active.mNumActive++;
  44. }
  45. r.isForeground = true;
  46. }
  47. r.postNotification();
  48. if (r.app != null) {
  49. updateServiceForegroundLocked(r.app, true);
  50. }
  51. getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
  52. mAm.notifyPackageUse(r.serviceInfo.packageName,
  53. PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
  54. } else {
  55. if (r.isForeground) {
  56. final ServiceMap smap = getServiceMapLocked(r.userId);
  57. if (smap != null) {
  58. decActiveForegroundAppLocked(smap, r);
  59. }
  60. r.isForeground = false;
  61. if (r.app != null) {
  62. mAm.updateLruProcessLocked(r.app, false, null);
  63. updateServiceForegroundLocked(r.app, true);
  64. }
  65. }
  66. if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
  67. cancelForegroundNotificationLocked(r);
  68. r.foregroundId = 0;
  69. r.foregroundNoti = null;
  70. } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
  71. r.stripForegroundServiceFlagFromNotification();
  72. if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
  73. r.foregroundId = 0;
  74. r.foregroundNoti = null;
  75. }
  76. }
  77. }
  78. }

anr的时限为嘛是5s呢?

  1. void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
  2. if (r.app.executingServices.size() == 0 || r.app.thread == null) {
  3. return;
  4. }
  5. Message msg = mAm.mHandler.obtainMessage(
  6. ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
  7. msg.obj = r;
  8. r.fgWaiting = true;
  9. mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
  10. }
  11. // How long the startForegroundService() grace period is to get around to
  12. // calling startForeground() before we ANR + stop it.
  13. static final int SERVICE_START_FOREGROUND_TIMEOUT = 5*1000;

这种timeout流程就很熟悉了。

 

4. 总结

Android O 后台应用想启动服务就老老实实的加个notification给用户看,表示你自己在后台占着资源,杀不杀由用户决定,偷偷地在后台跑没有framework帮忙想都别想,一个anr+crash套餐了解一下。

1)activity: Context.startForegroundService()

2)Service:startForeground(int id, Notification notification)(id must not be 0)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章