我已经提到了下列问题,但找不到答案:
Can't get service object (onServiceConnected never called)
onServiceConnected not getting called , getting a null pointer exception
onServiceConnected 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并且在manifest文件中也提到了它。

最佳答案

我重写了服务类,以便onbind()以如下方式返回ibinder。

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

    }
}

现在它开始工作了。

关于android - OnServiceConnected没有被调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14936225/

10-09 04:38