我有一个MyService
实现 custom 的类CallReceiver.Listener
。问题是调用的侦听器注册MyService
不起作用。mListener
inCallReceiver
始终为空。它证明听众没有注册,但我不知道为什么会这样。
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);
}
}
}