侦听Android手机ServiceState

本文介绍两种监听Android系统手机ServiceState的方法:一是通过注册广播接收器监听TelephonyIntents.ACTION_SERVICE_STATE_CHANGED广播;二是通过TelephonyManager注册PhoneStateListener。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载出处:http://blog.youkuaiyun.com/thl789/article/details/7361898


有些时候,需要侦听手机的ServiceState,本文从应用开发的角度,给出侦听Android系统手机ServiceState的方法:侦听广播TelephonyIntents.ACTION_SERVICE_STATE_CHANGED;在TelephonyManager中注册ListenerPhoneStateListener。

一、通过侦听广播

Android内部定义了ServiceState变化时,系统发出的广播(Action:TelephonyIntents.ACTION_SERVICE_STATE_CHANGED)。所以,如果要接收ServiceState的通知,可以通过代码注册

[java]  view plain  copy
  1. IntentFilter intentFilter = newIntentFilter(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);  
  2. // registerReceiver()是ContextWrapper定义的方法,子类中实现  
  3. registerReceiver(receiver, intentFilter);  

receiver是BroadcastReceiver,在其onReceive(Contextcontext, Intent intent)中,就可以侦听到ServiceState的变化:

[java]  view plain  copy
  1. onReceive(Context context, Intent intent) {  
  2. String action = intent.getAction();  
  3. if(action.equals(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED)) {  
  4.    ServiceState ss = ServiceState.newFromBundle(intent.getExtras())  
  5.     switch(ss.getState()) {  
  6.     case ServiceState.STATE_IN_SERVICE:  
  7.         //handle for …  
  8.        break;  
  9.     case …  
  10.        break;  
  11. else if () {  
  12.     //other broadcasts…  
  13. }  
  14. }  

在不用的时候,记得取消注册。而要接收这个广播,需要READ_PHONE_STATE的permission。

 

不过注意:这样的侦听方式,只能针对能看到底层的开发者,对于纯应用开发者来说是不行的。因为,TelephonyIntents是在com.android.intenal.telephony中定义的,而这个包是隐藏的。

 

二、注册Listener

既然com.android.intenal.telephony是隐藏的,给Android内部实现用的,那看外部exported的接口有什么。有一个android.telephony的包,里面有TelephonyManager。

Listen to PhoneState

通过TelephonyManager可以注册Listener来侦听ServiceState的变化。

 

TelephonyManager并不能直接被实例化,要获取它的实例,需要通过Context.getSystemService(),注册Listener通过listen(),其中的events是PhoneStateListener.LISTEN_xxx的bitmask:

[java]  view plain  copy
  1. TelephonyManager telMgr =(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);  
  2. telMgr.listen(mPhoneStateListener,PhoneStateListener.LISTEN_SERVICE_STATE);  

在mPhoneStateListener这个PhoneStateListener中overrideonServiceStateChanged(ServiceState serviceState)方法就可以了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值