Android: PhoneStateListener not working in service

I am trying to create an application that registers when I accept and reject calls. Therefore, I use PhoneStateListener.

When I start the listener in the onCreate() method, it stops its activity after a while. As far as I know, Android closes the application because it has no focus.

I tried to get around this behavior when starting the service. All the code I wrote works fine and is not killed by android ... but PhoneStateListener does not receive any events.

How do I start the service:

 public class RunningService extends IntentService { /** * A constructor is required, and must call the super IntentService(String) * constructor with a name for the worker thread. */ public RunningService() { super("RunningService"); } /** * The IntentService calls this method from the default worker thread with * the intent that started the service. When this method returns, * IntentService stops the service, as appropriate. */ @Override protected void onHandleIntent(Intent intent) { //...some code...creating a notification startForeground(12345, notification); TelephonyManager telephonyManager = (TelephonyManager) this .getSystemService(TELEPHONY_SERVICE); telephonyManager.listen(new PhoneStateListenerImpl(), PhoneStateListener.LISTEN_CALL_STATE); while (true) { ...some code to do...until Exit is called by user } } } 

PhoneStateListener with basic output:

 public class PhoneStateListenerImpl extends PhoneStateListener { public PhoneStateListenerImpl() { super(); Log.v("psListener", "constructor"); } @Override public void onCallStateChanged(int state, String incomingNumber) { switch (state) { case TelephonyManager.CALL_STATE_IDLE: Log.v("PhoneStateListener", "IDLE"); break; case TelephonyManager.CALL_STATE_OFFHOOK: Log.v("PhoneStateListener", "OFFHOOK"); break; case TelephonyManager.CALL_STATE_RINGING: Log.v("State", "Ringing"); break; default: { Log.v("Status", "something"); } } } } 

I get the log output from the Listeners constructor, but whenever something changes (for example, I call someone) nothing happens.

The same listener starting with onCreate() works fine.

I might have missed something

I just tried: I tried asking TelephonyManager for the state of the phone in the while loop of the service. It works great. But I think this is just a dirty decision.

Can anyone understand what could be the problem?

+4
source share

Source: https://habr.com/ru/post/1397070/


All Articles