Question

This is my BroadcastReceiver

    public class PlayAudio extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        tm.listen(new CustomPhoneStateListener(context), PhoneStateListener.LISTEN_CALL_STATE);
    }
}

This is my Custom PhoneStateListener Class

public class CustomPhoneStateListener extends PhoneStateListener {

    Context context; 

    public CustomPhoneStateListener(Context context) {
        super();
        this.context = context;
    }

    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        super.onCallStateChanged(state, incomingNumber);

        switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:
            Log.d("PHONEA", "IDLE");
            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
           Log.d("PHONEA", "OFFHOOK");
            break;
        case TelephonyManager.CALL_STATE_RINGING:
            Log.d("PHONEA", "RINGING");
            Intent intent = new Intent(this.context, AudioService.class);
            context.startService(intent);
            break;
        default:
            break;
        }
    }
}

and this is my service

public class AudioService extends Service{
    private static final String TAG = "PHONEA";
    MediaPlayer player;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate -> TODO");
        }
}

My question is that every time i receive data in Broadcast receiver i create a new instance of the TelephonyManager. So when i view the logcat the first time i get "RINGING", the second time "RINGING" "RINGING" and so on. WHen should i create my telephonylistener in order to have only one instance?

Regards, Nicos

Was it helpful?

Solution

You are getting call on your receiver(Asssuming you are listening for PhoneState) every time the phone state change.

You should put some check in your receiver and instatiate the TelephonyManager for the first time only.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top