José Carlos
José Carlos

Reputation: 2922

How to stop PhoneStateListener when I change the activity

I define a PhoneStateListener in an activity and I want to stop the listener when a I change the activity. I have tried to do it with this code, but it doesn't work.

public class OriginActivity extends AppCompatActivity{
    private TelephonyManager tManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_origin);
        tManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
        tManager.listen(new CustomPhoneStateListener(this), PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }

    protected void onPause() {
        super.onPause();

        // Logs 'app deactivate' App Event.
        AppEventsLogger.deactivateApp(this);

       tManager.listen(new CustomPhoneStateListener(this), PhoneStateListener.LISTEN_NONE);
    }
}

What am I doing wrong?

Upvotes: 4

Views: 1701

Answers (2)

Sanjeev
Sanjeev

Reputation: 151

Can be done when the service is stopped for some reason (say user click a stop button)

@Override
public void onDestroy() {
    super.onDestroy();
    telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
    listener = null;
}

Upvotes: 2

José Carlos
José Carlos

Reputation: 2922

I have found a solution!!!

public class OriginActivity extends AppCompatActivity{

    CustomPhoneStateListener customPhoneStateListener;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_origin);

        /**** Other Code ****/

    }

    protected void onResume() {
        super.onResume();

        //Here, we start the listener!!!
        TelephonyManager tManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
        customPhoneStateListener = new CustomPhoneStateListener(this);
        tManager.listen(customPhoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        Log.d(TAG, "onResume");
    }

    protected void onPause() {
        super.onPause();

        //Here, we stop the listener!!!
        TelephonyManager tManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
        tManager.listen(customPhoneStateListener, PhoneStateListener.LISTEN_NONE);
        customPhoneStateListener = null;
    }

}

Therefore, when we access to the Activity for the first time or back from another activity we call onResume() and we start the listener. And, when we exit the Activity with onPause() we stop the listener.

Upvotes: 4

Related Questions