Android系统可以停止你的服务随时当他们想停下来保持设备性能或功耗。有很多情况下,Android系统可以停止您的服务,如低电量,应用程序长时间处于活动状态,设备处于睡眠模式,省电模式等。
我开发了一个技巧或黑客(可以说)通过使用,没有人可以停止您的服务(Android系统,第三方应用程序,用户)。
注意:通过使用此服务,您的服务将永不停止,并且可能会耗尽您的电池。
按照下面的步骤: -
1)返回START_STICKY在onStartCommand。
2)然后修改的onDestroy()和onTaskRemoved()在你的服务方法如下:
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "Service Task destroyed", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(getApplicationContext(), YourService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, myIntent, 0);
AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(getApplicationContext(), "Start Alarm", Toast.LENGTH_SHORT).show();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent myIntent = new Intent(getApplicationContext(), YourService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, myIntent, 0);
AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(getApplicationContext(), "Start Alarm", Toast.LENGTH_SHORT).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Service Starts", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
这里我每天会在服务停止时间(由Android系统或由用户设置报警手动),并使用PendindIntent每次在10秒内重新启动服务。
您可以使用START_REDELIVER_INTENT而不是START_STICKY – rockstar
抱歉,但我的服务在使用后仍然会死亡。 –