For the moment I initialize a listener (extending PhoneStateListener
) from an activity (in its onCreate()
method).
private static boolean listening = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
//...
if (!listening) {
MyPhoneStateListener phoneListener = new MyPhoneStateListener(getApplicationContext());
TelephonyManager telephonyManager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
listening = true;
}
However, I realized I should initialize that listener when the device is rebooted as well, so I should also start it from the boot completed BroadcastReceiver
.
How do I then avoid having two instances of that listener running? (Also I wondered, if the activity is not running (app in background? switched activity?), will my listener always function?)
You can create a Class ListenerUtil,add a static variable for your listener in it,then you can access the static variable in both activity and BroadcastReceiver.Finally,if your activity is not destroied your listener will always work.