动态获取位置权限后,如果不开启位置服务仍然定位不了
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();
}
}