【问题标题】:Is there a way to get a current state of the application?有没有办法获取应用程序的当前状态?
【发布时间】:2011-09-26 22:53:54
【问题描述】:

我有一个应用程序定期检查服务器是否有一些标志。 然后根据此标志的值显示一条消息。

如果应用程序不在前面,我不想显示消息。 我使用 SharedPreferences 手动存储应用程序状态。 在每项活动中,我都会执行以下操作:

@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);      

但可能存在获取应用程序当前状态的本机方法或方式(应用程序是在前面还是在后台)?

【问题讨论】:

    标签: android application-state


    【解决方案1】:

    您正在显示什么样的消息?您的活动中的通知或其他内容? 您在应用程序的哪个位置需要该状态信息?

    您可以编写一个 BaseActivity 并从中扩展所有其他活动。所以你需要编写更少的代码。作为 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;
    }
    

    }

    使用该静态公共布尔值,您可以从“任何地方”询问您应用的可见性状态。 您可能不需要记住应用重新启动之间的状态,因此布尔值就足够了。

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

    【讨论】:

    • 我在 BroadcastReceiver 中使用 Toast 通知,就像 SDK 示例中的 ApiDemos/app/AlarmController 一样。
    • 为什么onResume方法里有super.onStart()?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 2013-05-16
    • 2012-01-01
    • 2021-12-21
    相关资源
    最近更新 更多