1

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?

abbylu
  • 49
  • 2
fsdklfm
  • 17
  • 6
  • When the user force-stops and app, he is saying that he doesn't want it to run anymore. This will also stop any services in the app. The app cannot be restarted unless the user manually launches the app again. This is by design. – David Wasser Sep 22 '19 at 21:01
  • You should take a look at the document https://developer.android.com/guide/background/ – GianhTran Sep 23 '19 at 23:29

1 Answers1

0

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

xsheru
  • 467
  • 4
  • 25