100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > android 监听界面变化 Android之页面有变化用onWindowFocusChanged来监听权限是否开启...

android 监听界面变化 Android之页面有变化用onWindowFocusChanged来监听权限是否开启...

时间:2019-12-18 15:49:19

相关推荐

android 监听界面变化 Android之页面有变化用onWindowFocusChanged来监听权限是否开启...

1 问题

我们需要在Activity里面监听网络变化、热点是否开启和关闭、GPS服务是否开启、位置权限是否开启等一些列行为。

2 思路

方法一:

如果是需要启动activity进行权限申请,我们可以用如下组合模式

var intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)

startActivityForResult(intent, REQUEST_GPS_CODE)

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

super.onActivityResult(requestCode, resultCode, data)

Log.i(TAG, "onActivityResult start requestCode is:" + requestCode)

//Android8.0以上版本

if (requestCode == REQUEST_GPS_CODE) {

}

}

方法二:

我们在onResume里面进行权限检测

方法三:

注册广播来进行监听

方法四:

利用handler.postDelayed实现定时器,然后定时检测权限

/**

* 检查是否满足条件让按钮变蓝色的定时器

*/

inner class CheckCondition : Runnable {

var context: Context? = null

var type: String? = null

constructor(context: Context, type: String) {

this.context = context

this.type = type

}

override fun run() {

var result = false

result = condition(type!!)

Log.i(TAG, "CheckCondition result is:$result")

if (result) {

nextCreateWifAp.isEnabled = true

} else {

nextCreateWifAp.isEnabled = false

}

handler!!.postDelayed(this, 1000)

}

}

checkCondition = CheckCondition(this, ANDROID_VERSION_SIX_TO_SEVEN)

handler.postDelayed(checkCondition, TIME_TITERVAL)

方法五:

在onWindowFocusChanged函数里面检测,比如切换页面,滑动菜单栏,都能触发到,方案最理想,基本上能满足你的需求。

override fun onWindowFocusChanged(hasFocus: Boolean) {

super.onWindowFocusChanged(hasFocus)

Log.i(TAG, "onWindowFocusChanged----------------------->")

var result = false

handler.postDelayed(Runnable {

result = condition(currentType)

Log.i(TAG, "CheckCondition result is:$result")

if (result) {

nextCreateWifAp.isEnabled = true

} else {

nextCreateWifAp.isEnabled = false

}

}, 1000)

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。