1.在討論打開gps的之前先看下如何檢測gps的開關情況:
方式一:
boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
方式二(此方式需要android.permission.WRITE_SECURE_SETTINGS權限,此權限僅限於系統應用,所以需要將app安裝特定文件夾(此句待驗證)):
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(context.getContentResolver(), LocationManager.GPS_PROVIDER );
2.開啟 GPS的方法:
方式一:手動的定位到"設置-位置信息訪問權限"進行設置.
Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(settingsIntent);
方式二,gps的開關,此方法根據不同值還可設置其他功能(0-wifi,1-brightness,2-sync,3-gps,4-bluetooth),本人的4.2.4版本失效,其他版本未測.
public static void toggleGPS(Context context){ Intent GPSIntent = new Intent(); GPSIntent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); GPSIntent.addCategory("android.intent.category.ALTERNATIVE"); GPSIntent.setData(Uri.parse("custom:3")); try { PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send(); } catch (CanceledException e) { e.printStackTrace(); } }
方式三,此處同檢測gps的方式二,都是通過Setting.Secure來完成,需要android.permission.WRITE_SECURE_SETTINGS權限
Settings.Secure.setLocationProviderEnabled( context.getContentResolver(), LocationManager.GPS_PROVIDER, false );
暫時了解這些,歡迎共同討論
