How about when the system loading is not heavy? It is still possible to be killed.
Let us discuss some setting about Service:
1. The return value of onStartCommand()
START_STICKY:In the demo we shown before, we used this value.
When the Service is killed, it will be restarted if the system loading is allowed.
However, the intent passed in may be null.
If we need to get data from the intent, we'd better make some check first.
@Override public int onStartCommand(Intent intent, int flags, int startId) { if(intent != null) { String sData1=Intent.getStringExtra("DATA_KEY1"); int iData2=Intent.getIntExtra("DATA_KEY2",0); mServiceThread = new ServiceThread(); mServiceThread.start(); } else { Intent i = new Intent(xxx); sendBroadcast(i); } return START_STICKY ; }If you need these data to start the Service, you will need the mechanism sendBroadcast().
You can send a broadcast event to the Activity where you start the Service.
We can start the Service again from there and pass the necessary data at the same time.
From my experiment, the Service will be restarted about every 30 minutes (The value will be different for each device), especially when the Service is in idle status.
For example, if you create a service for network communication and when there are no any packets input, the service may be killed and then restarted soon.
You can see that in the Apps RUNNING list, the service disappears for few seconds.
START_NOT_STICKY: When the Service is killed, it is terminated directly and will not be restarted.
START_REDELIVER_INTENT: When the Service is killed, it will be restarted and pass in the last intent.
That is, the intent will not be null.
However, the system will be hung up if I use this parameter.
I am not sure the reason.
2. Adjust AndroidManifest.xml
Some people suggest that we can increase the Service priority by the following setting:
<intent-filter android:priority="1000"></intent-filter>
As experimented, the Service may restart every 60 minutes.
Some ones try to restart the Service itself in onDestroy().
However, when the Service is killed, the onDestroy() is not called always.
I didn't try this method.
Anyway, it seems that the Service will be restarted somehow.
Is there any way for prevent Service being restarted?
You may try to set the Service as Foreground Service:
Notification notification = new Notification(R.drawable.launch, "Your Application Name", System.currentTimeMillis()); Intent notificationIntent = new Intent(this, YourMainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(this, "Your Application Name", "Your Service Name", pendingIntent); startForeground(1, notification);If you set the Service as Foreground mode, you will see your defined icon in the status bar.
As experimented, the Service never restarted within few days.
沒有留言:
張貼留言