How to get callback when Android app comes foregro

2019-05-25 11:01发布

How to know app state background to foreground in android?

I had extends my activities from one Baseactivity call and Baseactivity class extends android Activity. I put code appcomeForeground() into base activity on onRestart() but its call when we navigate activity into our foreground app also.

Please suggest way to get call back only when app comes foreground.

Thanks in advance.

4条回答
smile是对你的礼貌
2楼-- · 2019-05-25 11:38

Maintain a boolean variable in Baseactivity,

i.e.:

  private boolean  isForeground;

Inside onResume() of Baseactivity make isForeground = true and inside onPause() method of Baseactivity make isForeground = false

and whenever you want to know the status,check that boolean variable and apply your further logic accordingly.

查看更多
闹够了就滚
3楼-- · 2019-05-25 11:44

Another way to solve is to call putExtra on the intents which let the user navigate between the app's activities. If onRestart/onResume does not receive this Extra, the app was just coming into foreground.

查看更多
趁早两清
4楼-- · 2019-05-25 11:49

to check whether your application is in background of foreground you can do the following.

Declare a class which will maintain the state

public class ApplicationState {
    public static boolean isActivityVisible() {
        return activityVisible;
    }

    public static void activityResumed() {
        activityVisible = true;
    }

    public static void activityPaused() {
        activityVisible = false;
    }

    private volatile static boolean activityVisible;
}

in the onResume method of every activity of your application call

ApplicationState.activityResumed()

and in onPause method of every activity of your application call

ApplicationState.activityPaused()

Now at anytime you can check the foreground/background state of your application by just calling

ApplicationState.isActivityVisible()
查看更多
叼着烟拽天下
5楼-- · 2019-05-25 11:52

There's no framework-provided way to do this. I've described my own solution here: https://stackoverflow.com/a/14734761/1207921

查看更多
登录 后发表回答