简体   繁体   English

使用服务时ClassCastException

[英]ClassCastException while using service

I defined a local Service: 我定义了一个本地服务:

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;
    }    
}

The corresponding interface: 相应的界面:

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

    public interface IServiceBinder {
        IComService getService();
    }
}

Then i try to bind the service in another activity in another application, where the same interface is available: 然后我尝试将服务绑定到另一个应用程序中的另一个活动中,其中相同的接口可用:

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

and

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 ");
    }
};

but the line 但是这条线

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

always throws a 总是抛出一个

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

I can't explain why, I followed the app sample on http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceBinding.html 我无法解释原因,我在http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceBinding.html上关注了应用示例

Any hints would be nice! 任何提示都会很好!

You need to use AIDL to define interfaces that span applications (so-called "remote services"). 您需要使用AIDL来定义跨应用程序的接口(所谓的“远程服务”)。 You followed a local binding example, but you are not using local binding. 您遵循了本地绑定示例,但您没有使用本地绑定。 Try this and this sample project for a remote binding example using AIDL. 试试这个这个示例项目使用AIDL远程绑定的例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM