位置服务判断与开启

博客内容介绍了在获取位置权限后,如何判断并开启位置服务以实现有效定位,包括使用PermissionsUtils进行服务状态检查及如何引导用户打开位置服务设置页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

动态获取位置权限后,如果不开启位置服务仍然定位不了
1.PermissionsUtils 判断位置服务是否开启

import android.content.Context;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;

public class PermissionsUtils {


    public static boolean isLocationServiceEnabled(Context context) {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }
}

2.打开位置服务页面

 Intent intent = new Intent();
                        //定位服务页面
                        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        try {
                            startActivity(intent);
                        } catch (ActivityNotFoundException ex) {
                            //如果页面无法打开,进入设置页面
                            intent.setAction(Settings.ACTION_SETTINGS);
                            try {
                                startActivity(intent);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值