我有一个应用程序会定期检查服务器是否有一些标志。 然后根据这个标志的值显示一条消息。
我不想在应用程序不在前面时显示消息。 我使用 SharedPreferences 手动存储应用程序状态。 在每项 Activity 中,我都会做类似的事情:
@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();
}
这让我可以从“appInFront”首选项中获取应用程序的状态:
SharedPreferences prefs = context.getSharedPreferences("myprefs", Context.MODE_PRIVATE);
boolean appInFront = prefs.getBoolean("appInFront", true);
但是可能存在获取应用程序当前状态的 native 方法或方式(应用程序是在前台还是在后台)?
最佳答案
您要显示什么样的消息?在您的 Activity 中显示通知还是其他内容? 您在应用程序的哪个位置需要该状态信息?
您可以编写一个 BaseActivity 并从中扩展所有其他 Activity。所以你需要写更少的代码。作为 onPause() 的对应物,您应该使用 onResume():
public class BaseActivity{
public static boolean appInFront;
@Override
protected void onResume() {
super.onResume();
appInFront = true;
}
@Override
protected void onPause() {
super.onPause();
appInFront = false;
}
使用该静态公共(public) bool 值,您可以从“任何地方”询问应用的可见性状态。 您可能不需要记住应用重启之间的状态,因此 bool 值就足够了。
if(BaseActivity.appInFront){
//show message
}
关于android - 有没有办法获取应用程序的当前状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6551613/