Keep an android app running in background

1.8k Views Asked by At

I have seen many tutorials saying that to do this I have to use a service. After watching a youtube video, got this:

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        onTaskRemoved(intent);

        Toast.makeText(this, "Service", Toast.LENGTH_SHORT).show();

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
        restartServiceIntent.setPackage(getPackageName());
        startService(restartServiceIntent);
        super.onTaskRemoved(rootIntent);
    }
}

And I have to call this service in MainActivity using startService(new Intent(this, MyService.class));

This is working fine. Even if I close the app from the Recent Apps. But when I Force Stop the app from Settings, the service doesn't work anymore.

Is there any way to keep the app running even if the app is forcibly killed?

1

There are 1 best solutions below

0
xsheru On

You can register your app to get push notifications from google play services normally firebase now. And you can start your service by sending push notifications to your app from firebase Amin ask on your server.

NOTE: since android pie there are changes in how you can run your service. So before doing anything go through android pie services docs