Android双卡切换监测移动数据状态

用kotlin 语言Android 双卡切换判断移动数据是否开启

private var telephonyManager: TelephonyManager? = null
private var dialogBuilder: MaterialAlertDialogBuilder? = null
private var dialog: AlertDialog? = null
override fun onResume() {
    super.onResume()
    telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?
    telephonyManager!!.listen(myPhoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
    dialogBuilder = MaterialAlertDialogBuilder(this)
            .setTitle("温馨提示")
            .setMessage("请打开移动数据,否则可能无法正常使用")
            .setPositiveButton("知道了") { _, _ ->
                closeApp()
            }
            .setNegativeButton("去打开") { _, _ ->
                openMobileData()
            }
            .setCancelable(false)
}
override fun onPause() {
    super.onPause()
    Timber.i("onPause Activity ${javaClass.simpleName}")
    telephonyManager!!.listen(myPhoneStateListener, PhoneStateListener.LISTEN_NONE);
}
val myPhoneStateListener = object : PhoneStateListener() {
    override fun onDataConnectionStateChanged(state: Int,networkType: Int) {
        super.onDataConnectionStateChanged(state)
        //监听流量状态
        BLogUtils.e("VectorBaseActivity", "===========onDataConnectionStateChanged====state==========" + state+"networkType"+networkType)
        if (state == TelephonyManager.DATA_DISCONNECTED&&networkType == 20) {
            //移动数据关闭
            dialog = dialogBuilder!!.show()
        } else if(state == TelephonyManager.DATA_DISCONNECTED&&networkType == 13) {
            //移动数据开启  副卡
            if (dialog != null) {
                dialog!!.dismiss()
            }
        } else if(state == TelephonyManager.DATA_CONNECTED){
            //移动数据开启  主卡
            if (dialog != null) {
                dialog!!.dismiss()
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值