I am writing a simple app to keep track of the periods when my phone has poor signal strength. I do this using an IntentService
, which listens for PhoneStateListener.LISTEN_SIGNAL_STRENGTHS
as follows:
public class PoorSignalIntentService extends IntentService {
private TelephonyManager mTelephonyManager;
private PhoneStateListener mPhoneStateListener;
public PoorSignalIntentService() {
super("PoorSignalIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
mPhoneStateListener = new PhoneStateListener(){
@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
doSomething(signalStrength);
super.onSignalStrengthsChanged(signalStrength);
}
@Override
public void onServiceStateChanged(ServiceState serviceState) {
doSomething(serviceState);
super.onServiceStateChanged(serviceState);
}
};
mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS|PhoneStateListener.LISTEN_SERVICE_STATE);
}
private void doSomething(SignalStrength signalStrength){
Log.d(TAG, "Signal Strength changed! New strength = "+signalStrength.getGsmSignalStrength());
}
private void doSomething(ServiceState serviceState){
Log.d(TAG, "Service State changed! New state = "+serviceState.getState());
}
@Override
public void onDestroy() {
Log.d(TAG, "Shutting down the IntentService");
mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
super.onDestroy();
}
}
However, I see that after the first signal strength changed notification is received, the onDestroy()
is called (presumably, the IntentService
calls stopSelf()
).
This problem is not limited to PhoneStateListener
. I have another simple app which uses the Proximity Sensor thus:
@Override
protected void onHandleIntent(Intent intent){
mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
}
In this case too, only the first proximity change was notified, after which the Service
stopped itself.
So, what is the pattern for registering listeners like these in a Service
?
Ok, I found the solution. My bad. I should be using a
Service
rather thanIntentService
, since the latter callsstopSelf()
after processing the intents it receives inonHandleIntent()
.Here's the working code which extends
Service
: