前景服务在通知点击时被杀死

时间:2014-05-21 15:25:39

标签: android service android-notifications foreground-service

在Android 4.4.2中,点击我的前台服务通知会导致我的进程被终止。

在较旧的设备上(Samsuing Tab 2运行4.2.2),我可以从最近的任务中移除活动,并且仍然可以在后台运行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);
}

NotificationIcon:(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);
}

1 个答案:

答案 0 :(得分:4)

FLAG_RECEIVER_FOREGROUND标记添加到您的通知中使用的PendingIntent,以便允许服务以Foreground优先级运行。

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 Issue Tracker tool