java.lang.ClassCastException while running new `runnableThread` in `Service` Class

主宰稳场 提交于 2019-12-04 19:15:48

First of all, Service extends ContextWrapper and is therefore a Context. If you need a reference to a Context you can simply reference your Service. You cannot cast a Service's base Context to an Activity.

If you want to work on the UI Thread from a Service, have a look at creating a Handler with Looper.getMainLooper().

...
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
            @Override
            public void run() {
                LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                LocationListener locationListener = new MyLocationListener();

                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
            });
...

The Android documentation offers good information on communicating to the UI thread. Have a look here:

http://developer.android.com/training/multiple-threads/communicate-ui.html

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