requestLocationUpdates throws exception

2020-04-30 16:04发布

问题:

I am creating a service that periodically updates the position. but using the following code, it throws me:

runException Can't create handler inside thread that has not called Looper.prepare()

This code is running inside doInBackground of Async class in service

private void UpdatePosition()
    {
        locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);


        Location location = 
                locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        showPosition(location);
        locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                showPosition(location);
            }
            public void onProviderDisabled(String provider){

            }
            public void onProviderEnabled(String provider){

            }
            public void onStatusChanged(String provider, int status, Bundle extras){
                Log.i("LocAndroid", "Provider Status: " + status);

            }
        };


        locManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 15000, 0, locationListener);
    }

I was reviewing several posts and found that request has to run in uithread, but do not know how or where to put it.

what can i do?

EDIT:

i'll add only this to my code and now isnt throw any error

private void UpdatePosition()
    {
        Looper.prepare();
        looper = Looper.myLooper();
        locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);


        Location location = 
                locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        showPosition(location);
        locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                showPosition(location);
            }
            public void onProviderDisabled(String provider){

            }
            public void onProviderEnabled(String provider){

            }
            public void onStatusChanged(String provider, int status, Bundle extras){
                Log.i("LocAndroid", "Provider Status: " + status);

            }
        };


        locManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 15000, 0, locationListener);
    }

but i dont know if its correct..what do you say?