Hi,
I'm registering a PhoneStateListener in my service onCreate() method.
I want to do something when the call has ended, i.e. when state ==
TelephonyManager.CALL_STATE_IDLE. However when the very first call is
initiated my listener recieves two messages: one with CALL_STATE_IDLE
and the second one with CALL_STATE_OFFHOOK. Then after the user hangs
up I get third message with CALL_STATE_IDLE again. On subsequent calls
I get only two messages: CALL_STATE_OFFHOOK on call initialization and
CALL_STATE_IDLE on hangup.

I can't quite understand why I get the very first CALL_STATE_IDLE
which seems redundant and breaks my logic. As a workaround I had to
use a static variable to track previous call state.

My code looks like this:

public class LikeBookService extends Service {
        private TelephonyManager tm;
        private NotificationManager nm;
        private static int previousCallState = 0;
        private PhoneStateListener phoneStateListener = new
PhoneStateListener() {
                @Override
                public void onCallStateChanged(int state, String 
incomingNumber) {
                        super.onCallStateChanged(state, incomingNumber);

                        if (state == TelephonyManager.CALL_STATE_IDLE && state 
!=
previousCallState) {
                                //do stuff on hang up
                        }
                        previousCallState = state;
                }
        };


    @Override
    public void onCreate() {
        super.onCreate();

        nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        tm = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
        int events = PhoneStateListener.LISTEN_CALL_STATE;
        tm.listen(phoneStateListener, events);
    }

    @Override
    public void onStart(Intent intent, int startId) {

    }

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

    @Override
    public void onDestroy() {
        int events = PhoneStateListener.LISTEN_NONE;
        tm.listen(phoneStateListener, events);
    }

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to