androidandroid-intentandroid-activityandroid-service

Start Activity from Service in Android


Android:

public class LocationService extends Service {

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        startActivity(new Intent(this, activity.class));
    }
}

I launched this service from Activity

In Activity if condition satisfies start

startService(new Intent(WozzonActivity.this, LocationService.class));

from my LocationService mentioned above could not launch Activity, how can I get context of current running Activity in service class?


Solution

  • From inside the Service class:

    Intent dialogIntent = new Intent(this, MyActivity.class);
    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(dialogIntent);
    

    But, this does not work from Android 10+ due to battery optimisation restrictions