PhoneStateListener executing multiple times

973 views Asked by At

When i try to detect incoming calls with PhoneStateListener, it executes multiple times. This is my code. onCallStateChanged method is called multiple times.

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

There are 2 answers

0
Noor Ali Butt On

Using BroadcastReceiver with functionality of PhoneStateListener

In above line: The problem is that every time when the onReceive() method is called a new TelphoneManager instance is created and registers as a listener to Phoone State . Solution : I made every variable of the CallReceiverBroadcast class static ! and it solved the problem !! to an extent but still the service is called twice every time it means that some how there is 2 instance of the class registered as a listener but i don't know why. Although i can work around it through some condition but it is causing unnecessary overhead and Anyone having a better solution will be highly Appreciated .

0
Narendra Sorathiya On
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);
    }
}
}