Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
}
like image 871
Jayavinoth Avatar asked Dec 14 '22 23:12

Jayavinoth


2 Answers

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;
}
}
like image 53
Jayavinoth Avatar answered Dec 26 '22 20:12

Jayavinoth


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);
}
like image 40
Amir Raza Avatar answered Dec 26 '22 20:12

Amir Raza