允许用户设置GPS

时间:2015-09-14 10:01:19

标签: android

我想给用户对话框打开/关闭GPS。可以使用新的SettingAPI完成吗?如果是这样,如何:我看到下面的代码,但不确定它是否适用于通过兼容性库的Android 2.3设备?支持哪些版本的Android。特别是用户需要连接到网络才能将此服务用于GPS,或者它可以直接使用设备上的设置而不需要互联网连接吗?对话框还显示GPS设置还是用户可以访问设置的其他部分?我试图限制只使用GPS设置。

LocationSettingsStates locationSettingsStates = locationSettingsResult.getLocationSettingsStates();

    if (!locationSettingsStates.isGpsPresent() || !locationSettingsStates.isGpsUsable()) {

 Status status = locationSettingsResult.getStatus();
 if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
 try {
 status.startResolutionForResult(StilActivity.this, REQUEST_CHECK_SETTINGS);
 } catch (IntentSender.SendIntentException th) {
 Log.e(TAG, "Error opening settings activity.", th);
          }
      }
 }

1 个答案:

答案 0 :(得分:1)

只需调用该函数,然后

   public void start() {
        mlocManager = (LocationManager) 
                getSystemService(Context.LOCATION_SERVICE);

        if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(getApplicationContext(), "Response ==>" + "GPS is on",
                    Toast.LENGTH_LONG).show();
        } else {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    MainActivity.this);
            alertDialogBuilder
                    .setMessage("GPS is disabled in your device. Enable it?")
                    .setCancelable(false)
                    .setPositiveButton("Enable GPS",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    Intent callGPSSettingIntent = new Intent(
                                            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                    MainActivity.this.startActivity(callGPSSettingIntent);
                                }
                            });
            alertDialogBuilder.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alert = alertDialogBuilder.create();
            alert.show();

        }
    }

就像一个轻微的建议你可以调用startActivityforResult(),一旦用户从位置页面返回,你可以进一步执行。