2014-02-20 55 views
0

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

+1

GET “alreadyShown” 从SharedPreferences如果== false然后显示表单并将“alreadyShow”= true放入SharedPreferences – Selvin

+0

,如果该应用程序尚未在市场上销售 – Blackbelt

+0

@blackbelt,则该工作方式将起作用。 。什么?他问如何知道活动何时已经开启一次。就像新用户第一次查看主要活动一样。 –

回答

4

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

你如何使用它:

定义静态布尔标志,并为其分配false值,一旦该活动首次创建,使标志真实的,现在你用简单的做你的任务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; 
} 
+0

这看起来很有前途,我会试试看。谢谢 –

+0

当然,让我知道如果它的工作:) –

+0

感谢它的工作原理 –

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

我的意思是第一次自应用程序启动以来第一次调用活动,而不是第一次在此设备上调用该活动。据我所知即使完全终止应用程序后,共享首选项仍然存在。 –

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. 

} 

然后,当你想关闭应用程序,为您获得此类信息的具体应用实例

OverrideActivity完成()方法

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

} 
相关问题