前台服务在通知点击后被杀死

5
在Android 4.4.2上,点击我的前台服务通知会杀死我的进程。
在旧设备上(运行4.2.2的Samsuing Tab 2),我可以从“最近使用的任务”中向左滑动Activity,并且仍然可以在后台正常运行我的Service。然后,当我点击Notification时,我的应用程序Activity会非常愉快地重新启动。
然而,一旦我在运行4.4.2的Nexus 7上点击通知,我的进程就被杀死了(直到点击之前一直在后台运行)。 PendingIntent似乎根本没有触发,或者至少没有触发BroadcastReceiver的第一行:
05-21 16:17:38.939: I/ActivityManager(522): Killing 2268:com.test.student/u0a242 (adj 0): remove task

我已经阅读了this的答案,并使用命令dumpsys activity proccesses确认我的服务正在正确地在前台运行。

那么,是什么导致点击此通知会终止我的进程?

涉及将服务移至前台的代码如下:

服务:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("NativeWrappingService", "Starting Service...");
    startForeground(NotificationIcon.NOTIFICATION_STUDENT, NotificationManager.getStudentIcon(this).getNotification());    
    return super.onStartCommand(intent, flags, startId);
}

通知图标:(getStudentIcon(this).getNotification())

public Notification getNotification() {
    Builder mBuilder = new Builder(mContext);

    if(mSmallIcon   != -1)      mBuilder.setSmallIcon(mSmallIcon);
    if(mLargeIcon   != null)    mBuilder.setLargeIcon(mLargeIcon);
    if(mTitle       != null)    mBuilder.setContentTitle(mTitle);
    if(mSubTitle    != null)    mBuilder.setContentText(mSubTitle);
    if(mSubTitleExtra != null)  mBuilder.setContentInfo(mSubTitleExtra);

    mBuilder.setOngoing(mOngoing);
    mBuilder.setAutoCancel(mAutoCancel);
    mBuilder.setContentIntent(getPendingIntent(mContext, mAction, mBundle, mActivity));

    return mBuilder.build();
}

private PendingIntent getPendingIntent(Context context, String action, Bundle extras, String activity) {
    Intent newIntent = new Intent(context, BroadcastToOrderedBroadcast.class);
    Bundle bundle;
    if(extras != null)  bundle = extras;
    else                bundle = new Bundle();

    if(activity != null && !activity.equalsIgnoreCase("")) {
        BundleUtils.addActivityToBundle(bundle, activity);
    }

    BundleUtils.addActionToBundle(bundle, action);

    newIntent.putExtras(bundle);

    return PendingIntent.getBroadcast(NativeService.getInstance(), mNotificationID, newIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}

这是一个已知的 bug,正在此处进行跟踪。你可以尝试在评论 #7中列出的解决方案。 - Manish Mulimani
1个回答

4

在您的通知中使用PendingIntent时,添加 FLAG_RECEIVER_FOREGROUND标志,以允许Service以前台优先级运行。

Intent newIntent = new Intent(context, BroadcastToOrderedBroadcast.class);
newIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
return PendingIntent.getBroadcast(NativeService.getInstance(), mNotificationID, newIntent, PendingIntent.FLAG_UPDATE_CURRENT);

这里是信息来源:Android问题跟踪器工具

这不是等同于FLAG_ACTIVITY_NEW_TASK吗?它们都是0x10000000,你能支持一下我可以设置FLAG_RECEIVER_FOREGROUND的参考吗? - Boris Treukhov
@Manish Mulimani,我已经研究了您的建议。 当我的应用程序关闭后,如果我点击通知,则我的服务会重新启动。同时广播接收器也无法工作? - Himanshu Mori

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