SemyColon.Me
SemyColon.Me

Reputation: 378

How to prevent restarting a running Service - Android

i'm want to do long background work also i want to be able to show progress with statistics in ui anytime user goes to a activity also with updating notification.

i start a Service in START_STICKY mode then i bind it to my activity and run the proccess with an public method of Service.

everything works well until i close my app from recent apps.

it destroys and restart my running Service.

that's the problem. "i don't want my running service to restart"

i want my service to keep running without termination and without restarting.

how can i do what i want to do?

why os restart a running service: / thou

i tried START_NOT_STICKY but it's closing the service too.

Upvotes: 3

Views: 3597

Answers (3)

Kevin Krumwiede
Kevin Krumwiede

Reputation: 10288

On Android 6+, a foreground service will not be stopped when the user removes the app from recents. You can make your service a foreground service by adding this code to onCreate():

final Intent launcherIntent = new Intent();
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, launcherIntent, 0);
final Notification.Builder builder = new Notification.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("Test Notification")
        .setWhen(System.currentTimeMillis())
        .setContentIntent(pendingIntent);
final Notification notification;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    notification = builder.build();
}
else {
    //noinspection deprecation
    notification = builder.getNotification();
}
this.startForeground(NOTIFICATION_ID, notification);

Prior to Android 6, services are always killed when the user removes the task from recents. There is nothing you can do about it except shut down cleanly in onTaskRemoved().

Upvotes: 3

Salman500
Salman500

Reputation: 1211

check if service is running or not 

if(!isBackgroundServiceRunning(BackgroundServices.class))
        {
            Intent intent = new Intent(this,BackgroundServices.class);
            startService(intent);
        }

private boolean isBackgroundServiceRunning(Class<?> service)
    {
        ActivityManager manager = (ActivityManager)(getApplicationContext().getSystemService(ACTIVITY_SERVICE));

        if (manager != null)
        {
            for(ActivityManager.RunningServiceInfo info : manager.getRunningServices(Integer.MAX_VALUE))
            {
                if(service.getName().equals(info.service.getClassName()))
                    return true;
            }
        }
        return false;
    }

Upvotes: 0

Vlad D
Vlad D

Reputation: 454

Try using foreground service:

In method where you start service:

Intent startIntent = new Intent(MainActivity.this, ForegroundService.class);
startIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
startService(startIntent);

Now in onStartCommand():

if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Start Foreground Intent ");
Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();

Read more Simple foreground service

OR you can try something like this:

from onStartCommand() need to return START_STICKY

override in your service onDestroy method:

@Override
public void onDestroy() {
    super.onDestroy();
    Log.i("EXIT", "ondestroy!");
    Intent broadcastIntent = new Intent();
    broadcastIntent.putExtra("broadcast.Message", "alarm, need to restart service");
    sendBroadcast(broadcastIntent);
}

Now need to implement broadcast receiver:

public class RestarterBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
    context.startService(new Intent(context, YourService.class));
    }
}

Upvotes: 1

Related Questions