私はAndroid開発が初めてで、サービスにバインドしようとしています。サービスが開始されるとメソッドを呼び出すことができます。以下に説明するアクティビティとサービスは同じアプリケーションに含まれているため、そこに問題はないはずですが、アプリを実行するたびに次のエラーが表示されます。サービスにバインドするときのAndroid ClassCast例外
java.lang.ClassCastException:android.os.BinderProxy
これに起こる線である:
LocalBinder binder = (LocalBinder) service;
My活動コードである(簡略化):
public class Main extends Activity {
boolean gpsBound = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
/** Called whenever the activity is started. */
@Override
protected void onStart() {
super.onStart();
// Bind to GPSService
Intent i = new Intent(this, GPSService.class);
startService(i);
bindService(i, connection, Context.BIND_AUTO_CREATE);
}
/** service binding */
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// After binding to GPSService get the instance of it returned by IBinder
LocalBinder binder = (LocalBinder) service;
gpsBound = true;
}
public void onServiceDisconnected(ComponentName className) {
gpsBound = false;
}
};
}
サービス:
public class GPSService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent i) {
// TODO Auto-generated method stub
return new LocalBinder<GPSService>(this);
}
/**
* Our implementation of LocationListener that handles updates given to us
* by the LocationManager.
*/
public class CustomLocationListener implements LocationListener {
DBHelper db;
CustomLocationListener() {
super();
}
// Overridden methods here...
}
}
そして最後に、私のLocalBinder:
/**
* A generic implementation of Binder to be used for local services
* @author Geoff Bruckner 12th December 2009
*
* @param <S> The type of the service being bound
*/
public class LocalBinder<S> extends Binder {
private String TAG = "LocalGPSBinder";
private WeakReference<S> mService;
public LocalBinder(S service){
mService = new WeakReference<S>(service);
}
public S getService() {
return mService.get();
}
}
私はClassCast例外の意味を理解が、何をすべきか理解できません!私はGoogleのドキュメントの例に従ってきましたが、まだ動作していません。誰かがこれを引き起こしている可能性のあることについて何か光を当てることができますか?
ありがとうございます!
が好き意味するか: 「LocalBinderバインダー=(LocalBinder )サービスを;」 それでも同じエラーが発生する場合は! –
私はジェネリック医薬品を完全に取り出す方向に傾いていた。私はすぐに書いているboundServiceの使い方の簡単なサンプルで編集します。 –
ジェネリック医薬品を使わずに自分自身に行くことができますが、もしあなたが素晴らしい例を与えることができれば!ありがとう、ジェームズ –