Android应用开发之PhoneStateListener 的使用

这两天在做翻转静音的功能,需要用到PhoneStateListener,以前只是知道有这么个东西,没有具体用过

包含此类的包是:android.telephony.PhoneStateListener

 

由于StatusBar中用到了PhoneStateListener中较多的内容,索性研究了一下StatusBarPolicy.java

76 /**
77  * This class contains all of the policy about which icons are installed in the status
78  * bar at boot time.  In reality, it should go into the android.policy package, but
79  * putting it here is the first step from extracting it.
80  */

services/java/com/android/server/status/StatusBarPolicy.java

 

 

1、首先需要通过TelephonyManager来注册要监听的状态,状态定义在类PhoneStateListener中,如下所示

1)   LISTEN_CALL_FORWARDING_INDICATOR      Listen for changes to the call-forwarding indicator.

Requires Permission: READ_PHONE_STATE

2)   LISTEN_CALL_STATE                                      Listen for changes to the device call state.

Requires Permission: READ_PHONE_STATE

3)   LISTEN_CELL_LOCATION                               Listen for changes to the device's cell location. Note that this

                                                                            will result in frequent callbacks to the listener.

Requires Permission: ACCESS_COARSE_LOCATION

If you need regular location updates but want more control over the update interval or location precision, you can set up a listener through the location manager instead.

4)   LISTEN_DATA_ACTIVITY                                 Listen for changes to the direction of data traffic on the data

                                                                            connection (cellular).

Requires Permission: READ_PHONE_STATE Example: The status bar uses this to display the appropriate data-traffic icon.

5)   LISTEN_DATA_CONNECTION_STATE              Listen for changes to the data connection state (cellular).

6)   LISTEN_MESSAGE_WAITING_INDICATOR       Listen for changes to the message-waiting indicator.

Requires Permission: READ_PHONE_STATE

Example: The status bar uses this to determine when to display the voicemail icon.

7)   LISTEN_NONE                                                Stop listening for updates.

8)   LISTEN_SERVICE_STATE                                Listen for changes to the network service state (cellular).

9)   LISTEN_SIGNAL_STRENGTH                           This constant is deprecated. by LISTEN_SIGNAL_STRENGTHS

10) LISTEN_SIGNAL_STRENGTHS                         Listen for changes to the network signal strengths (cellular).

Example: The status bar uses this to control the signal-strength icon

 

 

StatusBarPolicy中的注册代码如下所示:

438         // register for phone state notifications.
439         ((TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE))
440                 .listen(mPhoneStateListener,
441                           PhoneStateListener.LISTEN_SERVICE_STATE
442                         | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS
443                         | PhoneStateListener.LISTEN_CALL_STATE
444                         | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE
445                         | PhoneStateListener.LISTEN_DATA_ACTIVITY);

 

当不需要再继续监听上述状态时,通常需要注销掉

// unregister for phone state notifications.

((TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE))
        .listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
 
 
2、定义mPhoneStateListener,以内部匿名类的方式定义
885     private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
886         @Override
887         public void onSignalStrengthsChanged(SignalStrength signalStrength) {
888             mSignalStrength = signalStrength;
889             updateSignalStrength();
890         }
891
892         @Override
893         public void onServiceStateChanged(ServiceState state) {
894             mServiceState = state;
895             updateSignalStrength();
896             updateCdmaRoamingIcon(state);
897             updateDataIcon();
898         }
899
900         @Override
901         public void onCallStateChanged(int state, String incomingNumber) {
902             updateCallState(state);
903             // In cdma, if a voice call is made, RSSI should switch to 1x.
904             if (isCdma()) {
905                 updateSignalStrength();
906             }
907         }
908
909         @Override
910         public void onDataConnectionStateChanged(int state, int networkType) {
911             mDataState = state;
912             updateDataNetType(networkType);
913             updateDataIcon();
914         }
915
916         @Override
917         public void onDataActivity(int direction) {
918             mDataActivity = direction;
919             updateDataIcon();
920         }
921     };
 

1) public void onSignalStrengthsChanged(SignalStrength signalStrength)

// Callback invoked when network signal strengths changes.

通过函数updateSignalStrength更新StatusBar上的信号图标


2) public void onServiceStateChanged(ServiceState state)

// Callback invoked when device service state changes.

通过ServiceState返回当前服务状态,有如下四种状态

STATE_EMERGENCY_ONLY       The phone is registered and locked. Only emergency numbers are allowed.

STATE_IN_SERVICE                  Normal operation condition, the phone is registered with an operator either in

                                                home network or in roaming.

STATE_OUT_OF_SERVICE        Phone is not registered with any operator, the phone can be currently searching a

                                                new operator to register to, or not searching to registration at all, or registration

                                                is denied, or radio signal is not available.

