每次应用程序被杀死时重新启动服务

时间:2016-07-28 06:16:41

标签: android service background chat

我有一个在后台运行的聊天应用程序,所以当我以任何方式杀死我的应用程序时,它会从最近的应用程序中删除或在设置中杀死应用程序,我希望我的服务每次都重新启动它应该是清醒的所有的时间,直到应用程序运行。我已经尝试过广播接收器来重启我的服务。

 @Override
public void onDestroy() {
    super.onDestroy();
    Log.d("MyService", "onDestroy");

        sendBroadcast(new Intent("RestartService"));
}

我也试过onTaskRemoved

@Override
public void onTaskRemoved(Intent rootIntent) {
    Log.d(TAG, "onTaskRemoved:");

    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
            AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + 1000,
            restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
}

并且在startCommand中我有用户START_STICKY,但似乎没有任何效果。 任何有关这方面的帮助将不胜感激..

0 个答案:

没有答案
相关问题