Jayavinoth
Jayavinoth

Reputation: 564

Run a service in background continuously

Run a service in background continuously. For example, a service has to be kicked off which will display a toast message 20 seconds once even if the app is closed.

public class AppService extends IntentService {

    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    public AppService() {
        super("AppService");
    }

    @Override
    protected void onHandleIntent(Intent workIntent) {
        Toast.makeText(getApplicationContext(), "hai", Toast.LENGTH_SHORT).show();
        SystemClock.sleep(20000);
    }
}

Upvotes: 6

Views: 34726

Answers (4)

Amir Raza
Amir Raza

Reputation: 2860

Accepted answer will not work on from Android 8.0 (API level 26), see the android's background limitations here

Modification in Accepted Answer:

1: You have to invoke the service's startForeground() method within 5 seconds after starting the service. To do this, you can call startForeground() in onCreate() method of service.

public class AppService extends Service {
    ....
    
    @Override
    public void onCreate() {
        startForeground(9999, Notification())
    }

    ....
} 

2: You must call startForegroundService() instead of startService() by checking API level from where you want to start the service.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    context.startForegroundService(intent);
} else {
    context.startService(intent);
}

Upvotes: 3

Fra Red
Fra Red

Reputation: 430

This code work for me..

public class ServiceClass extends Service {

    public static final int notify = 300000;  //interval between two services(Here Service run every 5 Minute)
    private Handler mHandler = new Handler();   //run on another Thread to avoid crash
    private Timer mTimer = null;    //timer handling

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        if (mTimer != null) // Cancel if already existed
            mTimer.cancel();
        else
            mTimer = new Timer();   //recreate new
        mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);   //Schedule task
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTimer.cancel();    //For Cancel Timer
        Log.d("service is ","Destroyed");
    }

    //class TimeDisplay for handling task
    class TimeDisplay extends TimerTask {
        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Log.d("service is ","running");
                }
            });
        }
    }
}

Upvotes: 2

Jayavinoth
Jayavinoth

Reputation: 564

Below code works for me...

public class AppService extends Service {

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, " MyService Started", Toast.LENGTH_LONG).show();
    return START_STICKY;
}
}

Upvotes: 7

Zoe - Save the data dump
Zoe - Save the data dump

Reputation: 28228

In your manifest, where you declare your service, add:

android:process=":processname"

This lets the service run on a separate process and thus it will not be killed with the app.

You can then chose if you want to use foreground. It will show a persistent notification, but reduces the likelihood if the service being killed.

Further, if you want to create a continuously running service, use Service, NOT IntentService. IntentService stops when it is finished doing its action.

Upvotes: 1

Related Questions