Android keep BroadcastReceiver in background

后端 未结 2 1058
猫巷女王i
猫巷女王i 2020-12-10 17:33

I created a BroadcastReceiver and it runs only when my app shown in recent apps menu. If I remove my app from the recent apps the BroadcastReceiver will stop working. How ca

2条回答
  •  时光说笑
    2020-12-10 18:13

    Use a service with it. Services can survive when the app dies if they have the right flag example:

    public class MyService extends Service {
        public int onStartCommand(Intent intent, int flags, int startId) {
            return START_STICKY; //this defines this service to stay alive
        }
    @Override
    public void onCreate() {
        super.onCreate();
    
        appStatus = APPISUP;
    
        //This is a thread that stays alive for as long as you need
        new CheckActivityStatus().execute();
        //Not needed but in case you wish to lauch other apps from it
    }
    
    private class CheckActivityStatus extends AsyncTask {
     @Override
        protected String doInBackground(String... params) {
            while(true) {
            ... //add something that breaks eventually
            }
        }
     }
    

    To lauch the service you have to lauch it from an activity like so:

    Intent service = new Intent(getBaseContext(), MyService.class);
        startService(service);
    

    With the service the BroadcastReceiver still functions receiving whatever you want. Note that the service sometimes stops and comes back. I haven't found out why but I'm betting on priorities of other apps that may ask the system to halt the service

提交回复
热议问题