添加运行时权限后,GoogleAPIClient未获取位置

时间:2017-01-31 07:49:35

标签: android location google-api-client

我的应用程序需要获取用户的当前位置,该位置使用下面的当前代码做得非常好但是在MarshMallow和Nougat上崩溃。所以我添加了运行时权限,现在它没有崩溃,但也没有获取当前位置。正在(isReadStorageAllowed())中检查权限,然后检查GPS设置。if ((checkConnection()))检查互联网是否可用,然后连接到GoogliAPI客户端..请帮助我

public class PreEstimateBill extends Activity  implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener {

ArrayList<String> carCategory;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
LatLng loc;
TextView bill_amt, bill_amt_rs, bill_amt_dash, bill_amt_upper, bill_amt_rs_upper, time_mins, time;
Button bt_est;
int FLAG = -1, round_time, round_bill_upper, round_bill_lower;
private Location mCurrentLocation;
private AutoCompleteTextView pickup_search, drop_search;
TextView coming_soon;
ArrayList<String> names;
double newLat_pickup, newLng_pickup, newLat_drop, newLng_drop, defaultPick_lat, defaultPick_Lng, newLat_default_pickup, newLng_default_pickup;
private PlacesAutoCompleteAdapter mAutocompleteAdapter;
private String place, newAddress_pickup, newAddress_drop, newAddress_pickup_default, newAddress_default_pickup;
double pickup_drop_distance, pickup_drop_time, extra_time, extra_dist, fare_lower, fare, tax, fare_upper;
boolean PICKFLAG = false, DROPFLAG = false;
int PICKFLAGVAL = 0, DROPFLAGVAL = 0;
Location l, m;
View dotted_line;
private int REQUEST_LOCATION = 2;
private static int REQUEST_CODE_RECOVER_PLAY_SERVICES = 200;



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

    pickup_search = (AutoCompleteTextView) findViewById(R.id.tv_startPoint);
    drop_search = (AutoCompleteTextView) findViewById(R.id.tv_destPoint);
    bill_amt = (TextView) findViewById(R.id.bill_amt);
    bill_amt_rs = (TextView) findViewById(R.id.bill_amt_rs);
    bt_est = (Button) findViewById(R.id.bt_est_2);
    bill_amt_upper = (TextView) findViewById(R.id.bill_amt_upper);
    bill_amt_dash = (TextView) findViewById(R.id.bill_amt_dash);
    bill_amt_rs_upper = (TextView) findViewById(R.id.bill_amt_rs_upper);
    time_mins = (TextView) findViewById(R.id.time_mins);
    time = (TextView) findViewById(R.id.time);
    dotted_line = findViewById(R.id.lastLine);
    coming_soon = (TextView) findViewById(R.id.tag_coming_soon);
    carCategory = new ArrayList<String>();
    //m=new Location(22.5851, 88.4222,"kolkata");//putting dummy latlong values
    pickup_search.setThreshold(0);
    drop_search.setThreshold(0);

    names = new ArrayList<String>();

    mAutocompleteAdapter = new PlacesAutoCompleteAdapter(this,
            android.R.layout.simple_list_item_1);
    pickup_search.setAdapter(mAutocompleteAdapter);
    drop_search.setAdapter(mAutocompleteAdapter);

////////taking runtime permission for marshmallow and nougat to access     location////////
    if (isReadStorageAllowed()) {
        //If permission is already having then showing the toast
        Toast.makeText(PreEstimateBill.this, "You already have the permission", Toast.LENGTH_LONG).show();
       //buildGoogleApiClient();


        //Existing the method with return
        return;
    }
else {
        //If the app has not the permission then asking for the permission
        requestLocationPermission();
    }
/////////////////////////////////////////////////////////////////////////////////////
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    if( !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("GPS NOT FOUND");  // GPS not found
        builder.setMessage("Please check your location settings"); // Want to enable?
        builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
        });
        builder.setNegativeButton("NO", null);
        builder.create().show();
        return;
    }

    if ((checkConnection())) {

        //if (isReadStorageAllowed()) {
        // buildGoogleApiClient();
        try {
            //statusCheck();
            //if (isLocationServiceEnabled()) {
                Log.d("Build GoogleAPI:", "Executing");
                if (mGoogleApiClient == null) {
                    mGoogleApiClient = new GoogleApiClient.Builder(this)
                            .addConnectionCallbacks(this)
                            .addOnConnectionFailedListener(this)
                            .addApi(LocationServices.API)
                            .build();
                }

                if (mGoogleApiClient != null && !mGoogleApiClient.isConnected())
                    mGoogleApiClient.connect();
                //android.location.Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            //}
            }catch(Exception e){
                //Toast.makeText(this, "Google API client build error", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
            Toast.makeText(PreEstimateBill.this, "You are connected", Toast.LENGTH_LONG).show();


        }else{
            Toast.makeText(this, "No internet.Please check your internet connection and try again", Toast.LENGTH_LONG).show();
        }

    /////////////check if location is enabled/////////////////////////////////////////////

   /* if (checkGooglePlayServices()) {
        Toast.makeText(this, "Google Play Services installed",
                Toast.LENGTH_SHORT).show();
    }*/
    /////////////////////////////////////////////////////////////////////////////////
        setListener();
        if (mCurrentLocation != null) {
            updateLatLong(mCurrentLocation);
        }
        //  }

}


