【发布时间】:2018-06-16 05:57:48
【问题描述】:
我正在使用 Android 应用小部件。我正在创建一个PendingIntent 对象并在方法RemoteViews#setOnClickPendingIntent() 中使用它。这是待定意图:
// The below code is called in the onUpdate(Context, AppWidgetManager, int[]) method of the AppWidgetProvider class.
// Explicit intent
Intent intent = new Intent(context, MyService.class);
intent.setAction(MY_ACTION);
intent.putExtra(EXTRA_KEY, VALUE);
// Create the pending intent
PendingIntent pendingIntent = PendingIntent.getService(context, appWidgetId, intent, 0);
// 'views' is a RemoteViews object provided by onUpdate in the AppWidgetProvider class.
views.setOnClickPendingIntent(R.id.root_layout, pendingIntent);
上面的代码在 Android Oreo 之前可以正常工作。但是,在 Android Oreo 中,如果应用程序从最近浏览器中滑开,它将不再启动该服务。 (不再活动)。 PendingIntents 不是在 Oreo 的后台执行限制中吗?
出于测试目的,我将getService 替换为getForegroundService,但Service 仍未启动。两种方法都在日志中显示以下消息:
W/ActivityManager: Background start not allowed: service Intent { act=com.example.myapp.MY_ACTION flg=0x10000000 cmp=com.example.myapp/com.example.myapp.MyService bnds=[607,716][833,942] (has extras) } to com.example.myapp/com.example.myapp.MyService from pid=-1 uid=10105 pkg=com.example.myapp
为什么Service 没有启动,即使使用getForegroundService?我在运行 Android 8.1.0 的 Nexus 6P 上对此进行了测试。
【问题讨论】:
-
从
getService()切换到getForegroundService()时,您可能需要使用0以外的其他标志(例如FLAG_UPDATE_CURRENT)。 -
@CommonsWare 我刚刚尝试过,但不幸的是它没有任何区别。我用
FLAG_UPDATE_CURRENT替换了0,但仍然出现相同的日志。 -
Hmmmm...如果它不会过多地扰乱您的环境,请安装代码的
getForegroundService()版本,重新启动设备/模拟器。尽管请求更新,但感觉就像您正在获得PendingIntent的常规getService()版本。这些仅保存在 RAM 中,因此重新启动将刷新旧的PendingIntent,确保您在重新启动后获得前台服务PendingIntent。 -
@CommonsWare 非常感谢!重新启动修复了它。我现在使用带有标志
FLAG_UPDATE_CURRENT的getForegroundService。只是想知道为什么我不能使用正常的服务。我只需要发送一个大约需要 0-10 秒的网络请求。 (10 秒超时)。大多数时候它会在一秒钟内完成。为什么应用小部件的PendingIntent不在排除“白名单”中? (developer.android.com/about/versions/oreo/…)
标签: android android-widget android-service android-appwidget android-8.1-oreo