0
我有一個MyService
類實現自定義CallReceiver.Listener
。問題是在MyService
中調用的監聽器註冊不起作用。 mListener
在CallReceiver
始終爲空。它證明聽衆沒有註冊,但我不知道爲什麼。自定義聽衆沒有註冊
爲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();
}
}
}
CallReceiver類:
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);
}
}
}
您從未註冊Receiver,這可能是一個問題。此外,如果此Receiver是Manifest的一部分,系統很可能會創建一個與您的服務無關的單獨實例,這會將'mListener'留空。 –
CallReceiver現在在AndroidManifest.xml中靜態註冊。 – Kristopher
我會說它不應該在清單中。相反,您的服務應該使IntentFilter動態註冊。我會很快發佈代碼示例。我不知道你的接收器需要什麼「Intent」動作。 –