Android 如何在手机通话或铃声响起时在后台运行服务?

Android 如何在手机通话或铃声响起时在后台运行服务?,android,Android,我试图在后台运行的服务中获取电话呼叫状态,但当我拨号并呼叫时,在我完成呼叫后,服务将停止,服务将再次运行 telephonyManager.listen(new MyPhoneListener(), PhoneStateListener.LISTEN_CALL_STATE); private class MyPhoneListener extends PhoneStateListener { @Override public void onCallStateChanged(i

我试图在后台运行的服务中获取电话呼叫状态,但当我拨号并呼叫时,在我完成呼叫后,服务将停止,服务将再次运行

telephonyManager.listen(new MyPhoneListener(), PhoneStateListener.LISTEN_CALL_STATE);

private class MyPhoneListener extends PhoneStateListener {

    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                callState = "ringing";
                Log.d("xxx", " ----------  phone ringing  " );
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                callState = "active";
                Log.d("xxx", " ----------  phone is active  " );
                break;
            case TelephonyManager.CALL_STATE_IDLE:
                callState = "idle";
                Log.d("xxx", " ----------  phone is idle  " );
                break;
        }
        super.onCallStateChanged(state, incomingNumber);
    }

}

我通过在前台运行服务解决了这个问题

在onCreate()方法中


按照惯例,我认为这是不可能的。我认为你能做到这一点的唯一方法是在系统文件中设置一个钩子。基本上是一个黑客。Xposed框架可能是实现这一点的唯一方法。
Intent notificationIntent = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);

Notification notification = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.app_icon)
            .setContentTitle("My Awesome App")
            .setContentText("Doing some work...")
            .setContentIntent(pendingIntent).build();

startForeground(1337, notification);