Launch Location Settings intent from preferences XML file
Asked Answered
F

2

19

I want to launch System's Location Settings from an Intent. I know that programmatically it goes like this

Intent viewIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(viewIntent);

but I need to do it from the XML of a Preference. I try like this

<Preference
    android:title="@string/pref_title" >
    <intent android:action="android.settings.ACTION_LOCATION_SOURCE_SETTINGS" />
</Preference>

but it does not work, I always get an ActivityNotFoundException. How can I launch that System Location Settings from an XML Intent?

Faina answered 14/4, 2013 at 16:42 Comment(0)
B
41

You can create a: PreferenceActivity that will represent you preferences and then you can assign an onClick to your preference like this:

Preference goToLocationSettings = (Preference) findPreference("goToLocationSettings");
goToLocationSettings.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        public boolean onPreferenceClick(Preference preference) {
            Intent viewIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(viewIntent);

            return true;
        }
    });

And you will need to assign a key to your preference in the xml file:

<Preference
    android:key="goToLocationSettings"
    android:title="@string/pref_title" />
Bissau answered 14/4, 2013 at 16:48 Comment(4)
I appreciate your answer, but does it mean there is no way to invoke that action from XML then?Faina
I'm not familiar with a way and I think there isn't one.Bissau
I'm getting an AndroidRuntimeException: "Calling StartActivity() from outside of an activity". I guess this is because of the context of onPreferenceClick()...Faina
you can do something like this: YourActivityName.this as the context.Bissau
R
0

Try this code:

<PreferenceScreen
    android:key="key_location"
    android:summary="location settings"
    android:title="Open location settings">

    <intent android:action="android.settings.ACTION_LOCATION_SOURCE_SETTINGS"/>

</PreferenceScreen>
Rohn answered 13/1, 2016 at 23:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.