如何以编程方式在android中启用/禁用gps和移动数据?
我希望我的应用程序能够以编程方式启用/禁用 gps 和移动数据,因为有许多应用程序,例如 tasker、profile flow、lookout extra 可以做到这一点,所以我搜索了它,但没有找到任何有用的示例,我发现下面的代码,但他们没有工作.
I want my application to be able to enable/disable gps and mobile data programmatically as there are many apps like tasker, profile flow, lookout extra which can do this so I searched for it but not found any useful example I found the following code but they didn't work.
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);
}
}
推荐答案
我希望我的应用程序能够启用/禁用 gps
I want my application to be able to enable/disable gps
幸运的是,出于明显的隐私原因,这是不可能的.虽然有一些黑客(例如您问题中的那个)曾经有效,但这些安全漏洞已经得到修复.
Fortunately, this is not possible, for obvious privacy reasons. While there were some hacks, like the one in your question, that used to work, those security flaws have since been fixed.
因为有许多应用程序,例如 tasker、profile flow、lookout extra 可以做到这一点
as there are many apps like tasker, profile flow, lookout extra which can do this
欢迎您提供证据证明这些应用中的任何一个都可以在现代版本的 Android 上执行此操作.
You are welcome to supply evidence that any of those apps can do this on modern versions of Android.
相关文章