2012-09-14 124 views
1

可能重複:
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); 

兩者不是爲我工作

任何一個有想法?

+0

僅僅因爲你得到一個強制關閉對話框並不意味着該方法是不好的。你嘗試過調試這個問題還是放棄了?也許你應該發佈一個你試過的代碼示例,並收到了什麼錯誤,以便我們能夠更好地幫助你。 – Samuel

+0

感謝您的回覆,我添加了功能,我嘗試使用..我希望有人會幫助我解決問題 –

+2

在Android中,你不能(也不應該btw)以編程方式激活GPS。您只需打開「定位設置菜單」並讓用戶自行打開。 – alex

回答

7

您無法以編程方式打開和關閉GPS。你可以做的最好的事情是將用戶發送到設置屏幕,讓他們自己做。

final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
    new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
    startActivity(intent); 
} 

存在着黑客打開GPS /關閉程序,但他們只在舊版Android的工作。即使你可以,也不要這樣做。用戶可能已經關閉了GPS,因爲他們不想讓應用程序精確地跟蹤它們。試圖強迫改變他們的決定是非常糟糕的形式。

如果您需要啓用GPS,請在您的應用程序啓動時檢查它,如果用戶不啓用它,則保釋。

+0

這就是我想要的! – GeekHades