【问题标题】:Activity binding a Service throws NullPointerException活动绑定服务抛出 NullPointerException
【发布时间】:2013-12-12 05:08:45
【问题描述】:

在我的活动中,我有实例变量LocalBinder mBinder ;ServiceConnection mConnection; andboolean mBound;`

onCreate 中,我实例化了一个ServiceConnection 并将其设置为mConnection,如下所示:

mConnection=new ServiceConnection()
{
   public void onServiceConnected(ComponentName class name,IBinder service){
     Log.d(TAG,"Service connected");
     mBinder=(LocalService.LocalBinder)service;
 }

我在 onServiceDisconnected(ComponentName className) 中将 mBinder 设置为 null

问题似乎是调用绑定服务使用:

Intent intent=new Intent(MainActivity.this,LocalService.class);
   bindService(intent,mConnection,Context.BIND_AUTO_CREATE);

永远不会发生...因此永远不会调用 ServiceConnection...当我在 LocalBinder 类中使用公共方法时,它会抛出异常,因为 binder 为 null。

我有一个非空的ServiceConnection 对象并且正在使用正确的上下文。Activity 在应用启动时启动。LocalBinder 就像您可能猜到的LocalService 的静态内部类。

本地服务如下所示:

 static  class LocalBinder
{
     public int getRandomNumber()
    {
         return (int)(Math.random()*100);
    }
 }

  public IBinder onBind(Intent intent)
  {
     LocalBinder binder=new LocalBinder();
      return binder;
     }

当我实现onStartCommandstartService(intent); 时服务启动,但它不会绑定...即使bindService 返回 true,Service Connected 也不会显示...因此 IBinder 未传递给 Activity 导致NullPointerException

【问题讨论】:

  • 你什么时候尝试访问 mBinder?
  • onResumemBinder.getRandomNumber(); 一样在for 循环中,这就是LogCat 中出现异常的地方
  • 尝试Log.d的bindService()返回值
  • bindService返回的值是true,我知道是bind服务返回然后用IBinder调用ServiceConnection
  • 但您在 logcat 中没有看到“服务已连接”?

标签: android nullpointerexception android-service android-service-binding


【解决方案1】:

我不认为你应该创建一个ServiceConnection()——相反,我认为你在你的Activity中实现ServiceConnection接口,然后在bindService中传递Activity:

public class MyClientActivity extends Activity implements ServiceConnection {

    @Override
    public void onStart() {
        bindService(new Intent(MainActivity.this,LocalService.class), this, BIND_AUTO_CREATE);
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.d(TAG,"Service connected");
        mBinder=(LocalService.LocalBinder)service;
    }

您还需要实现 onServiceDisconnected()。希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多