如何监视SIM状态变化

我希望能够做一些事情,当SIM卡状态改变,即播放声音时,需要SIM卡PIN,但我认为没有广播事件,可以拦截广播接收器为此…注册android.intent.action .PHONE_STATE只会告诉你什么时候CALL-STATE改变了。另一种方法是启动一个注册PhoneStateListener的服务,并在LISTEN_SERVICE_STATE时作出反应(当状态是Out-of-state时,它可以获得SIM状态,并查看状态是否为SIM_STATE_PIN_REQUIRED)。 所以,我的问题是:

1)是否有任何广播意图可用于拦截SIM状态更改或服务状态更改?

2)PhoneStateListener接收到电话状态变化的通知后,在服务中安装PhoneStateListener并使用它传递意图给服务本身是一个坏主意?

SIM状态改变时,广播意图android.intent.action.SIM_STATE_CHANGED 。 例如,在HTC Desire上使用T-Mobile SIM卡,如果将设备置于飞行模式,则广播以下意图:

  • Intent:android.intent.action.SIM_STATE_CHANGED with extras:ss = NOT_READY,reason = null

如果我把它从飞行模式中删除,则播放下列意图:

  • 意图:android.intent.action.SIM_STATE_CHANGED与额外:SS =locking,原因= PIN
  • Intent:android.intent.action.SIM_STATE_CHANGED with extras:ss = READY,reason = null
  • Intent:android.intent.action.SIM_STATE_CHANGED with extras:ss = IMSI,reason = null
  • 意图:android.intent.action.SIM_STATE_CHANGED额外:ss = LOADED,reason = null

不同的制造商和不同的型号可能会有不同的performance。 正如他们所说,“你的里程可能会有所不同”。

在监听onServiceStateChanged()的服务中使用PhoneStateListener的第二种方法适用于我。 我相信在一些设备上,你不会得到内部广播android.intent.action.SIM_STATE_CHANGED

大卫的答案是现货。 我想添加一些示例代码来帮助人们开始实施这样的状态监视器。

 /** * Handles broadcasts related to SIM card state changes. * <p> * Possible states that are received here are: * <p> * Documented: * ABSENT * NETWORK_LOCKED * PIN_REQUIRED * PUK_REQUIRED * READY * UNKNOWN * <p> * Undocumented: * NOT_READY (ICC interface is not ready, eg radio is off or powering on) * CARD_IO_ERROR (three consecutive times there was a SIM IO error) * IMSI (ICC IMSI is ready in property) * LOADED (all ICC records, including IMSI, are loaded) * <p> * Note: some of these are not documented in * https://developer.android.com/reference/android/telephony/TelephonyManager.html * but they can be found deeper in the source code, namely in com.android.internal.telephony.IccCardConstants. */ public class SimStateChangedReceiver extends BroadcastReceiver { /** * This refers to com.android.internal.telehpony.IccCardConstants.INTENT_KEY_ICC_STATE. * It seems not possible to refer it through a builtin class like TelephonyManager, so we * define it here manually. */ private static final String EXTRA_SIM_STATE = "ss"; @Override public void onReceive(Context context, Intent intent) { String state = intent.getExtras().getString(EXTRA_SIM_STATE); if (state == null) { return; } // Do stuff depending on state switch (state) { case "ABSENT": break; case "NETWORK_LOCKED": break; // etc. } } }