3

我已经提到了以下问题,但找不到答案:

这是我的代码:

@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 中,我只bound从 onBind() 函数中得到“”消息,而不是打印“ Pod: Service Connected”,这意味着服务已成功启动。在lolcat中,我得到了NullPointerException并且也在清单文件中提到了。

4

1 回答 1

2

我重写了服务类,以便 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

    }
}

现在它可以工作了。

于 2013-02-19T04:59:05.230 回答