requestLocationUpdates throws exception

一个人想着一个人 提交于 2019-12-02 21:26:25

问题


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?

来源:https://stackoverflow.com/questions/13810662/requestlocationupdates-throws-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!