// register intent time tick receiver which ticks every minute registerReceiver(timeTickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
/** * restart service every minute if it's killed */ private BroadcastReceiver timeTickReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { try { boolean isServiceRunning = false; if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) { ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE); if (manager != null) { for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if ("net.pupli.monitoring.MyMqttService".equals(service.service.getClassName())) { isServiceRunning = true; } } } if (!isServiceRunning) { Intent i = new Intent(context, MyMqttService.class); context.startService(i); } } } catch (Exception ex) { ex.printStackTrace(); } } };
References
https://llin233.github.io/2015/11/16/How-to-prevent-service/
https://developer.android.com/reference/android/content/Intent#action_time_tick
https://medium.com/google-developers/who-lives-and-who-dies-process-priorities-on-android-cb151f39044f
http://sourabhsoni.com/how-to-use-intent-action_time_tick/