0

我有一个MyService实现 custom 的类CallReceiver.Listener。问题是调用的侦听器注册MyService不起作用。mListenerinCallReceiver始终为空。它证明听众没有注册,但我不知道为什么会这样。

MyService 类(摘录):

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();
    }
  }

}

呼叫接收器类:

public class CallReceiver extends BroadcastReceiver   {

private boolean isRinging = false;
private Listener mListener = null;

// interface declaration
 public interface Listener {
        public void onPhoneStateChange(boolean state);
    }

// listener registration
 public void registerListener (Listener listener) {
        mListener = listener;
    }


@Override
public void onReceive(Context context, Intent intent) {

        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

        if(TelephonyManager.EXTRA_STATE_RINGING.equals(state))  {
            // do something while ringing
                Log.v("phone", "ringing");
                isRinging = true;
        }


        else if(TelephonyManager.EXTRA_STATE_IDLE.equals(state))    {
            //do something when the call ends
            Log.v("phone", "idle");
            isRinging = false;
        }


        if(mListener != null)   {
            // onPhoneStateChange is not called because mListener is null
            mListener.onPhoneStateChange(isRinging);
        }

  }

}
4

1 回答 1

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();
}
于 2013-02-03T20:30:38.103 回答