Android 来电监听

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

 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

package com.hyphenate.chatuidemo.receiver;

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();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,898评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,080评论 19 139
  • 先上结论:幽灵类型(Phantom Type)是一种可以把有些运行时才能检测到的错误,在编译时检测出来的技巧。按照...
    superxff阅读 625评论 0 0
  • 2017年9月26日 雨 星期二 今日的雨驱走了夏留在我们唇边的最后一丝淡淡的吻,之后的日子里,我们所要面对的就只...
    泥鳅的恋爱阅读 260评论 0 3
  • MeiuPic 相册是一款简单易用的相册系统,支持 xx分类 ---> xx相册 ---> xx相片集 方式显示你...
    Qoo酷儿阅读 1,744评论 0 1