2015-08-21 58 views
0

我正在嘗試啓用/禁用GPS。我試過這個代碼 - :以編程方式啓用/禁用gps android無法正常工作

//Enable GPS 
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); 
intent.putExtra("enabled", true); 
context.sendBroadcast(intent); 
//Disable GPS 
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); 
intent.putExtra("enabled", false); 
context.sendBroadcast(intent); 

它給安全權限錯誤。我也嘗試打開設置 - :

Intent in = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); 

startActivity(in); 

它不適用於每個設備。他們的任何解決方案來處理所有版本的android。

+1

請檢查我的答案在這裏[Android設備GPS開/關編程](http://stackoverflow.com/a/22529296/3330969)。檢查第四點。 – Kedarnath

+0

我認爲你不能直接啓用和禁用它,你需要顯示一個用戶決定的對話框 –

回答

2

這是deprecated。您無法以編程方式打開/關閉位置。更好的是,我建議你使用最新版本的GooglePlayService。使用PlayService您可以隨時檢查location是否已啓用。如果它沒有啓用,然後AlertDialog啓用它。即使不離開您的應用程序,您也可以啓用GPS。如果它沒有啓用,那麼你可以做任何你想要執行的操作。你可以找到這個post

更多的細節基本上你Activity應該實現ResultCallback<LocationSettingsResult>

和註冊PendingIntent像下面,

PendingResult<LocationSettingsResult> result = 
      LocationServices.SettingsApi.checkLocationSettings(
        mGoogleApiClient, 
        mLocationSettingsRequest 
      ); 
    result.setResultCallback(this); 

現在你有一個onResult回調可以執行你想要什麼要做

@Override 
public void onResult(LocationSettingsResult locationSettingsResult) { 
    final Status status = locationSettingsResult.getStatus(); 
    switch (status.getStatusCode()) { 
     case LocationSettingsStatusCodes.SUCCESS: 
      Log.i(TAG, "All location settings are satisfied."); 
      startLocationUpdates(); 
      break; 
     case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
      Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to" + 
        "upgrade location settings "); 
      try { 
       // Show the dialog by calling startResolutionForResult(), and check the result 
       // in onActivityResult(). 
       status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS); 
      } catch (IntentSender.SendIntentException e) { 
       Log.i(TAG, "PendingIntent unable to execute request."); 
      } 
      break; 
     case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
      Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " + 
        "not created."); 
      break; 
    } 
} 
// This code is from https://github.com/googlesamples/android-play-location/blob/master/LocationSettings/app/src/main/java/com/google/android/gms/location/sample/locationsettings/MainActivity.java 

請找到山姆在谷歌項目Github

相關問題