可能重複:
How to programmatically enable GPS in Android Cupcake開啓關閉GPS的Android
我目前正在寫在Android的一個應用程序,與GPS的工作原理。目前我能夠確定GPS是否啓用。我的問題是,我想要啓用應用程序啓動時的GPS,如果它被禁用。我怎樣才能做這個programmaticaly? 另外,我想創建打開和關閉GPS的功能,我讀了關於它的所有stackoverflow上的線程,但是我嘗試了所有的功能,我得到了「不幸你的應用程序必須停止」(我沒有忘記添加權限)
有人可以幫助我一個工作功能來啓用或禁用GPS?
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
起初,我用這些功能:
private void turnGPSOn(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
private void turnGPSOff(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps")){ //if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
然後我嘗試使用:
ENABLE GPS:
Intent intent=new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
DISABLE GPS:
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);
兩者不是爲我工作
任何一個有想法?
僅僅因爲你得到一個強制關閉對話框並不意味着該方法是不好的。你嘗試過調試這個問題還是放棄了?也許你應該發佈一個你試過的代碼示例,並收到了什麼錯誤,以便我們能夠更好地幫助你。 – Samuel
感謝您的回覆,我添加了功能,我嘗試使用..我希望有人會幫助我解決問題 –
在Android中,你不能(也不應該btw)以編程方式激活GPS。您只需打開「定位設置菜單」並讓用戶自行打開。 – alex