Hello. There are a couple of ideas on how to do this:
- In the service (if you use it) to register, so that it loads immediately when the system starts.
- The program monitors the status of the service.
- In the program, during the call to the
OnDestroy
and OnStop
, to make it collapse.
PS The 3rd way is eating a battery hard! A piece of code I can provide, but later. If I somewhere did not speak correctly, then correct.
Code:
1) ServiceBootStart.java
public class ServiceBootStart extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) { Intent serviceLauncher = new Intent(context, ServiceExample.class); context.startService(serviceLauncher); Log.v(this.getClass().getName(), "Service loaded while device boot."); } } }
AndroidManifest.xml:
<receiver android:name=".service.ServiceBootStart" android:enabled="true" android:exported="false"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> `<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>`
2) Well, on this point, then here is how much your imagination is enough. For example, I wrote to the file the entire log of the actions of the service, then the program read at what stage the service was, on what action it stopped, where the error took off, etc. Well, then did the logic of action in certain situations (but it's all very good. Hemorrhoids). You can do it easier, just browse the list of running programs, services and compare package names with the name of your service package, and then do certain actions.
The code to check if the service works:
public boolean isServiceRunning(String serviceClassName){ ActivityManager activityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo runningServiceInfo : services) { if (runningServiceInfo.service.getClassName().equals(serviceClassName)){ return true; } } return false; }
3) The code, instead of quitting the application, just collapse it:
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {// обрабатываю нажатие на кнопку "назад" if ((keyCode == KeyEvent.KEYCODE_BACK)) { moveTaskToBack(true); return true; } return super.onKeyDown(keyCode, event); }
PS I don’t remember exactly the 3rd point, it seems to be the way it is done, there is simply no source at hand to look at.