Finding my service is running or not in Android?
-
10-10-2019 - |
Question
I have a service to contact the server to do some data transfer from my app periodically. Its working fine.
But when i restarted(switch off and on) my phone that service can not be restarted. so my idea is that to start that service again when the user open my app after restarting the phone. For that, i have to know about my service is running or not? how to do it?
Any other idea to handle this scenario also thankful.
Thanks in advance.
Solution
you need an implementation of BroadcastReceiver
, which is intended on BOOT_COMPLETED
action. Like this:
public class OnStartReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// your starting service code here
}
}
Also, you should add receiver
tag to your manifest file with android:name
= your fully qualified name of OnStartReceiver and intent-filter tag nested with BOOT_COMPLETED
as intent name, like this:
<receiver android:name=".onStartReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
OTHER TIPS
Create a BroadcastReceiver
to listen for the ACTION_BOOT_COMPLETED
event. More details here.
Use AlarmManager
for scheduled tasks like this, so your service does not need to be in memory all of the time. As Mr. Ribery indicates, use a BroadcastReceiver
with ACTION_BOOT_COMPLETED
to re-schedule your tasks after a phone reboot.