I am currently developing something similar, maintaining a live service, even though the App
is closed or restart Smartphone
, the first thing you should do is:
Create a class that extends BroadcastReceiver
:
public class BootBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MyService.class));
}
}
In servicio
:
public class MyService extends Service {
.....
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
.....
}
Then you go to your AndroidManifest
, you register the BroadcastReceiver
and the servicio
in case Android Studio does not automatically create it ...
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" >
</service>
<receiver android:name=".BootBroadcast">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
And finally it is to start the servicio
from our MainActivity:
if (!isMyServiceRunning(MyService.class)){ //método que determina si el servicio ya está corriendo o no
serv = new Intent(context,MyService.class); //serv de tipo Intent
context.startService(serv); // tipo Context
Log.d("App", "Service started");
} else {
Log.d("App", "Service already running");
}
In case these last lines cause you problems, you simply start the service in a simple way first to test its operation, with:
startService(new Intent(this,MyService.class));
In the OnCreate
...
IMPORTANT !!!
Place the corresponding permiso
to raise the servicio
when the smarphone is turned on ...
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />