您的位置:首页 > 移动开发 > Android开发

侦听Android手机ServiceState

2016-05-20 09:00 579 查看
转载出处:http://blog.csdn.net/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

IntentFilter intentFilter = newIntentFilter(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);

// registerReceiver()是ContextWrapper定义的方法,子类中实现

registerReceiver(receiver, intentFilter);

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

[java] view
plain copy

onReceive(Context context, Intent intent) {

String action = intent.getAction();

if(action.equals(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED)) {

ServiceState ss = ServiceState.newFromBundle(intent.getExtras())

switch(ss.getState()) {

case ServiceState.STATE_IN_SERVICE:

//handle for …

break;

case …

break;

} else if () {

//other broadcasts…

}

}

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

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

二、注册Listener

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



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

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

[java] view
plain copy

TelephonyManager telMgr =(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);

telMgr.listen(mPhoneStateListener,PhoneStateListener.LISTEN_SERVICE_STATE);

在mPhoneStateListener这个PhoneStateListener中overrideonServiceStateChanged(ServiceState serviceState)方法就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: