问题
I have an application , contains a broadcastReceiver
which listens to all new received SMS
. If any new SMS received this BroadcastReceiver
starts a background Service
which runs GPS and return the coordinates , this coordinate retrieving needs a new thread to be run , in the Service class there is no getApplicationContext()
so I used 'getContentBase()' for starting the new thread this is the code
((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);
}
}
and I am getting this exception
E/AndroidRuntime(24700): java.lang.ClassCastException: android.app.ContextImpl cannot be cast to android.app.Activity
this is how the receiver defined in the manifest
<receiver
android:name=".BroadCastReceiver"
android:exported="true" >
<intent-filter android:priority="1000" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
and here is how the Service started in the BroadcastReceiver
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
context.startService(new Intent(con,
MyService.class));
}
and the exception is at this line
((Activity)getBaseContext()).runOnUiThread(new Runnable()
I've searched a lot through the stack and the google as well , non of the answers solved my issue and tried to send the context from the BroadCastReceiver
to the Service
class , again there was the same Exception , any help??
回答1:
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
来源:https://stackoverflow.com/questions/23324199/java-lang-classcastexception-while-running-new-runnablethread-in-service-cla