IBinder Android - ClassCastException:android.os.Handler& MessgerImpl

时间:2014-04-02 09:08:57

标签: android android-service android-service-binding

在进程中使用IBinder for android时,我遇到了ClassCastException。在大多数在线指南之后,在我的服务中,我有

public class TestBinder extends Binder { 
}

在我的客户中,

private ServiceConnection testServiceConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
                        TestBinder mIBeaconBinder = (TestBinder)service;
.....
            }
    }
TestBinder mIBeaconBinder = (TestBinder)service; this throws the exception. 

{

修改

public class TestBinder extends Binder { 
    public testService getService() { 
    // Return this instance of LocalService so clients can call public // methods 
      return        testService.this; 
    } 
  }

2 个答案:

答案 0 :(得分:1)

将该行更改为 -

IBinder mIBeaconBinder = (TestBinder)service;

由于你扩展了binder对象,你也实现了它的IBinder界面,你可以阅读更多here,如果不起作用(你仍然有一个激发)看看over here as for how to extend the service class(虽然添加了一个活页夹)而不是how to bind that service to an activity我为你标记了相关的行。

答案 1 :(得分:1)

正确的演员阵容

testService mService = ((testService.TestBinder)service).getService();