यहां पोस्ट किए गए अधिकांश समाधान एक महत्वपूर्ण टुकड़ा याद कर रहे हैं: एक जगा ताला के बिना ऐसा करने से आपकी सेवा समाप्त होने से पहले ही आपकी सेवा समाप्त होने का खतरा रहता है। एक और सूत्र में इस समाधान को देखा, यहाँ भी उत्तर दे रहा है।
WakefulBroadcastReceiver एपीआई 26 में पदावनत है क्योंकि यह 26 से नीचे एपीआई स्तर के लिए अनुशंसित है
आपको एक वेक लॉक प्राप्त करने की आवश्यकता है। सौभाग्य से, समर्थन पुस्तकालय हमें ऐसा करने के लिए एक वर्ग देता है :
public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// This is the Intent to deliver to our service.
Intent service = new Intent(context, SimpleWakefulService.class);
// Start the service, keeping the device awake while it is launching.
Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
startWakefulService(context, service);
}
}
फिर, अपनी सेवा में, वेक लॉक जारी करना सुनिश्चित करें:
@Override
protected void onHandleIntent(Intent intent) {
// At this point SimpleWakefulReceiver is still holding a wake lock
// for us. We can do whatever we need to here and then tell it that
// it can release the wakelock.
...
Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
SimpleWakefulReceiver.completeWakefulIntent(intent);
}
WAKE_LOCK अनुमति जोड़ने और अपने रिसीवर को मैनिफ़ेस्ट में पंजीकृत करना न भूलें:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
...
<service android:name=".SimpleWakefulReceiver">
<intent-filter>
<action android:name="com.example.SimpleWakefulReceiver"/>
</intent-filter>
</service>
startForeground()
अपनी सेवा में उपयोग करें। अन्यथा, एंड्रॉइड और उसके उपयोगकर्ता अंतरिक्ष की बर्बादी के रूप में आपकी सेवा को मार देंगे, और आपको एंड्रॉइड मार्केट में कुछ अप्रिय टिप्पणियां मिलेंगी। अधिकांश परिस्थितियां जहां आपको लगता है कि आप बूट समय पर शुरू करने के लिए एक सेवा चाहते हैं, तो आप बेहतर सेवा का उपयोग कर रहे हैंAlarmManager
ताकि आपकी सेवा लगातार चलने के बजाय समय-समय पर चल सके ।