为什么后台服务在应用关闭时停止工作?

时间:2015-11-06 11:26:41

标签: android android-service

我正在尝试创建一个每十分钟调用一次的后台服务,执行一项任务,并且在关闭应用程序时不应该杀死它。

以下是代码段:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_location_service);

    Intent intent = new Intent(this, AlarmReceiverLifeLog.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    alarms.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10 * 60 * 1000, pendingIntent);
}

onCreate中,它会每十分钟调用一次AlarmReceiverLifeLog课程。以下是AlarmReceiverLifeLog类的代码:

public class AlarmReceiverLifeLog extends BroadcastReceiver {
    static Context context;

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent ll24Service = new Intent(context, LifeLogService.class);
        context.startService(ll24Service);
    }
}

public class LifeLogService extends Service {


    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Intent restartService = new Intent(getApplicationContext(), this.getClass());
        restartService.setPackage(getPackageName());
        PendingIntent restartServicePI = PendingIntent.getService(getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT);
        Calendar calendar = Calendar.getInstance();
        AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(AlarmManager.ELAPSED_REALTIME, calendar.getTimeInMillis() + 100, restartServicePI);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

我无法弄清楚我错过了什么。当我关闭应用程序时,后台服务正在被杀死。

有人可以就此提出任何建议吗?

1 个答案:

答案 0 :(得分:0)

当应用程序关闭时,服务也会因为它们在一个线程中而关闭,所以服务应该在另一个线程上,以便它不被关闭,查看并查看保持服务处于活动状态并发出警报经理在这里举例http://www.vogella.com/articles/AndroidServices/article.html,这样您的服务就不会显示在通知中。