I’m trying to implement a Service and I have a classCastException in my Service.
Since Location isn’t Parcelable I wrap it in a ParcelableArrayList.
public class GPSService extends Service {
public void setLocation(Location location) {
ArrayList<Location> locationArrayList = new ArrayList<Location>(1);
locationArrayList.add(location);
Bundle b = new Bundle();
b.putParcelableArrayList("location", locationArrayList);
// try with an arrayList instead of just getExtra doesn't change anything :(
ArrayList<GPSResultReceiver> resultReceiverArrayList = intent.getParcelableArrayListExtra("receiver");
// this is a resultReceiver and not a GPSResultReceiver
// where did the upcast happen?
GPSResultReceiver receiver = resultReceiverArrayList.get(0);
Log.d("ResultClass", receiver.getClass().toString());
receiver.onReceiveResult(1111, b);
}
My Activity looks as following:
public class MyActivity extends Activity implements GPSResultReceiver.Receiver {
void startService() {
resultReceiver = new GPSResultReceiver(new Handler());
resultReceiver.setReceiver(this);
final Intent intent = new Intent(Intent.ACTION_SEND, null, this, GPSService.class);
// intent.putExtra("receiver", resultReceiver);
ArrayList<GPSResultReceiver> resultReceiverArrayList = new ArrayList<GPSResultReceiver>(1);
resultReceiverArrayList.add(resultReceiver);
intent.putParcelableArrayListExtra("receiver", resultReceiverArrayList);
serviceRunning = true;
startService(intent);
}
My GPSResultReceiver:
public class GPSResultReceiver extends ResultReceiver {
private Receiver resultReceiver;
public GPSResultReceiver(Handler handler) {
super(handler);
}
public void setReceiver(Receiver receiver) {
resultReceiver = receiver;
}
public interface Receiver {
public void onReceiveResult(int resultCode, Bundle resultData);
}
@Override
public void onReceiveResult(int resultCode, Bundle resultData) {
if (resultReceiver != null) {
resultReceiver.onReceiveResult(resultCode, resultData);
}
}
}
So why does this cast occur here and how can I work around it?
Thanks in advance
Seems it works as expected, because CREATOR of ResultReceiver creates ResultReceiver, but not it’s child classes.
The point here is following: actually, You don’t need GPSResultReceiver in the service. Just ResultReceiver is quite enough to send results back, but You should call public void send (int resultCode, Bundle resultData), but not
onReceiveResult.So, it would look like
Service: