在Android 2.2以后才可使用
1 import android.content.ContentResolver; 2 import android.content.Context; 3 import android.location.LocationManager; 4 import android.provider.Settings; 5 6 /** 7 * GPS類,用來判斷GPS是否開啟,切換GPS狀態 8 * 在 AndroidManifest.xml中需要添加權限: 9 * <uses-permission android:name="android.permission.WRITE_SETTINGS" /> 10 * <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" /> 11 * 在 AndroidManifest.xml中添加系統權限: android:sharedUserId="android.uid.system" 12 * 例如: 13 * <manifest xmlns:android="http://schemas.android.com/apk/res/android" 14 * android:sharedUserId="android.uid.system" > 15 * @author ljp 2014-1-11 16 * 17 */ 18 public class GPS { 19 /** 20 * Gets the state of GPS location. 21 * 22 * @param context 23 * @return true if enabled. 24 */ 25 public static boolean getGpsState(Context context) { 26 ContentResolver resolver = context.getContentResolver(); 27 boolean open = Settings.Secure.isLocationProviderEnabled(resolver, 28 LocationManager.GPS_PROVIDER); 29 System.out.println("getGpsState:" + open); 30 return open; 31 } 32 33 /** 34 * Toggles the state of GPS. 35 * 36 * @param context 37 */ 38 public static void toggleGps(Context context) { 39 ContentResolver resolver = context.getContentResolver(); 40 boolean enabled = getGpsState(context); 41 Settings.Secure.setLocationProviderEnabled(resolver, 42 LocationManager.GPS_PROVIDER, !enabled); 43 } 44 }
如果加入權限 <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />后出現
permission is only granted to system apps問題,可以用以下解決方法:點eclipse的菜單project->clean
上面步驟后本來以為可以了,但又出現新的問題,那就是android.uid.system權限添加后編譯出現錯誤:Installation error: INSTALL_FAILED_SHARED_USER_INCOMPATIBLE
解決辦法:通過在linux環境下更改編碼,vold 模塊里的 Volume.cpp文件 在調用doMount的語句里做一下修改~ doMount(devicePath, path, false, false, false,1000, 1015, 0702, true) ↓ doMount(devicePath, path, false, true, false,1000, 1015, 0002, true) 編譯以后.(由於沒用過linux環境,暫時還沒喲測試,待有空下個源碼重編譯一下)