As my code looks today, I'm periodically sending a alarm(?) using AlarmManager
that is received by AlarmReceiver extends BroadcastReceiver
which in turn starts a Service. The Service do some updating and ends with a stopSelf()
. IMO this is the best way of periodically perfom a task without constantly having a Service running. Correct?
The issue with this code is however that the whole chain of events is initiated onSharedPreferenceChanged()
. I (initially) thought this was a good idea since the whole updating thing is enabled by the user in SharedPreferences
. I've now come to the conclusion that this is in fact not very good and that I need to initiate the AlarmManager/AlarmReceiver/Service/whatever both onPreferenceChange
but also on boot.
I've done some searching but everyone seems to want to start the Service on boot. As I see it, I just need to initiate the AlarmManager
which will then start the Service (when needed and only periodically).
Please help me with, first of all, sorting this out and secondly coding it! Thanks in advance!
Then, create and register a BroadcastReceiver
where you will do the AlarmManager
stuff:
public class YourBootReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// do the AlarmManager here
}
}
Then, on your manifest:
<application>
... other stuff
<receiver android:name=".YourBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.