问题
I use descendant - class of PhoneStateListener:
class CallStateListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
if (incomingNumber!=null)
{
// code for incoming call handling
}
break;
}
super.onCallStateChanged(state, incomingNumber);
}
this is my BroadcastReceiver:
class ServiceReceiver extends BroadcastReceiver {
CallStateListener phoneListener;
@Override
public void onReceive(final Context context, Intent intent) {
if (phoneListener == null) {
phoneListener = CallStateListener.getCallStateInstance(context);
TelephonyManagerSingletone.getInstance().getTelephonyManager().listen(CallStateListener.getCallStateInstance(context),
android.telephony.PhoneStateListener.LISTEN_CALL_STATE);
}
}
manifest:
<receiver android:name="com.library.ServiceReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
</receiver>
but when I use it like this, I receive duplicate call in my CallStateListener. How can I fix this?
回答1:
When I tried your code, it run 10 times instead of running just once! It is better to declare phoneListener
as a static variable in this case. That way you can guarantee that listen
method will not be called more than once. Check this out:
public class ServiceReceiver extends BroadcastReceiver {
static CallStateListener phoneListener;
@Override
public void onReceive(final Context context, Intent intent) {
if (phoneListener == null) {
phoneListener = new CallStateListener();
TelephonyManager tm = (TelephonyManager)context.getSystemService("phone");
tm.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
}
Also, I have changed the way you deal with TelephonyManager
- I couldn't find that TelephonyManagerSingletone
that you mentioned in your code.
I hope this helps somebody!
回答2:
Not sure if it's a bug or a feature, but since API19 that happens with broadcasts.
For those who will search for the solution - you can keep track of previous state. Do stuff only if it is different.
来源:https://stackoverflow.com/questions/18853511/telephonymanager-call-state-ringing-calls-twice-while-one-call-ringing