2017-02-07 2 views
0

Я думаю, что мое приложение входит в цикл, потому что, как только оно начинается с устройства, оно не отвечает на любые команды, включая кнопку lisener. Я считаю, что проблема заключается в методах разрешений в RunTime. Прошу прощения за мой английский. Мой код:Приложение входит в цикл while во время локализации

общественный класс 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(); 
     } 
    } 
} 

}

+0

Если вы постоянно вводите инструкцию catch в 'onConnectionFailed', это может быть бесконечный цикл. Можете ли вы отлаживать/регистрировать и видеть, что ваш код вводит этот код снова и снова? –

+0

Я пробовал комментировать код, и я выяснял, что проблемы - это коды разрешений во время выполнения, но я не понимаю, что есть. –

+0

Какая версия для Android работает? –

ответ

0

Если manageLocationPermission() вызывается с правами уже выданным, ваш код входит следующий пункт ниже

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

Здесь вы звоните повторить одну и ту же функцию, а так как разрешения предоставлены, вы введете одно и то же условие, и снова одно и то же ... Вы видите, куда это происходит? Просто удалите manageLocationPermission() из этого else.

+0

, теперь он хорошо работает –

+0

@MattDeveloper убедитесь, что вы принимаете ответ, который решает ваш вопрос –

Смежные вопросы