How to restart service in android to call service oncreate again

前端 未结 6 1501
慢半拍i
慢半拍i 2020-12-09 08:10

I have a service in my Android Application which runs always.Now i have a settings from my server through GCM and update these settings to my service. I put my settings in o

相关标签:
6条回答
  • 2020-12-09 08:21

    The best solution is to use onDestroy().

    When need to restart the service just call

    RESTARTSERVICE = true;
    stopService(new Intent(this, CLASS_OF_SERVICE.class));
    

    and

    public void onDestroy()
    {
       if (RESTARTSERVICE)
        {
           startService(new Intent(this, CLASS_OF_SERVICE.class));
        }
    }
    
    0 讨论(0)
  • 2020-12-09 08:31

    Call this two methods right after each other, which will causes the Service to stop and start. Don't know any method that "restarts" it. This is how I have implemented it in my application.

    stopService(new Intent(this, YourService.class));
    startService(new Intent(this, YourService.class));
    
    0 讨论(0)
  • 2020-12-09 08:33

    Why not move the setting stuff from onCreate to a separate method. You can then call this method from onCreate and also call it when you need to change the settings. Then there would be no need to actually restart the service.

    0 讨论(0)
  • 2020-12-09 08:36

    Just calling again startService() will start the service again if it's already running, meaning service will be restarted.

    0 讨论(0)
  • 2020-12-09 08:41

    or you can use a delayed handler to start the service. The handler will need to be declared static in a singleton, so its reference is not killed while restarting:

    serviceRestartHandler = new Handler ();
    serviceRestartHandler.postDelayed (new Runnable () {
                @Override
                public void run() {
    
                    startService (new Intent (mContext, YourWonderfulService.class)
                            .putExtra (flagName, true));
                    serviceRestartHandler.removeCallbacksAndMessages (null);
                }
            }, 1000);
            stopSelf ();
    
    0 讨论(0)
  • 2020-12-09 08:45

    Use a Method onTaskRemoved(Intent rootIntent) inside service, hence the service restarted again

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        System.out.println("service in onTaskRemoved");
        long ct = System.currentTimeMillis(); //get current time
        Intent restartService = new Intent(getApplicationContext(),
                PushService.class);
        PendingIntent restartServicePI = PendingIntent.getService(
                getApplicationContext(), 0, restartService,
                0);
    
        AlarmManager mgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        mgr.setRepeating(AlarmManager.RTC_WAKEUP, ct, 1 * 1000, restartServicePI);
    }
    
    0 讨论(0)
提交回复
热议问题