【发布时间】:2013-05-21 02:39:49
【问题描述】:
我希望我的应用程序能够以编程方式启用/禁用 gps 和移动数据,因为有许多应用程序,例如 tasker、profile flow、lookout extra 可以做到这一点,所以我搜索了它,但没有找到任何有用的示例。下面的代码,但他们没有工作。
private void setMobileDataEnabled(Context context, boolean enabled) {
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}
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);
}
}
【问题讨论】:
-
你用什么安卓版本进行测试?
-
安卓 2.3 和 4.1.2
-
试试下面的代码,让我知道它是否有效。
-
它的工作谢谢,但它正在做的是打开服务,所以如果使用我的应用程序启动它,状态栏顶部会出现一个图标,它正在搜索 gps.... ..如果我什至手动或从应用程序关闭它,它不会从那里去,在 android 4.1.2 上它没有打开状态栏中的 gps 图标,但它启动了服务,但在 android 2.3 中它打开了图标,也启动了服务
-
忘记 GPS...您至少可以禁用移动数据吗?如果是,如何...代码(GPS 除外)如何工作?另外,请提及其他所需的更改,例如命名空间等......