カスタム サービスにバインドしようとしていますが、うまくいきません。
私のカスタムサービス
public class CustomService extends Service {
private CustomReceiver mReceiver;
private final CustomBinder mBinder = new CustomBinder();
public class CustomBinder extends Binder implements ICustomService {
// Implementation of the interface
}
public interface ICustomService {
// Public interface to comunicate to the service
}
@Override
public IBinder onBind(Intent intent) {
Log.d("customservice", "Service bound.");
mReceiver = intent.getParcelableExtra("receiver"); // ERROR HERE!
return mBinder;
}
// Other methods
私のカスタムレシーバー
public class CustomReceiver extends ResultReceiver {
public interface IReceiver {
public void onReceiveResult(int resultCode, Bundle resultData);
}
private IReceiver mReceiver;
public CustomReceiver(Handler handler) {
super(handler);
}
public void setReceiver(IReceiver receiver) {
mReceiver = receiver;
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (mReceiver != null) {
mReceiver.onReceiveResult(resultCode, resultData);
}
}
}
私の活動
public class MainActivity extends Activity implements CustomReceiver.IReceiver {
IRegressiveService mService;
CustomReceiver mReceiver;
boolean mBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
mService = (ICustomService) service;
mBound = true;
}
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
//...
mReceiver = new CustomReceiver(new Handler());
mReceiver.setReceiver(this);
Intent bindServiceIntent = new Intent(this, CustomService.class);
bindServiceIntent.putExtra("receiver", mReceiver);
bindService(bindServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
public void onReceiveResult(int resultCode, Bundle resultData) {
//...
}
//...
}
スタックトレース (不完全)
04-29 20:23:55.851: E/AndroidRuntime(690): FATAL EXCEPTION: main
04-29 20:23:55.851: E/AndroidRuntime(690): java.lang.RuntimeException: Unable to bind to service [package].CustomService@44f38cd8 with Intent { cmp=[package].CustomService (has extras) }: java.lang.ClassCastException: android.os.ResultReceiver
04-29 20:23:55.851: E/AndroidRuntime(690): at android.app.ActivityThread.handleBindService(ActivityThread.java:2996)
[...]
04-29 20:23:55.851: E/AndroidRuntime(690): Caused by: java.lang.ClassCastException: android.os.ResultReceiver
04-29 20:23:55.851: E/AndroidRuntime(690): at [package].CustomService.onBind(CustomService.java:37)
04-29 20:23:55.851: E/AndroidRuntime(690): at android.app.ActivityThread.handleBindService(ActivityThread.java:2983)
[...]
要するに
アクティビティでは、「レシーバー」キーを使用してCustomReceiver
(サブクラス)のインスタンスをサービスに渡します。ResultReceiver
しかし、このオブジェクトを回復しようとすると、サービスでClassCastException
発生します。なんで?どうすればこれを修正できますか?
API レベル 8 をターゲットにしています。
そして、他のSOの質問ではこの動作を見つけることができません。