Android :从 Activity onResume 检测调用状态

Android : Detect Call State from Activity onResume

我正在开发一个应用程序,如果有来电,我需要从 onResume 完成 activity。我创建了一个 CallHelper class,我在其中使用 PhoneStateListener 检测任何来电。

public class CallHelper {

    /**
     * Listener to detect incoming calls.
     */
    private static class CallStateListener extends PhoneStateListener {
        @Override
            public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    System.out.println("RINGING");
                    OverlayActivity overlayActivity = OverlayActivity.getInstance();
                    overlayActivity.finish();
                    System.out.println("Activity has been closed!!");
                    break;
            }
        }


    }

    /**
     * Broadcast receiver to detect the outgoing calls.
     */
    public class OutgoingReceiver extends BroadcastReceiver {
        public OutgoingReceiver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

            Toast.makeText(ctx,
                    "Outgoing: "+number,
                    Toast.LENGTH_LONG).show();
        }

    }

    private Context ctx;
    private TelephonyManager tm;
    private CallStateListener callStateListener;

    private OutgoingReceiver outgoingReceiver;

    public CallHelper(Context ctx) {
        this.ctx = ctx;

        callStateListener = new CallStateListener();
        outgoingReceiver = new OutgoingReceiver();
    }

    /**
     * Start calls detection.
     */
    public void start() {
        tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
        tm.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);

        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
        ctx.registerReceiver(outgoingReceiver, intentFilter);
    }

    /**
     * Stop calls detection.
     */
    public void stop() {
        tm.listen(callStateListener, PhoneStateListener.LISTEN_NONE);
        ctx.unregisterReceiver(outgoingReceiver);
    }

}

我需要检测 onResume 内部,如果有任何调用,我需要完成 activity 如果没有,我不需要做任何事情。

我还没有找到解决方案,所以我所做的是,我在 Activity 的 onResume 中添加了用于检测 CallStateChange 的代码,并使用该代码执行我正在执行的任务想在 CallStateChange 上执行。

我不确定这是否是正确的解决方案,但希望社区对此提出意见。

这是我正在使用的代码:

TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

        PhoneStateListener callStateListener = new PhoneStateListener() {
            public void onCallStateChanged(int state, String incomingNumber)
            {
                if(state==TelephonyManager.CALL_STATE_RINGING){
                    // Code i wanted to execute
                }
            }
        };
        telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);