2013-04-14 58 views
15

我想從Intent啓動系統的位置設置。我知道,編程它是這樣的從首選項XML文件啓動位置設置意圖

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

,但我需要從Preference的XML做到這一點。我嘗試這樣

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

,但它不工作,我總是得到一個ActivityNotFoundException。我如何從XML Intent啓動系統位置設置?

回答

33

您可以創建一個:PreferenceActivity將代表您的喜好,然後你可以指定一個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" /> 
+1

我apprecia你的答案,但這是否意味着無法從XML中調用該操作? – Jago

+0

我不熟悉一種方式,我認爲沒有一種。 –

+0

我得到一個'AndroidRuntimeException':「從一個活動的外部調用'StartActivity()'」。我想這是因爲'onPreferenceClick()'的上下文...... – Jago

0

試試這個代碼:

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

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

</PreferenceScreen> 
相關問題