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)
}