Android: Re-invoke application if task manager kill

前端 未结 5 2151
谎友^
谎友^ 2021-02-09 00:09

Application thread get close if its killed by task manager. Need to re-invoke application as though its killed by other application or task manager. Any idea?

5条回答
  •  你的背包
    2021-02-09 00:51

    While look at Google IO official product source code I have found the following

    ((AlarmManager) context.getSystemService(ALARM_SERVICE))
                .set(
                        AlarmManager.RTC,
                        System.currentTimeMillis() + jitterMillis,
                        PendingIntent.getBroadcast(
                                context,
                                0,
                                new Intent(context, TriggerSyncReceiver.class),
                                PendingIntent.FLAG_CANCEL_CURRENT));
    

    URL for code

    You can start a sticky service and register an alarm manager that will check again and again that is your application is alive if not then it will run it.

    You can also make a receiver and register it for then you can start your service from your receiver. I think there should be some broadcast message when OS or kills some service/application.

    Just to give you a rough idea I have done this and its working 1) register receiver Receiver Code:

    @Override public void onReceive(Context context, Intent intent) {

        try {
            this.mContext = context;
            startService(intent.getAction());
    
            uploadOnWifiConnected(intent);
    
        } catch (Exception ex) {
            Logger.logException(ex);
            Console.showToastDelegate(mContext, R.string.msg_service_starup_failure, Toast.LENGTH_LONG);
        }
    }
    
    private void startService(final String action) {
        if (action.equalsIgnoreCase(ACTION_BOOT)) {
    
            Util.startServiceSpawnProcessSingelton(mContext, mConnection);
    
        } else if (action.equalsIgnoreCase(ACTION_SHUTDOWN)) {
    
        }
    }
    

    Service Code:

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    
        Logger.logInfo("Service Started onStartCommand");
        return Service.START_STICKY;
    }
    

    I prefer doing nothing in onStartCommand because it will get called each time you start service but onCreate is only called 1st time service is started, so I do most of the code in onCreate, that way I don't really care about weather service is already running or not.

提交回复
热议问题