无法在片段中调用onActivityResult [英] Cannot call onActivityResult in fragment
问题描述
有一个主类mainActivity.和碎片.
There is a main class mainActivity. And fragments.
在片段Google地图中之一.功能是这样的:
In one of the fragments google map. The feature is this:
在关闭地理位置并打开应用程序后,将发送一个请求以允许位置检测,并且片段中的onActivityResult方法应重新启动.
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.
但是当我允许访问该位置时,onActivityResult方法仅在MainActivity中有效.
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!
我的尝试,但是该方法仍然无法解决:
主要活动
@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);
}
更新
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);
}
}
}
推荐答案
尝试在下面添加 super.onActivityResult(requestCode,resultCode,data);
,因为它首先调用了super方法.
Try to add super.onActivityResult(requestCode, resultCode, data);
below because it's call super method first.
主要活动
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!
这篇关于无法在片段中调用onActivityResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!