• Android 监听来电和去电状态


    要实现监听到打电话和接电话的状态,需要用到广播接受者BroadcastReceiver,其实现代码请参考如下;

    一、定义一个类,继承BroadcastReceiver,重写onReceive()方法。

     1 package com.example.phonereceiver;
     2 
     3 import android.app.Service;
     4 import android.content.BroadcastReceiver;
     5 import android.content.Context;
     6 import android.content.Intent;
     7 import android.telephony.TelephonyManager;
     8 
     9 public class PhoneReceiver extends BroadcastReceiver {
    10 
    11     @Override
    12     public void onReceive(Context context, Intent intent) {
    13         if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {//去电
    14             System.out.println("去电");
    15         } else {//来电(存在以下三种情况)
    16             TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
    17             switch (tm.getCallState()) {
    18             case TelephonyManager.CALL_STATE_IDLE:
    19                 System.out.println("挂断");
    20                 break;
    21             case TelephonyManager.CALL_STATE_OFFHOOK:
    22                 System.out.println("接听");
    23                 break;
    24             case TelephonyManager.CALL_STATE_RINGING:
    25                 System.out.println("响铃");
    26                 break;
    27             }
    28         }
    29     }
    30 }

    二、在清单文件中注册该广播,并加上相应的权限。

     1 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     2     package="com.example.phonereceiver"
     3     android:versionCode="1"
     4     android:versionName="1.0" >
     5 
     6     <uses-sdk
     7         android:minSdkVersion="8"
     8         android:targetSdkVersion="15" />
     9 
    10     <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    11     <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
    12 
    13     <application
    14         android:icon="@drawable/ic_launcher"
    15         android:label="@string/app_name"
    16         android:theme="@style/AppTheme" >
    17         <receiver android:name=".PhoneReceiver" >
    18             <intent-filter>
    19                 <action android:name="android.intent.action.PHONE_STATE" />
    20                 <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
    21             </intent-filter>
    22         </receiver>
    23     </application>
    24 
    25 </manifest>
  • 相关阅读:
    python流程控制
    数据类型
    python之初接触
    使用 HttpWebRequest 向网站提交数据
    在 ASP.NET MVC4 中使用 NInject
    第一篇 微信商城 开发前的准备工作
    (一)模块基础
    函数之递归、匿名函数及内置方法
    装饰器的使用原理
    mybatis返回list
  • 原文地址:https://www.cnblogs.com/zhangping/p/3681043.html
Copyright © 2020-2023  润新知