android service START_STICKY START_NOT_STICKY

╄→гoц情女王★ 提交于 2019-12-06 06:22:15

问题


I need to keep my service always running in background. And starting my service with "startService()" function. I don't want to restart service whatever is Application's state.

Here is my observations.

START_STICKY > if application starts , service is restarting. And service is restarting itself when application closes , too.

START_NOT_STICK > service doesn't work after application closed.

I need a service which always running , and it will receive broadcast when application starts. Services status musn't depend if application is running or not.

Can you help me ?

Thanks.


回答1:


you will want to set a BOOT receiver which starts your Service ALARM (which will wake up intermittently and make sure your Service is running) when the device boots. The ALARM receiver should wakes up every minute (or so) to see that your Service hasn't been cleaned up by Android (which will happen from time to time).

[EDIT]

You'll want a BootReceiver to start your alarm that will look like this:

public class BootReceiver extends BroadcastReceiver {
    @Override
       public void onReceive(Context context, Intent intent) {

          AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
          PendingIntent pendingIntent =
                   PendingIntent.getBroadcast(context, 0, new Intent(context, AlarmReceiver.class), 0);

          alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 2000,  60000, pendingIntent);
       }
    }

And an alarmReceiver would look like this:

public class AlarmReceiver extends BroadcastReceiver {
    private String TAG = "AlarmReceiver";
   // onReceive must be very quick and not block, so it just fires up a Service
   @Override
   public void onReceive(Context context, Intent intent) {     
      Intent i = new Intent(context, MyLovelyService.class);      
      PendingIntent.getService(context, 0,i, 0).send();    
   }
}

and lastly this needs to go into your manifest:

<receiver android:name=".BootReceiver">
  <intent-filter>
     <action android:name="android.intent.action.BOOT_COMPLETED" />
  </intent-filter>
 </receiver>

 <receiver android:name=".AlarmReceiver" />


来源:https://stackoverflow.com/questions/18387346/android-service-start-sticky-start-not-sticky

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!