我有一个实现自定义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();
}
}
}
答案 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();
}