当应用程序被刷掉时前台服务被杀死

时间:2014-08-23 04:48:13

标签: android service

我希望标题本身能说明我的问题是什么。

我有一个Service在前台运行。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            this);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
            new Intent(this, WidgetFlashReceiver.class)
                    .setAction(Constants.ACTION_NOTIFICATION_CLICK),
            PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setContentIntent(pendingIntent);
    builder.setOngoing(true);
    builder.setAutoCancel(false);
    builder.setContentTitle("Sample Service");
    Notification notification = builder.build();
    notification.icon = R.drawable.ic_launcher;
    notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
    startForeground(NOTIFICATION_ID, notification);
    return START_STICKY;
}

但是,当应用程序从最近的任务中删除时,即使它是前台服务,此服务也会被杀死。

感谢任何帮助。

5 个答案:

答案 0 :(得分:2)

关于Android错误的这个comment,我找到了解决这个问题的解决方案!

AlarmManager almgr = (AlarmManager)MyContext.getSystemService(Context.ALARM_SERVICE);
Intent timerIntent = new Intent(MyUniqueLabel);
timerIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
PendingIntent pendingOffLoadIntent = PendingIntent.getBroadcast(MyContext, 1, timerIntent, 0);
  

你必须做这些事情才能发挥作用。

     

1。)调用addFlags和intent并将其传递给FLAG_RECEIVER_FORGROUND

     

2。)在PendingIntent.getBroadcast

中使用非零请求代码      

如果你退出任何一个步骤,它将无效。

答案 1 :(得分:1)

Android中存在一个错误,描述了您遇到的同一问题:https://code.google.com/p/android/issues/detail?id=53313

此外,SO中有很多关于此事的信息:

Foreground service being killed by Android

Service being killed while holding wake lock and after calling startForeground

答案 2 :(得分:0)

检查您的服务以查看是否已重写onTaskRemoved()方法。确保您没有在此处调用stopSelf()方法。

答案 3 :(得分:-1)

在清单文件中添加以下代码

     <service
        android:name="com.example.service.NameOfYourService"
        android:process=":remote" >
    </service>

答案 4 :(得分:-2)

使用服务onTaskRemoved()方法。

相关问题