Android - calling startActivity() from LocationListener.onLocationChanged(), Is this really what I want?

StackOverflow https://stackoverflow.com/questions/15063306

  •  11-03-2022
  •  | 
  •  

Question

I am writing a foreground service to receive GPS notifications, send system notifications and make calls. The application has no Activity attached to it, only a service that is launched from a boot receiver. When I was trying to start the calling activity from within onLocationChanged() of the service, I got:

Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

Fearing the skeptical question, I decided to look at stackOverFlow, where I found these: Calling startActivity() from outside of an Activity context, Android: Make phone call from service, android start activity from service - all suggesting to do this exact thing.

So, my question is: Why is it inadvisable to use this flag (something about the history stack)? Is it OK to do it in my case?

A simplified code:

public class CallService extends Service implements LocationListener {

    @Override
    public void onCreate() {
        super.onCreate();
        startForeground(1, NotificationGenerator.getNotification());
    }

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

    @Override
    public synchronized void onLocationChanged(Location loc) {
        String url = "tel:xxxxxxxxxx";
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    ...
}
Was it helpful?

Solution

The answer to that lies purely in User Experience (UX) domain. Android devices are usually personal devices and you should put that in mind while coding your app.

Users are maybe playing a game or making a phone call, launching your activity without any notification is rude and I would uninstall any app that would do that.

Also if the phone is locked your activity will not actually launch instead it will wait until the user unlocks the phone.

Notifications on the other hand are made to tell the user that the app wants to show you something. So use them instead.

Unless you are building a private app then you know what is better for your requirements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top