I am a beginner in android guys.So, I need your help, I created an android service and I want to restart that service when the device powered-on or restarts only in the situation when my service is activated. In case my service is deactivated it shouldn't be started on device being powered-on or restarting of device. Please help Thanks
Asked
Active
Viewed 2,867 times
2 Answers
0
To restart your service you can create a BrodcastReciever with the action android.intent.action.BOOT_COMPLETED
and inside it, simply start your Service. And you can use SharedPreferences to save if the service was running on shutdown or not.

Elias Dolinsek
- 669
- 3
- 7
- 11
0
First, you need a way to indicate whether or not the service is activated. In this case, I'd use a SharedPreference
, which is stored persistently even after the app is closed, device is rebooted, etc. You can do that like so:
public void setServiceActivated(boolean activated) {
SharedPreferences sharedPreferences = context.getSharedPreferences("servicePrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor prefEditor = sharedPreferences.edit();
prefEditor.putBoolean("serviceActivated", activated);
prefEditor.apply();
}
Then, create a BroadcastReceiver
, which will run when the device bootup process is completed, and will start your service if it is activated:
public class AutoStart extends BroadcastReceiver {
// Method is called after device bootup is complete
public void onReceive(final Context context, Intent arg1) {
SharedPreferences sharedPreferences = context.getSharedPreferences("servicePrefs", Context.MODE_PRIVATE);
boolean serviceActivated = sharedPreferences.getBoolean("serviceActivated", false);
if (serviceActivated) {
// Start service here
}
}
}
And finally, register the BroadcastReceiver
in the manifest:
<application
android:allowBackup="true"
android:largeHeap="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<!-- Launches your service on device boot-up -->
<receiver android:name=".AutoStart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>

rjr-apps
- 352
- 4
- 13
-
-
please help me with this.... https://stackoverflow.com/questions/49338079/horizontal-layout-for-viewpager-not-inflating?noredirect=1#comment85676418_49338079 – Vijay Mar 17 '18 at 15:46
-
hey nope could you help me with this??? https://stackoverflow.com/questions/50217950/about-us-screen-pop-up-using-3-dots-action-bar-button – Vijay May 07 '18 at 18:11