我正在尝试使用从 Intent 到intentService的自定义ResultReciever,但出现此bizare错误。

有什么想法吗?

在使用resulReciever作为回调时遵循了本指南

http://lalit3686.blogspot.co.uk/2012/06/how-to-update-activity-from-service.html

这是我从启动服务的 Activity 获得的代码:

private void doNetworkInitCalls() {
    intent = new Intent(getApplicationContext(), NetworkService.class);
    intent.setAction(NetworkService.ACTION_GET_CITY_INFO);
    intent.putExtra(NetworkService.EXTRA_LATLON, new LatLon(51.5073, 0.1276));
    MyReciever reciever = new MyReciever(null);
    reciever.setOnCityInfoRecieved(this);
    intent.putExtra(MyReceiver.RESULT_RECEIEVER_EXTRA, reciever);
    startService(getCityInfoIntent);
}

MyReciever类别:
public class MyReciever extends ResultReceiver {

    public static final String RESULT_CITY_INFO = "cityInfoData";
    public static final String RESULT_RECEIEVER_EXTRA = "reciever";

    public MyReciever(Handler handler) {
        super(handler);
    }

    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        super.onReceiveResult(resultCode, resultData);
    }
}

IntentService:
public class NetworkService extends IntentService {

 @Override
 protected void onHandleIntent(Intent intent) {
     if (intent != null) {
         MyReciever reciever = intent.getParcelableExtra(MyReciever.RESULT_RECEIEVER_EXTRA); //fails on this line
    }
}

最佳答案

那这个呢 :

public class NetworkService extends IntentService {

 @Override
 protected void onHandleIntent(Intent intent) {
     if (intent != null) {
         ResultReceiver reciever = intent.getParcelableExtra(MyReciever.RESULT_RECEIEVER_EXTRA);
    }
}

由于尚未在MyReciever中重新定义CREATOR,因此它将创建ResultReceiver实例。只需按原样从ResultReceiver接收您的ResultReceiver实例。

关于无法将java.lang.ClassCastException : android. os.ResultReceiver强制转换为com.hello.utils.network.MyReciever,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26383789/

10-12 00:23