如何检查用户是否真的在Android中启用GPS位置?

时间:2015-07-02 08:53:54

标签: android gps location fragment settings

我的应用程序需要GPS,因此在执行特定操作时,我会检查GPS是否启用如下(并且正如Marcus在this其他问题中所建议的那样):

var textBoxes = new List<TextBox> { txtReset1, txtReset2, txtReset3, txtReset4 };

...

// Option 1: using .ForEach()
textBoxes.ForEach(tb => SetEmptyTextBoxToZero(tb));

// Option 2: using foreach
foreach (var tb in textBoxes)
{
    SetEmptyTextBoxToZero(tb);
}

问题在于,用户从位置设置无法启用GPS(例如,通过单击&#34;返回&#34;按钮并返回应用程序)。在这种特殊情况下,片段为相应的过程注入布局,但GPS仍然被禁用。怎么解决?

2 个答案:

答案 0 :(得分:1)

我想这是您正在寻找的方法。 您必须检查KitKat上方的Android版本。

@SuppressLint("InlinedApi") @SuppressWarnings("deprecation")
public static boolean isLocationEnabled(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 (SettingNotFoundException e) {
            e.printStackTrace();
        }

        return locationMode != Settings.Secure.LOCATION_MODE_OFF;

    }else{
        locationProviders =     Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        return !TextUtils.isEmpty(locationProviders);
    }
} 

答案 1 :(得分:0)

我通过在startActivity(...)方法中将startActivityForResult(...)替换为buildAlertMessageNoGps()来解决问题。这样,我可以再次检查回调函数onActivityResult(...)中是否已启用GPS。