Aravind Jagatab
Aravind Jagatab

Reputation: 69

How turn on GPS programmatically in my android application?

If we use this code we see a message: searching for GPS. However, the GPS symbol is merely shown; GPS doesn't actually work:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
    intent.putExtra("enabled", true);
    this.sendBroadcast(intent);   
}

Why isn't it working ? And how to make it work correctly ?

Upvotes: 1

Views: 5162

Answers (1)

Yash Sampat
Yash Sampat

Reputation: 30601

That's not allowed anymore. If you take a look at this bug report, this hack was subverted in Android 4.4. It still works on older OS versions, though you shouldn't be using it anywhere now. To quote that report:

This doesn't work ... however, it can cause stuff to react as if the GPS status changed -- for example, the HTC One S will show the GPS icon in the status bar, even though the GPS is still disabled.

That explains why you can see the GPS icon even though it isn't actually ON. Now as for why you can't do that ...

Android's GPS technology periodically sends location data to Google even when no third-party apps are actually using the GPS function. In many Western countries this is seen as a major violation of privacy. That's why Google made it mandatory to get the user's consent before using the GPS function. The following dialog is seen whenever the user turns GPS on:

GPS user permission

And hence it is no longer possible to programmatically change the GPS settings, as by necessity it requires the user's permission. What the programmer can do is direct the user to the GPS settings by calling

startActivity(context, new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));

and let the user make a choice.

As an interesting point, if you try sending the GPS_ENABLED_CHANGE broadcast on the new OS versions, you get a

java.lang.SecurityException: Permission Denial: 
    not allowed to send broadcast android.location.GPS_ENABLED_CHANGE

error. As you can see, its a SecurityException with a permission denial message.

Upvotes: 1

Related Questions