使用服务时ClassCastException

时间:2010-05-02 20:27:41

标签: java android

我定义了一个本地服务:

public class ComService extends Service implements IComService {
    private IBinder binder = new ComServiceBinder();

    public class ComServiceBinder extends Binder implements IComService.IServiceBinder {
        public IComService getService() {
            return ComService.this;
        }
    }

    public void test(String msg) {
        System.out.println(msg);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }    
}

相应的界面:

public interface IComService {
    public void test(String msg);

    public interface IServiceBinder {
        IComService getService();
    }
}

然后我尝试将服务绑定到另一个应用程序中的另一个活动中,其中可用的界面相同:

bindService(new Intent("ch.ifi.csg.games4blue.gamebase.api.ComService"), conn, Context.BIND_AUTO_CREATE);

private ServiceConnection conn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.i("INFO", "Service bound " + name);
        comService = ((IComService.IServiceBinder)service).getService();
        serviceHandler.sendEmptyMessage(0);
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        Log.i("INFO", "Service Unbound ");
    }
};

但行

comService = ((IComService.IServiceBinder)service).getService();

总是抛出一个

05-02 22:12:55.922: ERROR/AndroidRuntime(622): java.lang.ClassCastException: android.os.BinderProxy

我无法解释原因,我在http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceBinding.html

上关注了应用示例

任何提示都会很好!

1 个答案:

答案 0 :(得分:9)

您需要使用AIDL来定义跨应用程序的接口(所谓的“远程服务”)。您遵循了本地绑定示例,但您没有使用本地绑定。使用AIDL尝试thisthis示例项目以获取远程绑定示例。