Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

google maps - Android app closes when showing location permissions request dialog

I'm building a map application so I want to request location permissions at runtime. Actually the app closes by itself when the location permissions shows up.

I have to select the permission and then to open the app again.

Here is the code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    mapView = mapFragment.getView();

    getSupportActionBar().setTitle("My map");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);


    if ( Build.VERSION.SDK_INT >= 23){
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED  ){
            requestPermissions(new String[]{
                            android.Manifest.permission.ACCESS_FINE_LOCATION},
                    LOCATION_PERMISSION_REQUEST_CODE);
            //Provo a chiamare un dialog per la localizzazione
            settingsrequest();
            return ;
        }
    }
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    MobileAds.initialize(this);

    mAdView = findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

}

public void settingsrequest() {
    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10);
    mLocationRequest.setSmallestDisplacement(10);
    mLocationRequest.setFastestInterval(10);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    LocationSettingsRequest.Builder builder = new
            LocationSettingsRequest.Builder();
    builder.addLocationRequest(mLocationRequest);

    Task<LocationSettingsResponse> task = LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());

    task.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
        @Override
        public void onComplete(Task<LocationSettingsResponse> task) {
            try {
                LocationSettingsResponse response = task.getResult(ApiException.class);
                // All location settings are satisfied. The client can initialize location
                // requests here.

            } catch (ApiException exception) {
                switch (exception.getStatusCode()) {
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be fixed by showing the
                        // user a dialog.
                        try {
                            // Cast to a resolvable exception.
                            ResolvableApiException resolvable = (ResolvableApiException) exception;
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            resolvable.startResolutionForResult(
                                    MapsActivity.this,
                                    101);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        } catch (ClassCastException e) {
                            // Ignore, should be an impossible error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way to fix the
                        // settings so we won't show the dialog.
                        break;
                }
            }
        }
    });


}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
        return;
    }

    if (PermissionUtils.isPermissionGranted(permissions, grantResults, Manifest.permission.ACCESS_FINE_LOCATION)) {
        // Enable the my location layer if the permission has been granted.
        enableMyLocation();
    } else {
        // Permission was denied. Display an error message
        // Display the missing permission error dialog when the fragments resume.
        permissionDenied = true;
    }
}

public void setUpMap() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    fusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        Location lastLocation = location;
                        LatLng currentLatLng = new LatLng(location.getLatitude(), location.getLongitude());
                        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 14f));
                    } else {
                        LatLng cippo109 = new LatLng(41.52123, 13.50557);
                        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(cippo109, 10f));
                    }
                }
            });
}

@SuppressLint("MissingPermission")
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.setOnMyLocationButtonClickListener(this);
    mMap.setOnMyLocationClickListener(this);
    enableMyLocation();
    setUpMap();

do something here...
}

I tried to search on a lot of other questions but nothing is resolving my issue. Since the full code is not relevant, I pasted functions about permissions. The map is working well after permissions granted.

Stack trace:

    2021-01-22 10:33:44.370 512-542/system_process I/ActivityTaskManager: Displayed com.google.android.permissioncontroller/com.android.permissioncontroller.permission.ui.GrantPermissionsActivity: +2s945ms
2021-01-22 10:33:44.393 512-1896/system_process I/system_server: oneway function results will be dropped but finished with status OK and parcel size 4
2021-01-22 10:33:44.868 512-1896/system_process W/NotificationService: Toast already killed. pkg=it.iovara.trainassistant token=android.os.BinderProxy@ddf8206
2021-01-22 10:33:44.876 694-694/com.android.systemui W/ToastPresenter: Error calling back it.iovara.trainassistant to notify onToastHide()
    android.os.DeadObjectException
        at android.os.BinderProxy.transactNative(Native Method)
        at android.os.BinderProxy.transact(BinderProxy.java:540)
        at android.app.ITransientNotificationCallback$Stub$Proxy.onToastHidden(ITransientNotificationCallback.java:141)
        at android.widget.ToastPresenter.hide(ToastPresenter.java:248)
        at com.android.systemui.toast.ToastUI.hideCurrentToast(ToastUI.java:112)
        at com.android.systemui.toast.ToastUI.hideToast(ToastUI.java:107)
        at com.android.systemui.statusbar.CommandQueue$H.handleMessage(CommandQueue.java:1295)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2021-01-22 10:33:44.838 0-0/? I/binder: 694:694 transaction failed 29189/-22, size 104-0 line 3146
2021-01-22 10:33:44.938 150-150/? E/SELinux: avc:  denied  { find } for pid=16288 uid=2000 name=car_service scontext=u:r:shell:s0 tcontext=u:object_r:default_android_service:s0 tclass=service_manager permissive=0
2021-01-22 10:33:44.942 16288-16288/? W/cmd: Can't find service car_service
2021-01-22 10:33:45.911 150-150/? E/SELinux: avc:  denied  { find } for pid=16294 uid=2000 name=car_service scontext=u:r:shell:s0 tcontext=u:object_r:default_android_service:s0 tclass=service_manager permissive=0
2021-01-22 10:33:45.911 16294-16294/? W/cmd: Can't find service car_service
2021-01-22 10:33:46.311 362-362/? I/perfetto: probes_producer.cc:329  Producer stop (id=98)
2021-01-22 10:33:46.315 363-363/? I/perfetto: ng_service_impl.cc:1948 Tracing session 98 ended, total sessions:0
question from:https://stackoverflow.com/questions/65843232/android-app-closes-when-showing-location-permissions-request-dialog

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

DeadObjectException - This means that your service had already stopped - either killed from the OS, or stopped from your application.

Check this and this

And it may be memory leak problem. Check this answer


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...