How can I run a service in the background without stopping?

0

The problem I have, is that when you launch the service in the background after 5 min it stops. It also stops when you block your phone or close the app instead of minimizing it.

What I want is to launch the service and keep it running without being interrupted. I have looked in a thousand pages, but I do not give with the answer. I hope you can help me.

    
asked by Antonio Olvera 30.07.2018 в 10:49
source

1 answer

0

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" />
    
answered by 31.07.2018 / 21:09
source