我正在尝试构建一个应用程序,在我接听和拒绝来电时进行记录。因此,我正在使用 PhoneStateListener。
当我在 onCreate()
方法中启动监听器时,它会在一段时间后停止 Activity 。据我所知,Android 会关闭应用程序,因为它没有焦点。
我试图通过启动服务来解决该问题。我编写的所有代码都运行良好,不会被 android 杀死...但是 PhoneStateListener 没有收到任何事件。
我如何启动服务:
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:
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");
}
}
}
}
我从 Listeners 构造函数获得日志输出,但每当发生变化(比如我正在调用某人)时,什么都没有发生。
从 onCreate()
开始的同一个 Listener 工作正常。
也许我错过了什么
我刚试过: 我试图在服务的 while 循环中向 TelephonyManager 询问电话状态。这很好用。但我想这只是一个肮脏的解决方法。
有人知道可能是什么问题吗?
最佳答案
您正在 onHandleIntent 上注册您的 PhoneStateListener,而不是在 onStartCommand 或 onCreate 函数中注册您的监听器,并确保您在项目 list 中提到了以下权限
关于Android:PhoneStateListener 在服务中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9331733/