魅力程序猿

  • 首页
  • Java
  • Android
  • APP
    • 扑克计分器
    • Video Wallpaper
  • 联系我
  • 关于我
  • 资助
道子
向阳而生
  1. 首页
  2. Android
  3. 正文

Android中怎么判断是Home键或非正常退出(进入后台)

2016年10月8日 10002点热度 0人点赞 6条评论

我们先写两个Activity:A和B,试着A打开B观察它们的生命周期:

 

你会发现是这样运行的:(A)onCreate->(A)onStart()->(A)onResume()->A正在运行中,此时A需要跳转的到B->(A)onPause()->(B)onCreate->(B)onStart()->(B)onResume()->B正在运行中->(A)onStop()->(A)onDestory()。是不是你发现了什么猫腻,找到了解决方法了。

OK,我直接说方法吧:

1、定义一个全局变量进行计数,我是在Application中声明了一个变量:

/** 用于判断APP进入后台使用 */
      public static int mAppActivityCount = 0;

2、在BaseActivity中的onStart()、onStop()方法中这样写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Override
protected void onStart() {
 try {
 super.onStart();
 XYApplication.mAppActivityCount ++;
 if (XYApplication.mAppActivityCount == 1) {
     //第一次启动
 }else {
     //由APP的其他Activity启动
 }
 } catch (Exception e) {
     e.printStackTrace();
 }
}

@Override
protected void onStop() {
 super.onStop();
 XYApplication.mAppActivityCount --;
 if (XYApplication.mAppActivityCount == 0) {
    //切到后台
 }else {
    //启动其他Activity
 }
}

3、A和B Activity继承BaseActivity

总结:看懂了没有,没有的话你可以亲自试试哦,验证一下对不。不行的话,可以留言或加QQ群:179730949。

还有更高大上的方法:

Android中怎么判断是Home键或非正常退出(进入后台)续

 

标签: Android判断一个App是否在前台运行 Home键或非正常退出(进入后台) 判断一个App是否在前台运行
最后更新:2016年10月8日

daozi

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

文章评论

  • Mattie

    …We were born in to this world with God’s will and one day we will also leave this world at his will. Therefore we should live our lives how Allah (God) wills us to, and he has revealed to us the Qura&8217;#n (our Intructions and guide) but it does not stop there; he is so generous he has also given us an example, the best of examples: The Prophet Muhammed (PBUH). We should live our lives being aware that Allah (God) is all knowledgable and knows what we do, even in secret. Ask4more info

    2016年12月19日
    回复
  • Seston

    Your story was really inartmfoive, thanks!

    2016年12月19日
    回复
  • gun of boom hack

    Good Day, glad that i saw on this in bing. Thanks!

    2017年9月26日
    回复
  • little snitch 4 crack

    yahoo brought me here. Thanks!

    2017年9月28日
    回复
  • razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
    回复 gun of boom hack 取消回复
    搜索
    联系方式

    QQ群:179730949
    QQ群:114559024
    欢迎您加入Android大家庭
    本人QQ:136049925

    赐我一丝安慰
    给我一点鼓励

    COPYRIGHT © 2023 魅力程序猿. ALL RIGHTS RESERVED.

    Theme Kratos Made By Seaton Jiang

    豫ICP备15000477号