0

I have run into the ClassCastException when using IBinder for android within a process. Following most of the online guides, inside of my service, I have

public class TestBinder extends Binder { 
}

In my client,

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

{

EDIT

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

2 回答 2

1

将该行更改为 -

IBinder mIBeaconBinder = (TestBinder)service;

由于您扩展了活页夹对象,因此您还实现了它的接口,即 IBinder,您可以在此处阅读更多内容,以防万一不起作用(并且您仍然有异常),请在此处查看如何扩展服务类(同时添加一个活页夹),而不是如何将该服务绑定到一个活动,我为您标记了相关行。

于 2014-04-02T09:20:18.850 回答
1

正确的演员阵容是

testService mService = ((testService.TestBinder)service).getService();
于 2014-04-02T09:24:39.200 回答