Reputation: 203
I want create Android service all time working to when I stopped it. Restart device, Garbage collector and etc don't affect it's working. Advice me best example please.
Upvotes: 3
Views: 808
Reputation: 419
For this you will have to set a BroadcastReciver which will receive boot completed. in that receiver start the service you want following is exact code.
Service class
public class BroadCastService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.tone);
mediaPlayer.start();
return Service.START_STICKY;
}
}
BroadCastReciver class
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, BroadCastService.class);
context.startService(startServiceIntent);
}
}
inside Manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
// add following in <application>
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Upvotes: 1
Reputation: 1579
Upvotes: 2
Reputation: 95578
You need to have a BroadcastReceiver
that listens for the BOOT_COMPLETED broadcast Intent
and start your Service
when the device boots.
Your Service
should return START_STICKY
from onStartCommand()
. This will restart your Service
if Android decides to kill it for any reason.
You cannot prevent Android from killing your Service
if it wants to. All you can do is try to make sure that your Service
gets restarted if killed.
Also, if your user force stops your application, your Service
will be stopped and will not be automatically started again. In this case, the user will need to launch your app again in order for you to restart your Service
.
Upvotes: 3