获取用户对权限的响应时无法恢复活动

时间:2017-01-19 00:07:20

标签: xamarin.android user-permissions

我试图获得用户访问GPS的权限。我不确定我是否正确使用它,因为当我访问该屏幕时,我遇到了错误:

  

java.lang.RuntimeException:无法恢复活动{com.SuppShoesTest.SuppShoesTest / md5056fe371b3902b2cc984ad5dda4f920b.gMaps}:android.util.SuperNotCalledException:Activity {com.SuppShoesTest.SuppShoesTest / md5056fe371b3902b2cc984ad5dda4f920b.gMaps}没有调用super。的onResume()   01-18 23:57:20.419 E / AndroidRuntime(2712):在android.app.ActivityThread.performResumeActivity(ActivityThread.java:3103)   01-18 23:57:20.419 E / AndroidRuntime(2712):在android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3134)   01-18 23:57:20.419 E / AndroidRuntime(2712):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2481)   01-18 23:57:20.419 E / AndroidRuntime(2712):在android.app.ActivityThread.-wrap11(ActivityThread.java)   01-18 23:57:20.419 E / AndroidRuntime(2712):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1344)   01-18 23:57:20.419 E / AndroidRuntime(2712):在android.os.Handler.dispatchMessage(Handler.java:102)   01-18 23:57:20.419 E / AndroidRuntime(2712):在android.os.Looper.loop(Looper.java:148)   01-18 23:57:20.419 E / AndroidRuntime(2712):在android.app.ActivityThread.main(ActivityThread.java:5417)   01-18 23:57:20.419 E / AndroidRuntime(2712):at java.lang.reflect.Method.invoke(Native Method)   01-18 23:57:20.419 E / AndroidRuntime(2712):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)   01-18 23:57:20.419 E / AndroidRuntime(2712):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)   01-18 23:57:20.419 E / AndroidRuntime(2712):引起:android.util.SuperNotCalledException:Activity {com.SuppShoesTest.SuppShoesTest / md5056fe371b3902b2cc984ad5dda4f920b.gMaps}没有调用super.onResume()   01-18 23:57:20.419 E / AndroidRuntime(2712):在android.app.Activity.performResume(Activity.java:6314)   01-18 23:57:20.419 E / AndroidRuntime(2712):在android.app.ActivityThread.performResumeActivity(ActivityThread.java:3092)

这是我的代码

