在 Android 中启用 GPS

Enabling GPS in Android

我在我的应用程序中使用 GPS 定位,但当 GPS 未启用时应用程序崩溃了。 因为我是 android 开发的新手,所以我用谷歌搜索了一下,然后在 Whosebug 中找到了这个答案 Check if gps is on In Kitkat (4.4)

这里的问题是 PackageUtil 和 ACCESS_FINE_LOCATION 未定义,我不确定应该下载哪个库并将其嵌入到我的应用程序中

有什么建议吗?

if (PackageUtil.checkPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)) {

要在 Android 中设置权限,您必须在 AndroidManifest.xml 中像这样

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

应该在<application>标签结束后声明。

docs

中阅读更多相关信息

更新

您可以像这样检查gps是否开启

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
    Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
}else{
    Toast.makeText(this, "GPS is Disabled in your devide", Toast.LENGTH_SHORT).show();
}

并显示您可以使用的 GPS 设置页面

Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);

首先在manifest中添加这个权限

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

删除您编写的 if 代码。

然后添加此 GPS 检查器代码。此代码检查 GPS 是否已启用。如果未启用,它将打开 GPS 设置。

private void CheckEnableGPS() {
        String provider = Settings.Secure.getString(getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if(!provider.equals("")){
            //GPS Enabled
        }else{
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Enable GPS");  // GPS not found
            builder.setMessage("The app needs GPS to be enabled do you want to enable it in the settings? "); // Want to enable?
            builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            });
            builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            });
            builder.setCancelable(false);
            builder.create().show();
            return;
        }
    }