Reputation: 406
There is a main class mainActivity. And fragments.
In one of the fragments google map. The feature is this:
When geolocation is turned off and the application is turned on, a request is sent to allow location detection and the onActivityResult method in the fragment should restart.
But the onActivityResult method only works in MainActivity when I give access to the location.
Please tell me how to fix this situation how to run the method in the fragment? Thank you for your help!
My attempts, but the method still does not work out:
Main Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
MapFragment
// Get the current location of the device and set the position of the map.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 51) {
if (resultCode == RESULT_OK) {
getDeviceLocation();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
UPDATE
public class MapFragment extends Fragment implements OnMapReadyCallback {
// Keys for storing activity state.
private static final String KEY_CAMERA_POSITION = "camera_position";
private static final String KEY_LOCATION = "location";
// The entry point to the Fused Location Provider.
private FusedLocationProviderClient _mFusedLocationProviderClient;
private CameraPosition _mCameraPosition;
// A default location (Минск, Беларусь) and default zoom to use when location permission is
// not granted.
private final LatLng mDefaultLocation = new LatLng(53.9000000, 27.5666700);
private static final int DEFAULT_ZOOM = 17;
private GoogleMap _map;
// The geographical location where the device is currently located. That is, the last-known
// location retrieved by the Fused Location Provider.
private Location _mLastKnownLocation;
private LocationCallback locationCallback;
SharedManager _manager;
Connect _connect;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_manager = new SharedManager(getActivity());
_connect = new Connect();
// Construct a FusedLocationProviderClient.
_mFusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(getActivity());
// Retrieve location and camera position from saved instance state.
if (savedInstanceState != null) {
_mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
_mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
}
}
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_map, container, false);
//Инициализация карты
initializeMap();
return root;
}
/**
* Saves the state of the map when the activity is paused.
*/
@Override
public void onSaveInstanceState(Bundle outState) {
if (_map != null) {
outState.putParcelable(KEY_CAMERA_POSITION, _map.getCameraPosition());
outState.putParcelable(KEY_LOCATION, _mLastKnownLocation);
super.onSaveInstanceState(outState);
}
}
@SuppressLint("MissingPermission")
@Override
public void onMapReady(GoogleMap googleMap) {
_map = googleMap;
_map.getUiSettings().setZoomControlsEnabled(false);
_map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
updateLocationUI();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
SettingsClient settingsClient = LocationServices.getSettingsClient(getActivity());
Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());
task.addOnSuccessListener(getActivity(), new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
getDeviceLocation();
}
});
task.addOnFailureListener(getActivity(), new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if (e instanceof ResolvableApiException) {
ResolvableApiException resolvable = (ResolvableApiException) e;
try {
resolvable.startResolutionForResult(getActivity(), 51);
} catch (IntentSender.SendIntentException e1) {
e1.printStackTrace();
}
}
}
});
}
// Get the current location of the device and set the position of the map.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//TODO: код не отрабатывает, когда выключен локатор , после разрешения снова найти локацию
if (requestCode == 51) {
if (resultCode == RESULT_OK) {
getDeviceLocation();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Gets the current location of the device, and positions the map's camera.
*/
@SuppressLint("MissingPermission")
private void getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
Task<Location> locationResult = _mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(getActivity(), new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
_mLastKnownLocation = task.getResult();
if (_mLastKnownLocation != null) {
_map.moveCamera(
CameraUpdateFactory.newLatLngZoom(
new LatLng(_mLastKnownLocation.getLatitude(),
_mLastKnownLocation.getLongitude()), 15));
} else {
final LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult == null) {
return;
}
_mLastKnownLocation = locationResult.getLastLocation();
_map.moveCamera(
CameraUpdateFactory.newLatLngZoom(
new LatLng(_mLastKnownLocation.getLatitude(),
_mLastKnownLocation.getLongitude()), 15));
_mFusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
};
_mFusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
} else {
Toast.makeText(getActivity(), "unable to get last location", Toast.LENGTH_SHORT).show();
Log.e(TAG, "Exception: %s", task.getException());
_map.moveCamera(CameraUpdateFactory
.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
}
}
});
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
private void updateLocationUI() {
if (_map == null) {
return;
}
try {
{
_map.setMyLocationEnabled(true);
_map.getUiSettings().setMyLocationButtonEnabled(true);
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
// Build the map.
private void initializeMap() {
if (_map == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_View);
mapFrag.getMapAsync(MapFragment.this);
}
}
}
Upvotes: 0
Views: 193
Reputation: 1496
Try to add super.onActivityResult(requestCode, resultCode, data);
below because it's call super method first.
Main Activity
YourFragment yourFragment = new YourFragment(); //And use this object to all over
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == YOUR_FRAGMENT_CODE) {
try {
yourFragment.onActivityResult(requestCode, resultCode, data);
} catch (Exception e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data); //Add Here
}
I hope this can help you!
Upvotes: 1