@Override
protected void onResume() {
    super.onResume();
    setListener();
}


/* @Override
protected void onStart() {
        super.onStart();
}*/


@Override
public void onStop() {
    super.onStop();
    if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}
@Override
public void onConnected(Bundle bundle) {
    //Toast.makeText(this,"onConnected",Toast.LENGTH_SHORT).show();
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        android.location.Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {

            loc = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
            defaultPick_lat = mLastLocation.getLatitude();
            defaultPick_Lng = mLastLocation.getLongitude();
        }

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(5000); //5 seconds
        mLocationRequest.setFastestInterval(3000); //3 seconds
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        mLocationRequest.setSmallestDisplacement(0.2F); //1/10 meter

        pickup_search.setText(getCompleteAddressString(mLastLocation.getLatitude(), mLastLocation.getLongitude()));

        newAddress_pickup_default = pickup_search.getText().toString();
        place = newAddress_pickup_default;
        new GeodecoderTask(place).execute();
        FLAG = 2;
        pickDefaultVal();
    }
}

@Override
public void onConnectionSuspended(int i) {
   // Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
   // Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
   // mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(android.location.Location location) {



}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
public boolean checkConnection() {
boolean isConnected;
ConnectivityManager cn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();

if (nf != null && nf.isConnected() == true) {
    isConnected=true;
} else {
    isConnected=false;
}
return isConnected;
}
public boolean sameLoc()
{
    Toast.makeText(this, "Pick Up and Drop are same", Toast.LENGTH_LONG).show();
    bill_amt_rs.setVisibility(View.INVISIBLE);
    bill_amt.setVisibility(View.INVISIBLE);
    bt_est.setVisibility(View.INVISIBLE);
    bill_amt_rs_upper.setVisibility(View.INVISIBLE);
    bill_amt_upper.setVisibility(View.INVISIBLE);
    bill_amt_dash.setVisibility(View.INVISIBLE);
    time.setVisibility(View.INVISIBLE);
    time_mins.setVisibility(View.INVISIBLE);
    coming_soon.setVisibility(View.INVISIBLE);
    dotted_line.setVisibility(View.INVISIBLE);//dotted line
    return true;
}

private boolean isReadStorageAllowed() {
    //Getting the permission status
    int result = ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION);

    //If permission is granted returning true
    if (result == PackageManager.PERMISSION_GRANTED)
        return true;

    //If permission is not granted returning false
    return false;
}

//Requesting permission
private void requestLocationPermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION)){
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }

    //And finally ask for the permission
    ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);
}

//This method will be called when the user will tap on allow or deny
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    //Checking the request code of our request
    if(requestCode == REQUEST_LOCATION){

        //If permission is granted
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            //Displaying a toast
            //buildGoogleApiClient();

            Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();


        }
    }
}
  /* private boolean checkGooglePlayServices(){
   int checkGooglePlayServices = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
   if (checkGooglePlayServices != ConnectionResult.SUCCESS) {
    /*
    * Google Play Services is missing or update is required
    *  return code could be
    * SUCCESS,
    * SERVICE_MISSING, SERVICE_VERSION_UPDATE_REQUIRED,
    * SERVICE_DISABLED, SERVICE_INVALID.
    */
     //  GooglePlayServicesUtil.getErrorDialog(checkGooglePlayServices,this, REQUEST_CODE_RECOVER_PLAY_SERVICES).show();

   /*    return false;
   }

   return true;
  }
   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_RECOVER_PLAY_SERVICES) {

        if (resultCode == RESULT_OK) {
            // Make sure the app is not already connected or attempting to connect
            if (!mGoogleApiClient.isConnecting() &&
                    !mGoogleApiClient.isConnected()) {
                mGoogleApiClient.connect();
            }
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "Google Play Services must be installed.",
                    Toast.LENGTH_SHORT).show();
            finish();
        }
    }
}*/
  /*       public void statusCheck() {
    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();

    }
}
    private void buildAlertMessageNoGps() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        dialog.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }*/

    /*  public boolean isLocationServiceEnabled() {
    LocationManager lm = (LocationManager)
            this.getSystemService(Context.LOCATION_SERVICE);
    String provider = lm.getBestProvider(new Criteria(), true);
    return !LocationManager.PASSIVE_PROVIDER.equals(provider);
}*/
}

0 个答案:

没有答案