应用程序在本地化期间进入循环

时间:2017-02-07 09:42:07

标签: java android android-studio

我认为我的应用程序进入循环,因为一旦它在设备中启动,它就不会响应任何命令,包括lisener按钮。我认为问题是RunTime中的许可方法。对不起我的英语。 我的代码是:

公共类MainActivity扩展AppCompatActivity实现了GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {

private static final int REQUEST_RESOLVE_ERROR = 3;
private GoogleApiClient mGoogleApiClient;
private volatile Location mCurrentLocation;
private static final int REQUEST_PERMISSION_LOCATE = 2;
private static final int LOCATION_DURATE_TIME = 5000;
private boolean mResolvingError = false;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Toast.makeText(MainActivity.this, "ciao", Toast.LENGTH_LONG).show();
        }
    });

}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
    Toast.makeText(MainActivity.this, "connesso", Toast.LENGTH_LONG).show();
}

@Override
protected void onStop() {
    super.onStop();
    mGoogleApiClient.disconnect();
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    manageLocationPermission();
}

@Override
public void onConnectionSuspended(int i) {

}

//gestione dell'errore
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
{
    if (mResolvingError) {
        // If we're already managing an error we skip the invocation of this method
        return;
    } else if (connectionResult.hasResolution()) {
        // Here we check if the ConnectionResult has already the solution. If it has
        // we start the resolution process
        try {
            // Starting resolution
            mResolvingError = true;
            // We launch the Intent using a request id
            connectionResult.startResolutionForResult(MainActivity.this, REQUEST_RESOLVE_ERROR);
        } catch (IntentSender.SendIntentException e) {
            // If we have an error during resolution we can start again.
            mGoogleApiClient.connect();
        }
    } else {
        // The ConnectionResult in the worse case has the error code we have to manage
        // into a Dialog
        // Starting resolution
        mResolvingError = true;
    }
}



//location update
private void updateLocation()
{
    LocationRequest locationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setNumUpdates(1)
            .setExpirationDuration(LOCATION_DURATE_TIME);


    LocationServices.FusedLocationApi
            .requestLocationUpdates(mGoogleApiClient, locationRequest, new LocationListener() {
                @Override
                public void onLocationChanged(Location location)
                {
                    mCurrentLocation = location;
                }
            });
}

private void startLocationListener()
{
    updateLocation();
}


//permessi in RunTime
private void manageLocationPermission()
{
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED)
    {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
        {
            new AlertDialog.Builder(this)
                    .setTitle("Permesso di geolocalizzazione")
                    .setMessage("Devi dare il permesso alla geolocalizzazione")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSION_LOCATE);
                        }
                    })
                    .create()
                    .show();
        }
        else {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSION_LOCATE);
        }
    }else
    {
        mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        manageLocationPermission();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if(requestCode == REQUEST_PERMISSION_LOCATE)
    {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
        {
            //se mi hanno accettato i permessi
            startLocationListener();
        }
        else{
            new AlertDialog.Builder(this)
                    .setTitle("Permesso di geolocalizzazione")
                    .setMessage("Devi dare il permesso alla geolocalizzazione")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .create()
                    .show();
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

如果使用已授予的权限调用manageLocationPermission(),则代码将输入以下else子句

} else {
    mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    manageLocationPermission();
}

这里你再次调用相同的函数,并且由于权限被授予,你将输入相同的else子句,并再次输入相同的内容......你会看到这是怎么回事?只需从此else子句中删除manageLocationPermission()

即可