Search code examples
androidgeolocationtitanium

Application crashes before requestLocationPermissions


I am making application using ti.map on Titanium.

From Android6 permission system is changing . I have to give the permission not when installing but in the app running.

I made these code, but it works like this.

  • At first launch.

If you try to show map,it crashes. However alert (Allow to access this device's location?) remains.

  • Second launch If you touched yes at first launch. It works and correctly shows the map.

I think problem is ,crashes happen when trying to open the map before the return of the result of requestLocationPermissions dialog.

But, requestLocationPermissions dialog is triggered only when user try to open map by Ti.Geolocation.requestLocationPermissions. So it is impossible to ask user the permission before opening map in advance.

So in summary

I would like to fire requestLocationPermissions callback in advance.

So this is my code.

if (Ti.Platform.osname === 'android'){
    var hasLocationPermissions = Ti.Geolocation.hasLocationPermissions(Ti.Geolocation.AUTHORIZATION_ALWAYS);
    Ti.API.info('Ti.Geolocation.hasLocationPermissions : ' +  hasLocationPermissions);
    if (hasLocationPermissions) {
        Ti.API.info('You already have permission.');
    }
    else {
        Ti.Geolocation.requestLocationPermissions(Ti.Geolocation.AUTHORIZATION_ALWAYS, function(e) {
            Ti.API.info('Ti.Geolocation.requestLocationPermissions' +  e);
            if (e.success) {
                // Instead, probably call the same method you call if hasLocationPermissions() is true
                alert('You granted permission.');

            } else if (OS_ANDROID) {
                alert('You denied permission for now, forever or the dialog did not show at all because it you denied forever before.');

            } else {

        // We already check AUTHORIZATION_DENIED earlier so we can be sure it was denied now and not before
                Ti.UI.createAlertDialog({
                    title: 'You denied permission.',

                    // We also end up here if the NSLocationAlwaysUsageDescription is missing from tiapp.xml in which case e.error will say so
                    message: e.error
                }).show();
            }
        });
    }
}

And error messages are below.

[ERROR] TiApplication: (main) [13751,15075] Sending event: exception on thread: main msg:java.lang.SecurityException: my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION; Titanium 6.0.1,2016/12/19 16:51,undefined
[ERROR] TiApplication: java.lang.SecurityException: my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
[ERROR] TiApplication:  at com.google.maps.api.android.lib6.impl.az.c(:com.google.android.gms.DynamiteModulesB:50297)

Solution

  • on Android call the function without params

    Ti.Geolocation.hasLocationPermissions();
    

    Documentation