Last active
December 25, 2019 06:50
-
-
Save Hasiy/f55aa79d0d5860bd65741b6e40e04a90 to your computer and use it in GitHub Desktop.
获取app 当前状态 在前台还是在后台
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @Author: hasiy | |
* @Date: 2019/1/12 - 17 : 06 | |
* @LastEditors: hasiy | |
* @LastEditTime: 2019/1/12 - 17 : 06 | |
* @Description: androoid | |
* @Email: hasiy.jj@gmail.com | |
* 程序主入口 | |
*/ | |
class MYApplication : Application() { | |
private var isBackground = false | |
companion object { | |
lateinit var appContext: WeakReference<Context> | |
} | |
override fun onCreate() { | |
super.onCreate() | |
appContext = WeakReference(applicationContext) | |
listenForForeground() | |
listenForScreenTurningOff() | |
} | |
private fun listenForForeground() { | |
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks { | |
override fun onActivityPaused(activity: Activity) {} | |
override fun onActivityStarted(activity: Activity) {} | |
override fun onActivityDestroyed(activity: Activity) {} | |
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} | |
override fun onActivityStopped(activity: Activity) {} | |
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {} | |
override fun onActivityResumed(activity: Activity?) { | |
if (isBackground) { | |
isBackground = false | |
LogUtil.e("应用到前台了") | |
} | |
} | |
}) | |
} | |
private fun listenForScreenTurningOff() { | |
registerReceiver(object : BroadcastReceiver() { | |
override fun onReceive(context: Context, intent: Intent) { | |
isBackground = true | |
LogUtil.e("应用到后台了") | |
} | |
}, IntentFilter(Intent.ACTION_SCREEN_OFF)) | |
} | |
override fun onTrimMemory(level: Int) { | |
super.onTrimMemory(level) | |
if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) { | |
isBackground = true | |
LogUtil.e("应用到后台了") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment