Android:从Activity onResume检测呼叫状态

时间:2018-11-24 19:31:31

标签: android broadcastreceiver onresume

我正在开发一个应用程序,如果有来电,我需要从onResume完成活动。我创建了一个CallHelper类,可以在其中使用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中进行检测,如果有任何呼叫,如果没有,我需要完成活动,我不需要执行任何操作。

1 个答案:

答案 0 :(得分:0)

我还没有找到解决方案,所以我要做的是,我在我的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);