在`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