执行后台服务的最佳方法是使用系统AlarmManager 类并在每 XXX 秒后调用一次警报,但这会消耗更好的性能,但解决方案绝对适合您。
接下来的步骤,
- 创建警报
public static void setUpalarm(Context context) {
Intent intent = new Intent(context, RestartServiceFromTimer.class);
final PendingIntent pIntent = PendingIntent.getBroadcast(context , 0,
intent,0);
// Setup periodic alarm every every half hour from this point onwards
long firstMillis = System.currentTimeMillis(); // alarm is set right away
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
long delay = 5 * 1000 * 60; // time sets to 5 minute change accordingly
long time = System.currentTimeMillis() + delay;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
alarm.set(AlarmManager.RTC_WAKEUP, time, pIntent);
else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
alarm.setExact(AlarmManager.RTC_WAKEUP, time, pIntent);
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pIntent);
}
2 创建广播接收器并再次重新启动服务并再次安排警报
public class RestartServiceFromTimer extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Task Trigger","Task is triggered");
if(!isMyServiceRunning(DetectIncomonCallService.class,context.getApplicationContext()))
{ Intent myserviceIntent = new Intent(context.getApplicationContext(),Service.class);
//start your background service here
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
{
ContextCompat.startForegroundService(context.getApplicationContext(),myserviceIntent);//this is for forground service
}
else
{
context.startService(myserviceIntent);
}
}
MainActivity.setUpalarm(context.getApplicationContext());
}
private boolean isMyServiceRunning(Class<?> serviceClass,Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
3 从这样的主要活动中调用方法
setUpalarm(MainActivity.this)