在`Service`类中运行新的`runnableThread`时出现java.lang.ClassCastException
我有一个应用程序,包含一个broadcastReceiver
,它监听所有新收到的短信。 如果接收到任何新的SMS,则此BroadcastReceiver
启动运行GPS并返回坐标的后台Service
,此坐标检索需要运行一个新线程,在Service类中没有getApplicationContext()
所以我使用’getContentBase()’启动新线程这是代码
((Activity)getBaseContext())。runOnUiThread(new Runnable(){
((Activity)getBaseContext()).runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new MyLocationListener(); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 10, locationListener); } }
我得到了这个例外
E/AndroidRuntime(24700): java.lang.ClassCastException: android.app.ContextImpl cannot be cast to android.app.Activity
这是接收器在清单中定义的方式
以下是服务在BroadcastReceiver
启动方式
@Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub context.startService(new Intent(con, MyService.class)); }
而这个例外就在这条线上
((Activity)getBaseContext()).runOnUiThread(new Runnable()
我通过堆栈和谷歌搜索了很多,非答案解决了我的问题,并尝试将上下文从BroadCastReceiver
发送到Service
类,再次有相同的例外,任何帮助??
首先, Service
扩展了ContextWrapper
,因此是一个Context
。 如果您需要对Context的引用,您可以简单地引用您的服务。 您无法将服务的基本上下文强制转换为Activity
。
如果您想从服务Handler
UI线程,请查看使用Looper.getMainLooper()
创建Handler
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); }); ...
Android文档提供了有关与UI线程进行通信的良好信息。 看看这里:
http://developer.android.com/training/multiple-threads/communicate-ui.html
- java.lang.NoClassDefFoundError:如何修复此错误?
- Android:如何在应用程序执行其他工作时持续保存传感器数据
- 如何同步两个Listview位置
- 如何实现高效的Alpha-Beta修剪游戏搜索树?
- Java(Android)IOException:在索引7处预期的权限:http://
- java.lang.IllegalStateException:在Android Studio中找不到按钮的onClick方法
- 使用Service,AsyncTask和Thread制作智能Android Media Player应用程序
- Android – 用HAPI v 2.2和DefaultHapiContext解析HL7消息
- Android自定义对话框NullPointerException