OnServiceConnected not getting called

北慕城南 提交于 2019-12-01 23:39:05

问题


I referred to the following questions already but could not find an answer:

  • Can't get service object (onServiceConnected never called),
  • onServiceConnected not getting called , getting a null pointer exception, and
  • onServiceConnected never called after bindService method

Here is my code:

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

and My service class contains nothing, only this much, i have shown it bellow

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

    }
}

But in lolcat i am getting only "bound" message from onBind() function, but not printing "Pod: Service Connected", means service is started successfully. and in lolcat i am getting NullPointerException and also mentioned in manifest file too.


回答1:


I rewrote the service class so that onBind() returns IBinder as 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

    }
}

and now it works.



来源:https://stackoverflow.com/questions/14936225/onserviceconnected-not-getting-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!