繁体   English   中英

检查活动是否是自启动以来的第一个活动

[英]check if activity is the first since launch

我希望我的主要活动在启动时显示一个弹出窗口,该活动是创建的第一个活动,但是可以创建该活动的多个实例,并且我只希望自启动以来的第一个活动显示此弹出窗口,所以我想知道是否有办法检查。

最简单的方法是使用静态变量

你如何使用它:

首次创建活动后,定义一个静态布尔标志并将其分配为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;
}

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 
     }
}

我会使用塞尔文斯方法。 除非您具有应用程序设置和用户注册的后端,否则除非您使用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 finish()方法

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM