OnServiceConnected未被调用

时间:2013-02-18 12:23:18

标签: android android-service

我提到了Can't get service object (onServiceConnected never called)onServiceConnected not getting called , getting a null pointer exceptiononServiceConnected never called after bindService method,但未找到答案。

这是我的代码

@Override
    public void onStart() {
        super.onStart();
        Context context = getApplicationContext();
        Intent intent = new Intent(context, PodService.class);
        context.bindService(intent, mPodServiceConn, Context.BIND_AUTO_CREATE);

    }




    private ServiceConnection mPodServiceConn = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName className, IBinder service) {
                    Log.e(TAG, "Pod: Service Connected");
                  mPodService = IPodService.Stub.asInterface(service); //here i am getting NullPointerException
                }
        }

和我的服务类什么都没有,只有这么多,我已经显示了它

public class PodService extends Service {
@Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        Log.d("bound", "bound");
        return null;
    }

 static class PodSeviceStub extends IPodService.Stub {

//here i implemented unimplemented methods

    }
}

但是在lolcat中,我只从onBind()函数中获取“bound”消息,但不打印“Pod: Service Connected”,表示服务已成功启动。 在lolcat我得到NullPointerException,也在清单文件中提到过。

1 个答案:

答案 0 :(得分:1)

我重写了服务类,以便onBind()将IBinder作为follwos返回。

public class PodService extends Service {
@Override
    public IBinder onBind(Intent intent) {

        Log.d("bound", "bound");
        return mBinder; // returns IBinder object
    }

    private final IBinder mBinder = new PodSeviceStub(this);

 static class PodSeviceStub extends IPodService.Stub {

         WeakReference<PodService> mService;

        public PodSeviceStub(PodService service) {// added a constructor for Stub here
            mService = new WeakReference<PodService>(service);
        }
//here i implemented unimplemented methods

    }
}

现在可行。