Android后台JobService中PendingIntent启动模式设置报错求助
解决JobService中PendingIntent后台启动Activity的模式重置问题
在Android后台JobService中尝试通过PendingIntent启动Activity并设置后台启动模式时,出现如下报错:
Resetting option setPendingIntentBackgroundActivityStartMode(1) to SYSTEM_DEFINED from the options provided by the pending intent creator (com.Myapp) because this option is meant for the pending intent sender
问题原因
setPendingIntentBackgroundActivityStartMode这个选项是给PendingIntent的发送者设置的,而非创建者。你在创建PendingIntent时传入该选项,系统会直接判定为无效并重置。
解决方案
- 创建PendingIntent时无需携带这个启动模式的Bundle
- 在调用
pendingIntent.send()方法时,将包含后台启动模式的选项Bundle作为参数传入
修正后的代码
Intent intent = new Intent(this, StreamListMainActivity.class); // 创建PendingIntent时不传入启动模式相关的options PendingIntent pendingIntent = PendingIntent.getActivity(context, 998, intent, FLAG_IMMUTABLE); try { // 在发送阶段构建并传入后台启动模式选项 ActivityOptions options = ActivityOptions.makeBasic(); options.setPendingIntentBackgroundActivityStartMode(ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED); pendingIntent.send(context, 0, null, null, null, null, options.toBundle()); } catch (PendingIntent.CanceledException e) { AppLogger.Exception(LOG_TAG, e); }
说明
PendingIntent.send()方法支持传入额外的options参数,这才是系统认可的、由发送者设置后台启动模式的正确位置。创建PendingIntent时传入的options会被系统忽略,因为该阶段无法确认发送者的上下文与权限,必须在发送动作执行时指定相关配置。
内容的提问来源于stack exchange,提问作者Pol Poggi
相关产品推荐
相关产品推荐