STATE_POWER_OFF                 Radio of telephony is explicitly powered off.

 

同时还可以获取到以下信息

  • Service state: IN_SERVICE, OUT_OF_SERVICE, EMERGENCY_ONLY, POWER_OFF
  • Roaming indicator
  • Operator name, short name and numeric id
  • Network selection mode

     

    StatusBarPolicy根据上面四种状态封装了如下函数,用来判断当前是否有服务

    960     private boolean hasService() {
    961         if (mServiceState != null) {
    962             switch (mServiceState.getState()) {
    963                 case ServiceState.STATE_OUT_OF_SERVICE:
    964                 case ServiceState.STATE_POWER_OFF:
    965                     return false;
    966                 default:
    967                     return true;
    968             }
    969         } else {
    970             return false;
    971         }
    972     }
    3) public void onCallStateChanged(int state, String incomingNumber)
    // Callback invoked when device call state changes
    用来更新来电图标,其中state有三种状态,如下
    public static final int CALL_STATE_IDLE
    Since:  API Level 1

    Device call state: No activity.

    Constant Value: 0 (0x00000000)
    public static final int CALL_STATE_OFFHOOK
    Since:  API Level 1

    Device call state: Off-hook. At least one call exists that is dialing, active, or on hold, and no calls are ringing or waiting.

    Constant Value: 2 (0x00000002)
    public static final int CALL_STATE_RINGING
    Since:  API Level 1

    Device call state: Ringing. A new call arrived and is ringing or waiting. In the latter case, another call is already active.

    Constant Value: 1 (0x00000001)
    4) public void onDataConnectionStateChanged(int state, int networkType)
    // Callback invoked when connection state changes
    用来控制是否显示有移动网络数据交互,其中state有四种状态,如下
    public static final int DATA_CONNECTED
    Since:  API Level 1

    Data connection state: Connected. IP traffic should be available.

    Constant Value: 2 (0x00000002)
    public static final int DATA_CONNECTING
    Since:  API Level 1

    Data connection state: Currently setting up a data connection.

    Constant Value: 1 (0x00000001)
    public static final int DATA_DISCONNECTED
    Since:  API Level 1

    Data connection state: Disconnected. IP traffic not available.

    Constant Value: 0 (0x00000000)
    public static final int DATA_SUSPENDED
    Since:  API Level 1

    Data connection state: Suspended. The connection is up, but IP traffic is temporarily unavailable. For example, in a 2G network, data activity may be suspended when a voice call arrives.

    Constant Value: 3 (0x00000003)
    5) public void onDataActivity(int direction)
    // Callback invoked when data activity state changes.
    用来控制显示数据传输的图标
    918             mDataActivity = direction;
    1115                     switch (mDataActivity) {
    1116                         case TelephonyManager.DATA_ACTIVITY_IN:
    1117                             iconId = mDataIconList[1];
    1118                             break;
    1119                         case TelephonyManager.DATA_ACTIVITY_OUT:
    1120                             iconId = mDataIconList[2];
    1121                             break;
    1122                         case TelephonyManager.DATA_ACTIVITY_INOUT:
    1123                             iconId = mDataIconList[3];
    1124                             break;
    1125                         default:
    1126                             iconId = mDataIconList[0];
    1127                             break;
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Google Android SDK开发范例大全(完整版)共4个分卷 目录 第1章 了解.深入.动手做. 1.1 红透半边天的Android 1.2 本书目的及涵盖范例范围 1.3 如何阅读本书 1.4 使用本书范例 1.5 参考网站 第2章 Android初体验 2.1 安装AndroidSDK与ADTplug-in 2.2 建立第一个Android项目(HelloAndroid!) 2.3 Android应用程序架构——从此开始 2.4 可视化的界面开发工具 2.5 部署应用程序到Android手机 第3章 用户人机界面 3.1 更改与显示文字标签——TextView标签的使用 3.2 更改手机窗口画面底色——drawable定义颜色常数的方法 3.3 更改TextView文字颜色——引用Drawable颜色常数及背景色 3.4 置换TextView文字——CharSequence数据类型与ResourceID应用 3.5 取得手机屏幕大小——DisplayMetrics取得画面宽高的方法 3.6 样式化的定型对象——Style样式的定义 3.7 简易的按钮事件——Button事件处理 3.8 手机页面的转换——setContentView的应用 3.9 调用另一个Activity——Intent对象的使用 3.10 不同Activity之间的数据传递——Bundle对象的实现 3.11 返回数据到前一个Activity——startActivityForResult方法 3.12 具有交互功能的对话框——AlertDialog窗口 3.13 置换文字颜色的机关——Button与TextView的交互 3.14 控制不同的文字字体——Typeface对象使用 3.15 如iPhone拖动相片特效——Gallery画廊 3.16 自制计算器——多按钮的整合应用 3.17 关于(About)程序信息——Menu功能菜单程序设计 3.18 程序加载中,请稍后——ProgressDialog与线程整合应用 3.19 全屏幕以按钮覆盖——动态产生按钮并最大化 3.20 今晚到哪儿打牙祭?——具选择功能的对话框 3.21 Android变脸——主题(Theme)实现 第4章 史上超豪华的手机控件 4.1 EditText与TextView共舞——setOnKeyListener事件 4.2 设计具有背景图的按钮——ImageButton的焦点及事件处理 4.3 给耶诞老人的信息——Toast对象的使用 4.4 我同意条款——CheckBox的isChecked属性 4.5 消费券采购列表——多选项CheckBox的应用 4.6 向左或向右——RadioGroup组与onCheckedChanged事件 4.7 专业相框设计——ImageView的堆栈应用 4.8 自定义下拉菜单模式——Spinner与setDropDownViewResource 4.9 动态添加/删除的Spinner菜单——ArrayList与Widget的依赖性 4.10 心爱小宝贝相片集——Gallery与衍生BaseAdapter容器 4.11 快速的搜索手机文件引擎——JavaI/O的应用 4.12 按钮也能随点击变换——ImageButton选择特效 4.13 具自动提示功能的菜单——AutoCompleteTextView与数组 4.14 数字及模拟小时钟设计——AnalogClock与DigitalClock的原理 4.15 动态输入日期与时间——DatePicker与TimePicker应用 4.16 猜猜红心A在那儿——ImageView点击事件与透明度处理 4.17 后台程序运行进度提示——ProgressBar与Handler的整合应用 4.18 动态文字排版——GridView与ArrayAdapter设计 4.19 在Activity里显示列表列表——ListView的布局 4.20 以动态列表配置选项——ListActivity与Menu整合技巧 4.21 查找程序根目录下所有文件——JavaI/O与ListActivity的结合.. 4.22 加载手机磁盘里的图文件——使用decodeFile方法 4.23 动态放大缩小ImageView里的图片——运用Matrix对象来缩放图文件 4.24 动态旋转图片——Bitmap与Matrix旋转ImageView 4.25 猜猜我在想什么——RadioButtonID 4.26 离开与关闭程序的弹出窗口——对话窗口上的ICON图标 第5章 交互式通信服务与手机控制 5.1 具有正则表达式的TextView——Linkify规则 5.2 ACTION!CALL!拨打电话——Intent.ACTION.CALL的使用 5.3 自制发送短信程序——SmsManager与PendingIntent对象 5.4 自制发送Email程序——Intent在Email上的使用 5.5 自制日历手机数据库——实现SQLiteOpenHelper 5.6 手机震动的节奏——Vibrator对象及周期运用 5.7 图文可视化提醒——Toast与LinearLayoutView 5.8 状态栏的图标与文字提醒——NotificationManager与Notification对象的应用 5.9 搜索手机通讯录自动完成——使用ContentResolver 5.10 取得联系人资料——Provider.Contact的使用 5.11 制作有图标的文件资源管理器——自定义Adapter对象 5.12 还原手机默认桌面——重写clearWallpaper方法 5.13 置换手机背景图——Gallery与setWallpaper整合实现 5.14 撷取手机现存桌面——getWallpaper与setImageDrawable 5.15 文件资源管理器再进化——JavaI/O修改文件名及删除 5.16 取得目前File与Cache的路径——getCacheDir与getFilesDir 5.17 打开/关闭WiFi服务——WifiManager状态判断 5.18 取得SIM卡内的信息——TelephonyManager的应用 5.19 调用拨号按钮——打电话CALL_BUTTON 5.20 DPAD按键处理——onKeyDown事件与Layout坐标交互 5.21 任务管理器正在运行的程序——RunningTaskInfo 5.22 动态更改屏幕方向——LANDSCAPE与PORTRAIT 5.23 系统设置更改事件——onConfigurationChanged信息处理 5.24 取得电信网络与手机相关信息——TelephonyManager与android.provider.Settings.System的应用 第6章 手机自动服务纪实 6.1 您有一条短信popup提醒——常驻BroadcastReceiver的应用 6.2 手机电池计量还剩多少——使用BroadcastReceiver捕捉Intent.ACTION_BATTERY_CHANGED 6.3 群发拜年短信给联系人——ACTION_PICK与Uri对象 6.4 开始与停止系统服务——Service与Runnable整合并用 6.5 通过短信发送email通知——BroadcastReceiver与Intent整合 6.6 手机拨接状态——PhoneStateListener之onCallStateChanged 6.7 有来电,发送邮件通知——PhoneStateListener与ACTION_SEND 6.8 存储卡剩余多少容量——Environment加StatFs 6.9 访问本机内存与存储卡——File的创建与删除 6.10 实现可定时响起的闹钟——PendingIntent与AlarmManager的运用 6.11 黑名单来电自动静音——PhoneStateListener与AudioManager 6.12 手机翻背面即静音震动——SensorListener及AudioManager整合应用 6.13 指定时间置换桌面背景——多AlarmManager事件处理 6.14 判断发送短信后的状态——BroadcastReceiver聆听PendingIntent 6.15 后台服务送出广播信息——sendBroadcast与BroadcastReceiver 6.16 开机程序设计——receiver与intent-filter协同作业 6.17 双向短信常驻服务——Service与receiver实例 第7章 娱乐多媒体 7.1 访问Drawable资源的宽高——ContextMenu与Bitmap的应用 7.2 绘制几何图形——使用android.graphics类 7.3 手机屏幕保护程序——FadeIn/FadeOut特效与运行线程 7.4 用手指移动画面里的照片——onTouchEvent事件判断 7.5 加载存储卡的Gallery相簿——FileArrayList 7.6 取得手机内置媒体里的图文件——ACTION_GET_CONTENT取回InputStream 7.7 相片导航向导与设置背景桌面——ImageSwitcher与Gallery 7.8 调整音量大小声——AudioManager控制音量 7.9 播放mp3资源文件——raw文件夹与MediaPlayer的使用 7.10 播放存储卡里的mp3音乐——MediaPlayer.setDataSource 7.11 自制录音/播放录音程序——MediaRecorder与AudioEncoder 7.12 通过收到短信开始秘密录音——MediaRecorder与BroadcastReceiver实例 7.13 内置影片播放器载入3gp电影——VideoViewWidget 7.14 自制3gp影片播放器——MediaPlayer与实现SurfaceView 7.15 相机预览及拍照临时文件——Camera及PictureCallback事件 第8章 当Android与Internet接轨 8.1 HTTPGET/POST传递参数——HTTP连接示范 8.2 在程序里浏览网页——WebView.loadUrl 8.3 嵌入HTML标记的程序——WebView.loadData 8.4 设计前往打开网页功能——Intent与Uri.parse 8.5 将网络图像网址放入Gallery中显示——URL.URLConnection.BaseAdapter 8.6 即时访问网络图文件展示——HttpURLConnection 8.7 手机气象局,实时卫星云图——HttpURLConnection与URLConnection和运行线程 8.8 通过网络播放MP3——Runnable存储FileOutputStream技巧 8.9 设置远程下载音乐为手机铃声——RingtoneManager与铃声存放路径 8.10 远程下载桌面背景图案——URLConnection与setWallpaper()搭配 8.11 将手机文件上传至网站服务器——模拟HTTPFORM的POSTACTION 8.12 移动博客发布器——以XML-RPC达成远程过程调用 8.13 移动RSS阅读器——利用SAXParser解析XML 8.14 远程下载安装Android程序——APKInstaller的应用 8.15 手机下载看3gp影片——Runnable混搭SurfaceView 8.16 访问网站LoginAPI——远程服务器验证程序运行权限 8.17 地震速报!——HttpURLConnection与Service侦测服务 第9章 Google服务与Android混搭 9.1 Google帐号验证Token——AuthSub 9.2 Google搜索——AutoCompleteTextView与GoogleSearchAPI 9.3 前端产生QRCode二维条形码——GoogleChartAPI 9.4 以经纬度查找目的地位置——GeoPoint与MapView的搭配运用 9.5 GPSGoogle地图——LocationListener与MapView实时更新 9.6 移动版GoogleMap——Geocoder反查Address对象 9.7 规划导航路径——DirectionsRoute 9.8 移动设备上的Picasa相册——GooglePicasaAPI 9.9 随身翻译机——GoogleTranslateAPI 第10章 创意Android程序设计 10.1 手机手电筒——PowerManager控制WakeLock并改变手机亮度 10.2 GPS轨迹记录器——利用LocationListener在地图上画图并换算距离 10.3 女性贴身看护——AlarmManager.DatePicker.TimePicker 10.4 手机QRCode二维条形码生成器——Canvas与SurfaceHolder绘图 10.5 AndroidQRCode二维条形码扫描仪——BitmapFactory.decodeByteArray 10.6 上班族今天中午要吃什么——热量骰子地图 10.7 掷杯筊——把手机放在空中甩事件处理...

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值