自定义侦听器未注册

时间:2013-02-03 20:09:25

标签: java android listener

我有一个实现自定义MyService的{​​{1}}类。问题是CallReceiver.Listener中调用的监听器注册无法正常工作。 MyService中的mListener始终为空。它证明听众没有注册,但我不知道为什么会这样。

MyService类(摘录):

CallReceiver

CallReceiver类:

public class MyService extends Service implements CallReceiver.Listener {

CallReceiver mCallReceiver;

   public int onStartCommand (Intent intent, int flags, int startId) {

    serviceStart();
    return startId;
   }

    // starting service
    public void serviceStart()  {

    mCallReceiver = new CallReceiver();

    // registering listener for CallReceiver
    mCallReceiver.registerListener(this);
   }


    public void onPhoneStateChange(boolean state) {
     if (state) {
        Log.v("onPhoneStateChange", "service destroyed");
        serviceDestroy();
    } else {
        // serviceStart();
    }
  }

}

1 个答案:

答案 0 :(得分:1)

您应该动态注册接收器。

// registering listener for CallReceiver
   mCallReceiver.registerListener(this);
   IntentFilter filter = new IntentFilter("your.Intent");
   registerReceiver (mCallReceiver, filter);

此外,在您的服务onDestroy()中,不要忘记取消注册。

@Override
public void onDestroy ()
{
    try {
    unregisterReceiver (broadcastReceiver);
    }
    catch (IllegalArgumentException e){}
    catch (NullPointerException ne){}
    super.onDestroy();
}