开发者

Is there a way to get a current state of the application?

开发者 https://www.devze.com 2023-03-17 05:22 出处:网络
I have an application that periodically checks the server for some flag. And then displays a message depending on the value of this flag.

I have an application that periodically checks the server for some flag. And then displays a message depending on the value of this flag.

I don't want to display a message then the application is not in a front. And I use SharedPreferences to store the application state manually. In each activity I do something like:

@Override
protected void onStart() {
    super.onStart();
    SharedPreferences.Editor prefs = context.getSharedPreferences("myprefs", getApplicationContext().MODE_PRIVATE).edit();
    prefs.putBoolean("appInFront", true);
    prefs.commit();
}
@Override
protected void onPause() {
    super.onPause();
    SharedPreferences.Editor prefs = context.getSharedPreferences("myprefs", getApplicationContext().MODE_PRIVATE).edit();
    prefs.putBoolean("appInFront", false);
    prefs.commit();
}

And this allows me to get a state of the application from "appInFront" preference:

SharedPreferences prefs = context.getSharedPreferences("myprefs", Context.MODE_PRIVATE);
boolean appInFront = prefs.getBoolean("appInFront", true);      

But may be exists native method or way to get a current 开发者_JAVA百科state of the application (is the application in a front or is it in a background)?


What kind of message are you displaying?A Notification or something in your Activity? Where in your Application do you need that state information?

You can write an BaseActivity and extend all other Activities from. So you need to write less code. And as counterpart of onPause() you should use onResume():

public class BaseActivity{

public static boolean appInFront;

@Override
protected void onResume() {
    super.onResume();
    appInFront = true;
}
@Override
protected void onPause() {
    super.onPause();
    appInFront = false;
}

}

With that static public boolean you can ask from "anywhere" for the visibility state of your app. You probably don't need to remember the state between app restarts so a boolean is sufficient.

if(BaseActivity.appInFront){
    //show message
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号