Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/221.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 从首选项XML文件启动位置设置_Android_Android Intent_Android Preferences - Fatal编程技术网

Android 从首选项XML文件启动位置设置

Android 从首选项XML文件启动位置设置,android,android-intent,android-preferences,Android,Android Intent,Android Preferences,我想从Intent启动系统的位置设置。我知道从编程的角度来说,它是这样的 Intent viewIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(viewIntent); <Preference android:title="@string/pref_title" > <intent android:action="andr

我想从
Intent
启动系统的位置设置。我知道从编程的角度来说,它是这样的

Intent viewIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(viewIntent);
<Preference
    android:title="@string/pref_title" >
    <intent android:action="android.settings.ACTION_LOCATION_SOURCE_SETTINGS" />
</Preference>
但是我需要从
首选项的XML中执行它。我试着这样做

Intent viewIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(viewIntent);
<Preference
    android:title="@string/pref_title" >
    <intent android:action="android.settings.ACTION_LOCATION_SOURCE_SETTINGS" />
</Preference>


但它不起作用,我总是得到一个
ActivityNotFoundException
。如何从XML意图启动该系统位置设置?

您可以创建一个表示您的首选项的:
首选项活动
,然后您可以按如下方式为您的首选项分配一个
onClick

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;
        }
    });
您需要在xml文件中为您的首选项分配一个密钥:

<Preference
    android:key="goToLocationSettings"
    android:title="@string/pref_title" />

尝试以下代码:

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

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

</PreferenceScreen>


我很感激你的回答,但这是否意味着没有办法从XML调用该操作?我不熟悉一种方法,我认为没有。我得到了一个
AndroidRuntimeException
:“从活动外部调用
StartActivity()
”。我想这是因为preferenceclick()上的
onPreferenceClick()
…您可以这样做:YourActivityName.this作为上下文。