Android 电话监听

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhou906767220/article/details/80865022

在你要监听来电的地方就行

private void telephony() {
        //获得相应的系统服务
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        if(tm != null) {
            try {
                MyPhoneCallListener myPhoneCallListener = new MyPhoneCallListener();
                myPhoneCallListener.setCallListener(new MyPhoneCallListener.CallListener() {
                    @Override
                    public void onCallRinging() {
                        //回调,做你想做的,我是关闭当前界面
                        finish();
                    }
                });
                // 注册来电监听
                tm.listen(myPhoneCallListener, PhoneStateListener.LISTEN_CALL_STATE);
            } catch(Exception e) {
                // 异常捕捉
            }
        }
    }

PhoneStateListener的onCallStateChanged方法监听来电状态
监听电话的类 MyPhoneCallListener.java


import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;


/**
 * Created by Mr.Robot on 2018/1/23.
 * https://github.com/Siomt
 */

public class MyPhoneCallListener extends PhoneStateListener {

    private static final String TAG = "MyPhoneCallListener";
    protected CallListener listener;
         /**
         * 返回电话状态
         *
         * CALL_STATE_IDLE 无任何状态时
         * CALL_STATE_OFFHOOK 接起电话时
         * CALL_STATE_RINGING 电话进来时
         */
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        switch (state) {
            case TelephonyManager.CALL_STATE_IDLE:// 电话挂断
                Log.d(TAG ,"电话挂断...");
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK: //电话通话的状态
                Log.d(TAG ,"正在通话...");
                listener.onCallRinging();
                break;
            case TelephonyManager.CALL_STATE_RINGING: //电话响铃的状态
                Log.d(TAG ,"电话响铃");
                break;
        }
        super.onCallStateChanged(state, incomingNumber);
    }
    //写个回调
    public void setCallListener(CallListener callListener){
        this.listener = callListener;
    }
    //回调接口
    public interface CallListener{
        void onCallRinging();
    }
}

猜你喜欢

转载自blog.csdn.net/zhou906767220/article/details/80865022