【问题标题】:OnServiceConnected not getting calledOnServiceConnected 没有被调用
【发布时间】:2013-02-18 12:23:18
【问题描述】:

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

这是我的代码:

@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,并且在清单文件中也提到了。

【问题讨论】:

    标签: android android-service


    【解决方案1】:

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

    现在它可以工作了。

    【讨论】:

    • 请解释您的解决方案!
    • 我重写了服务类以便 onBind() 返回 IBinder
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多