Android中设置、打开GPS的两种方法,包括反射的应用

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的方式调用,但可以使用反射方式调用,从而实现相应的功能。


阅读源码还是非常有帮助的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liranke

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值