简体   繁体   中英

Location Permission In Android Fragment

I hope this will be a simple fix and someone can help me.

I have an app that needs users location in order to use the lat and lng to get the weather of their location. I am able to get the user location after I choose to allow the permission, leave the fragment and then go back into it again. The problem lies when I choose allow on the popup. I need to immediately get the location. Hopefully my code is self explanatory.

I took the liberty of removing all code that was not pertinent to my issue. Furthermore, I have attempted to call onStart() with no success.

public class FragmentLocalWeather extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

private static final int PERMISSION_ACCESS_COARSE_LOCATION = 0;
private GoogleApiClient googleApiClient;

public FragmentLocalWeather() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.local_weather_fragment, container, false);

    googleApiClient = new GoogleApiClient.Builder(this.getActivity(), this, this).addApi(LocationServices.API).build();

    if (ContextCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this.getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                PERMISSION_ACCESS_COARSE_LOCATION);
    }

    setHasOptionsMenu(true);

    return view;
}

@Override
public void onStart() {
    super.onStart();
    if (googleApiClient != null) {
        googleApiClient.connect();
    }
}

@Override
public void onStop() {
    googleApiClient.disconnect();
    super.onStop();

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_ACCESS_COARSE_LOCATION:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // ********** problem Area **********
                // Need to user location here.
            } else {
                Toast.makeText(this.getActivity(), "Need your location!", Toast.LENGTH_SHORT).show();
            }
            break;
    }
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_local_weather, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    switch (id) {
        case R.id.action_settings: {

        }
        case R.id.action_refresh: {
            onStart();
        }
    }

    return true;
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ContextCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

        double lat = lastLocation.getLatitude(), lon = lastLocation.getLongitude();
        Log.d("dozer74", "===========================>>>>>>>>>>>>> " + lat + " : " + lon);
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

In addition to what Marcin was suggesting (calling googleApiClient.connect() in your problem area) I think you need to use the requestPermissions method in the fragment instead of ActivityCompat.requestPermissions.

The requestPermissions method in the fragment will call the onRequestPermissionsResult you have defined in the fragment while the method you are currently using will call onRequestPermissionsResult() inside of your activity (which Im guessing you haven't overriden).

Thus you onCreate will look more like:

   if (ContextCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
            PERMISSION_ACCESS_COARSE_LOCATION);
}

Try this to get manifest permission in fragment

if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM