Android:PhoneStateListener 在服务中不工作

标签 android service phone-state-listener

我正在尝试构建一个应用程序,在我接听和拒绝来电时进行记录。因此,我正在使用 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/

相关文章:

android - android PhoneStateListener 是否在后台运行?

android - PhoneStateListener 不调用

android - 来电广播接收器不工作

android - 前台启动通知错误,服务通知 channel 无效 :

c++ - linux qt中的gsoap undefined reference

android - 更改 AlertDialog 中超链接的颜色

Flash 全屏打开时 Android WebView 空白 - ICS 4.0

Angular4 尝试比较 '[object Object]' 时出错

android - onCleared如何运作AndroidViewModel [android-architecture-component]

android - 单击时如何获取图像按钮的ID