2011-07-01 214 views
1

我有一个应用程序定期检查服务器的一些标志。 然后根据此标志的值显示一条消息。有没有办法获得应用程序的当前状态?

我不想显示消息,那么应用程序不在前面。 我使用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);  

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

回答

3

你显示的是什么样的信息?通知或你的活动中的某些信息? 你的应用程序中的哪个位置需要该状态信息?

您可以编写一个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 
} 
+0

我在BroadcastReceiver中使用Toast Notifications,就像SDKDeveloper中的ApiDemos/app/AlarmController一样。 – Serg

+0

谢谢赫尔曼,我这样做了。 – Serg

+0

为什么在onResume方法中有super.onStart()? – maysi

相关问题