PhoneStateListener执行多次

时间:2013-12-25 06:54:59

标签: android phone-state-listener

当我尝试使用PhoneStateListener检测来电时,它会多次执行。 这是我的代码。多次调用onCallStateChanged方法。

public class CallHelper {
    public String number;
    private Context ctx;
    private TelephonyManager tm;



    private CallStateListener callStateListener;
    private OutgoingReceiver outgoingReceiver;
    SharedPreferences trackMeData;
    public CallHelper(Context ctx) {
        this.ctx = ctx;

        number ="";
        callStateListener = new CallStateListener();
        outgoingReceiver = new OutgoingReceiver();
        trackMeData = ctx.getSharedPreferences("LockedSIM", 0);

    }
    private class CallStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                number = incomingNumber;
                sendsmstoph(number);
                System.out.println("Incomgin");
                Toast.makeText(ctx, "Incoming: " + incomingNumber,Toast.LENGTH_LONG).show();
                break;
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

Using BroadcastReceiver with functionality of PhoneStateListener

在上面一行:问题是每次调用onReceive()方法时,都会创建一个新的TelphoneManager实例并注册为Phoone State的监听器。 方案: 我将CallReceiverBroadcast类的每个变量都设为静态!它解决了问题!!在某种程度上,但是每次调用服务时都会调用两次,这意味着有两个类的实例如何被注册为监听器,但我不知道为什么。虽然我可以通过一些条件解决它,但它会导致不必要的开销,任何拥有更好解决方案的人都会受到高度赞赏。

答案 1 :(得分:0)

package com.example.netlogger.Receiver;

import java.util.Date;
import com.example.netlogger.util.LocalDatabase;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;import android.widget.Toast;

public class CallActionsReceiver extends BroadcastReceiver {
static ThePhoneStateListener phoneStateListener;

@Override
public void onReceive(Context arg0, Intent arg1) {
    TelephonyManager manager = (TelephonyManager) arg0
            .getSystemService(arg0.TELEPHONY_SERVICE);      
    if (phoneStateListener == null) {
        phoneStateListener = new ThePhoneStateListener(arg0);
        manager.listen(phoneStateListener,
                android.telephony.PhoneStateListener.LISTEN_CALL_STATE);
    }
}
}