{
    private GoogleMap maps;
    string dman;
    string date;
    string time;
    public static readonly EndpointAddress EndPoint = new EndpointAddress("http://192.168.1.3:9608/SuppShoes.svc");
    private SuppShoesClient _client;
    ArrayList postal;
    double mylat;
    double mylong;
    Location _currentLocation;
    LocationManager _locationManager;
    LinearLayout layout;
    string _locationProvider;
    PolylineOptions rect = new PolylineOptions();
    readonly string[] PermissionsLocation = 
{
  Manifest.Permission.AccessCoarseLocation,
  Manifest.Permission.AccessFineLocation
};

    const int RequestLocationId = 0;
    protected override void OnCreate(Bundle savedInstanceState)
    {

        base.OnCreate(savedInstanceState);

        SetContentView(Resource.Layout.gMap);
        layout = (LinearLayout)FindViewById(Resource.Id.layout);
        InitializeHelloWorldServiceClient();
        dman = Intent.GetStringExtra("Dman");
        date = Intent.GetStringExtra("date");
        time = Intent.GetStringExtra("Time");
        InitializeLocationManager(); 
        SetUpMap();


        // Create your application here
    }

    private void InitializeHelloWorldServiceClient()
    {


        BasicHttpBinding binding = CreateBasicHttp();
        _client = new SuppShoesClient(binding, EndPoint);


    }

    private static BasicHttpBinding CreateBasicHttp()
    {
        BasicHttpBinding binding = new BasicHttpBinding
        {
            Name = "basicHttpBinding",
            MaxBufferSize = 2147483647,
            MaxReceivedMessageSize = 2147483647
        };
        TimeSpan timeout = new TimeSpan(0, 0, 30);
        binding.SendTimeout = timeout;
        binding.OpenTimeout = timeout;
        binding.ReceiveTimeout = timeout;
        return binding;
    }

    public async void OnLocationChanged(Location location)
    {
        _currentLocation = location;
        if (_currentLocation == null)
        {

        }
        else
        {

            AddMarker();
        }

    }
    public void OnProviderDisabled(string provider) { }

    public void OnProviderEnabled(string provider) { }

    public void OnStatusChanged(string provider, Availability status, Bundle extras) { }




    protected override void OnResume()
    {


            const string permission = Manifest.Permission.AccessFineLocation;
            if (CheckSelfPermission(permission) == (int)Permission.Granted)
            {
                base.OnResume();
                _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);

            }
        if (ShouldShowRequestPermissionRationale(permission))
              {

                //Explain to the user why we need to read the contacts
                  Android.Support.Design.Widget.Snackbar.Make(layout,"Location access is required to show coffee shops nearby.", Android.Support.Design.Widget.Snackbar.LengthIndefinite)
                        .SetAction("OK", v => RequestPermissions(PermissionsLocation, RequestLocationId))
                        .Show();
                return;
              }

//最后使用权限列表和Id请求权限   RequestPermissions(PermissionsLocation,RequestLocationId);         }

                    public override async void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
                    {
                      switch (requestCode)
                      {
                        case RequestLocationId:
                        {
                          if (grantResults[0] == Permission.Granted)
                          {
                            //Permission granted
                              var snack = Android.Support.Design.Widget.Snackbar.Make(layout, "Location permission is available, getting lat/long.", Android.Support.Design.Widget.Snackbar.LengthShort);
                            snack.Show();

                            base.OnResume();
                          }
                          else
                          {
                            //Permission Denied :(
                            //Disabling location functionality
                              var snack = Android.Support.Design.Widget.Snackbar.Make(layout, "Location permission is denied.",  Android.Support.Design.Widget.Snackbar.LengthShort);
                            snack.Show();
                          }
                        }
                        break;
                      }
                    }
    protected override void OnPause()
    {
        base.OnPause();
        _locationManager.RemoveUpdates(this);
    }
    void InitializeLocationManager()
    {
        _locationManager = (LocationManager)GetSystemService(LocationService);
        Criteria criteriaForLocationService = new Criteria
        {
            Accuracy = Accuracy.Fine
        };
        IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);

        if (acceptableLocationProviders.Any())
        {
            _locationProvider = acceptableLocationProviders.First();
        }
        else
        {
            _locationProvider = string.Empty;
        }

    }

    void AddMarker()
    {
        RunOnUiThread(() =>
        {
            LatLng current = new LatLng(_currentLocation.Latitude, _currentLocation.Longitude);
            MarkerOptions asd = new MarkerOptions();

            asd.SetPosition(current);

            asd.InvokeIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.green));
            maps.AddMarker(asd);
            rect.Add(current);
        });
    }
    private void SetUpMap()
    {
        if(maps==null)
        {
            FragmentManager.FindFragmentById<MapFragment>(Resource.Id.googlemap).GetMapAsync(this);
        }

    }
    public void OnMapReady(GoogleMap googleMap)
    {
        this.maps = googleMap;

        LatLng latlng = new LatLng(Convert.ToDouble(1.3521), Convert.ToDouble(103.8198));
        CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(latlng,10);
        maps.MoveCamera(camera);

        _client.getPostalAsync(dman, date, time);
        _client.getPostalCompleted += _client_getPostalCompleted;
    }


    private void _client_getPostalCompleted(object sender, getPostalCompletedEventArgs e)
    {

        RunOnUiThread(() =>
        {


        foreach (var item in e.Result)
        {


            LatLng latlng = new LatLng(item.lat1, item.longi2);
            MarkerOptions options = new MarkerOptions()    
            .SetPosition(latlng)
            .SetTitle(item.companyname2)
            .SetSnippet(item.DevID.ToString());
            maps.AddMarker(options);
            rect.Add(latlng);
            Polyline polyline = maps.AddPolyline(rect);
        }
    });


    }
}

2 个答案:

答案 0 :(得分:2)

对于Xamarin表单,需要调用base.OnResume()以避免此异常。与往常一样,这需要位于重写的OnResume()方法的顶部。

答案 1 :(得分:0)

您的异常Caused by: android.util.SuperNotCalledException清楚明了,您必须添加super.onResume()才能执行恢复生命周期,因为您的方法是@Overriding

super内致电onResume();

super.onResume();