【问题标题】:Requesting for Location Services Android请求位置服务 Android
【发布时间】:2016-09-24 14:43:17
【问题描述】:

我正在使用此代码让用户激活位置服务。我想显示用户对话框以接受以启用位置服务,然后将它们重定向到 LOCATION_SETTINGS 页面。但是如果没有用户从用户那里接受它,它就会重定向到位置设置。

if(lm==null)
    lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
try{
    gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch(Exception ex){}
try{
    network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch(Exception ex){}

if(!gps_enabled && !network_enabled){
    dialog = new AlertDialog.Builder(this);
    dialog.setMessage(this.getResources().getString(R.string.gps_network_not_enabled));
    dialog.setPositiveButton(this.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface paramDialogInterface, int paramInt) {
            // TODO Auto-generated method stub
            Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(myIntent);
            //get gps
        }
    });
    dialog.setNegativeButton(this.getString(R.string.Cancel), new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface paramDialogInterface, int paramInt) {
            // TODO Auto-generated method stub
            finish();
        }
    });
    dialog.show();

}

【问题讨论】:

    标签: android


    【解决方案1】:

    据我了解,您尝试启用该位置。

    您可以显示一个对话框来启用该位置,而不是将它们重定向到 LOCATION_SETTING 页面。

    一步一步的过程。

    首先你需要设置一个 GoogleApiClient 并实现 GoogleApiClient CallBackMethods。

    protected synchronized void buildGoogleApiClient() {
            mGoogleApiClient = new Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API).build();
            mGoogleApiClient.connect();   
    }
    

    回调方法

    @Override
    public void onConnected(Bundle bundle) {
        Log.d("OnConnected", "Connection successful");
        settingsrequest();
    }
    
    @Override
    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
    }
    
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
    }
    

    googleapiclient 连接后,onconnected 方法将调用,settingsRequest 方法将调用。

    protected static final int REQUEST_CHECK_SETTINGS = 0x1;
    LocationRequest locationRequest;
    
    
    public void settingsrequest() {
        locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setNumUpdates(1);
        locationRequest.setExpirationDuration(20000);
        locationRequest.setFastestInterval(500);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
        builder.setAlwaysShow(true); //this is the key ingredient
        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                final LocationSettingsStates state = result.getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS: {
                        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
                    }
                    // All location settings are satisfied. The client can initialize location
                    // requests here.
                    break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be fixed by showing the user
                        // a dialog.
                        try {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            status.startResolutionForResult(MainTab.this, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way to fix the
                        // settings so we won't show the dialog.
                        break;
                }
            }
        });
    }
    

    status.startResolutionForResult(MainTab.this, REQUEST_CHECK_SETTINGS) 将显示一个对话框请求位置。

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
       // Check for the integer request code originally supplied to startResolutionForResult().
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
                        break;
                    case Activity.RESULT_CANCELED:
                        break;
                }
                break;
        }
    }
    

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this) 将为已更改的位置设置监听器。

    随着位置的改变,onLocationChanged 方法将被调用。

     @Override
    public void onLocationChanged(Location location) {
          prevLocation  = location;
          //Do you work
    }
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-02-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2018-07-10
      • 2014-06-03
      • 2018-08-15
      • 1970-01-01
      相关资源
      最近更新 更多