【发布时间】:2011-11-07 17:31:42
【问题描述】:
好的,我是 android 开发新手,我正在尝试绑定到服务,以便在服务启动后调用该服务的方法。下面描述的 Activity 和 Service 都是同一个应用程序的一部分,所以那里不应该有任何问题,但是每次我运行我的应用程序时,我都会收到以下错误:
java.lang.ClassCastException: android.os.BinderProxy
发生这种情况的行是:
LocalBinder binder = (LocalBinder) service;
我的Activity代码(简体为):
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 Exception 的含义,但不明白该怎么做!我已经按照谷歌文档中的示例进行操作,但它仍然无法正常工作。任何人都可以阐明可能导致这种情况的原因吗?
提前致谢!
【问题讨论】:
标签: android binding service android-activity classcastexception