1. 内容简介:
在实际项目的开发中,经常需要实现定位功能,这就需要使用GPS,那么,如何用代码实现GPS的打开呢?本节介绍2种方法:
第一种,使用Settings提供的GPS设置功能;
第二种,使用反射的方式。
2. 代码:
(1)第一种,使用Settings提供的GPS设置功能:
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();
}
}
说明:
主要使用了SettingsAppWidgetProvider这个provider。
ContentProvider,即内容提供者,是Android中四大组件之一,通常用于数据共享。
在软件项目中,当其他应用程序需要访问本应用程序的数据时,可以使用ContentProvider来实现。在具体使用时,需要监听相应的URI。其它应用程序通过URI向ContentProvider发起插入/删除/更新/查询等操作,从而实现数据的共享。
(2)第二种,使用反射的方式:
public static boolean toggleGprs(Context mContext, boolean isEnable) {
ConnectivityManager connManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
;
boolean result = true;
try {
Class<?> cmClass = connManager.getClass();
Class<?>[] argClasses = new Class[1];
argClasses[0] = boolean.class;
// 反射ConnectivityManager中hide的方法setMobileDataEnabled,可以开启和关闭GPRS网络
Method method = cmClass.getMethod("setMobileDataEnabled", argClasses);
method.invoke(connManager, isEnable);
result = true;
} catch (Exception e) {
e.printStackTrace();
result = false;
}
return result;
}
说明:
Android系统源码中有很多隐藏的方法,用hide注解,这些方法不能直接以Api的方式调用,但可以使用反射方式调用,从而实现相应的功能。
阅读源码还是非常有帮助的。