我希望我的主要活动在启动时显示弹出窗口,此活动是第一个创建的活动,但是可以创建此活动的多个实例,我只希望自启动后的第一个显示此弹出窗口,所以我想知道我是否可以检查这个。
答案 0 :(得分:5)
最简单的方法是使用静态变量
您如何使用它:
定义一个静态布尔标志并为其赋值false,一旦第一次创建活动,将标志设为true,现在用简单的if/else
条件执行任务
public static boolean flag=false;
然后在onCreate
if(flag==true)
{
//Activity is not calling for first time now
}
if(flag==false)
{
//first time calling activity
flag=true;
}
答案 1 :(得分:2)
在SharedPreferences
中存储标志,表示应用程序是否首次启动。使用Activity Oncreate方法:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create and check SharedPreferences if fist time launch
SharedPreferences settings = getSharedPreferences("showpopup", 0);
SharedPreferences.Editor editor = settings.edit();
if(settings.contains("firsttime")){
// means activity not launched first time
}else{
// means activity launched first time
//store value in SharedPreferences as true
editor.putBoolean("firsttime", true);
editor.commit();
//show popup
}
}
答案 2 :(得分:1)
我会使用selvins方法。除非您有应用程序设置和用户注册的后端,否则您将无法获得特定应用程序实例的此类信息,除非您使用SharedPreferences
int activityLaunchCount = 0;
SharedPreferences preferences = getBaseContext().getSharedPreferences("MyPreferences", SharedPreferences.MODE_PRIVATE);
activityLaunchCount = preferences.getInt("ActivityLaunchCount", 0);
if(activityLaunchCount < 1)
{
// ** This is where you would launch you popup **
// ......
// Then you will want to do this:
// Get the SharedPreferences.Editor Object used to make changes to shared preferences
SharedPreferences.Editor editor = preferences.edit();
// Then I would Increment this counter by 1, so if will never popup again.
activityLaunchCount += 1;
// Store the New Value
editor.putInt("ActivityLaunchCount", activityLaunchCount);
// You Must call this to make the changes
editor.commit();
}else{
// If you application is run one time, this will continue to execute each subsequent time.
// TODO: Normal Behavior without showing a popup of some sort before proceeding.
}
然后当你想要关闭应用程序时
Override
Activity
完成()方法
@Override public void finish()
{
super.finish();
// Get the SharedPreferences.Editor Object used to make changes to shared preferences
SharedPreferences.Editor editor = preferences.edit();
// Store the New Value
editor.putInt("ActivityLaunchCount", 0);
// You Must call this to make the changes
editor.commit();
}