Android:bindService不会连接到远程(AIDL)服务,我也不知道为什么

时间:2010-12-05 01:03:29

标签: android service aidl

我正在尝试在Android 2.2.1上开发基本的AIDL服务。似乎所有东西都构建并安装好了,但bindService()就不会 - 好吧,绑定。我的ServiceConnection类没有被调用。我真的不知道为什么不,所以任何帮助将不胜感激。这是我的客户活动:

public class go extends Activity {
    protected static final String TAG = "HOSPlayerClient";
    private IHOSPlayerService hosPlayerService = null;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.v(TAG, "onServiceConnection");
            hosPlayerService = IHOSPlayerService.Stub.asInterface(service);
            callService();
        }

        public void onServiceDisconnected(ComponentName name) {
            Log.v(TAG, "onServiceDisconnected");
        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.v(TAG, IHOSPlayerService.class.getName());
        boolean bound = bindService(
                new Intent(IHOSPlayerService.class.getName()),
                serviceConnection, Context.BIND_AUTO_CREATE);

        Log.v(TAG, bound ? "service bound" : "service bind failed");
    }

    private void callService() {
        try {
            hosPlayerService.go();
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

...以下是我认为是AIDL服务的相关部分:

public class HOSPlayerService extends Service
{
 private static final String TAG = "HOSPlayerService";

 public class HOSPlayerServiceImpl extends IHOSPlayerService.Stub
 {
  public void go() throws RemoteException
  {
   Log.v(TAG, "go called");
  }
 }

 @Override
 public IBinder onBind(Intent intent) 
 {
  // TODO Auto-generated method stub
  return new HOSPlayerServiceImpl();
 }
}

...和AIDL文件:

package com.HOS.ahos.HOSPlayerService;

interface IHOSPlayerService
{
 void go();
}

1 个答案:

答案 0 :(得分:2)

尝试将以下代码放在服务文件中 -

@Override
public IBinder onBind(Intent arg0) {
    //arg0.getExtras();
    return binder;
}

Service应该返回binder,然后只调用你的MyServiceConnection类。