2011-01-08 57 views
86

我目前正在开发一个android应用。我第一次启动应用程序时需要做些事情,即代码只在第一次启动程序时运行。确定android应用是否是第一次使用

+1

当我刚开始做的应用程序,我只是想在第一次运行一个应用程序后调用此已安装。后来我意识到,升级后我还需要处理和区分第一次运行。 @ schnatterer的答案在下面和我的答案[这里](http://stackoverflow.com/a/30274315/3681880)显示如何做到这一点。谨慎对待不考虑升级的答案。 – Suragch 2015-07-22 16:25:02

+0

@Suragch你表现得好像它是坏的做法是不采取升级的考虑,但在某些情况下,就像你不想做:) – creativecreatorormaybenot 2016-09-12 17:59:14

+0

@creativecreatorormaybenot一个应用程序的介绍,这是事实。有时你只关心初始安装而不关心后续升级。一个简单的布尔值就足够用于这些情况。但是,如果在将来某个时候想要为当前用户添加一个不同的介绍,以了解刚才添加的所有新功能?在我看来,检查版本号而不是布尔值是比较有远见的。这至少会为您提供一种选择,以便为新安装和升级提供另一种方式。 – Suragch 2016-09-13 01:45:02

回答

42

另一个想法是使用共享首选项中的设置。相同的一般想法检查一个空文件,但你没有一个空文件左右浮动,没有被用来存储任何

+2

以上的答案,注意这种方法无法在Android Froyo上使用三星Galaxy S。这是因为SharedPreferences存在一个错误。下面是对一个SO问题的链接:http://stackoverflow.com/questions/7296163/cant-save-my-preferences-after-app-killed这里对谷歌代码门票:http://code.google ?的.com/p /机器人/问题/细节ID = 14359 – 2012-03-09 08:07:25

+2

当心为Android 6.0(API 23 - 棉花糖)或以上的自动备份(https://developer.android.com/guide/topics/data/autobackup.html)是默认启用的。如果用户卸载并重新安装应用程序,共享首选项将被恢复。因此,在重新安装后,如果有任何问题需要重新安装,您无法检查它是否第一次运行。 – Alan 2017-03-09 23:38:33

1

您可以简单地检查是否存在空文件,如果它不存在,那么执行您的代码并创建文件。

例如

if(File.Exists("emptyfile"){ 
    //Your code here 
    File.Create("emptyfile"); 
} 
+0

我想这样做的,但认为必须有一个更好的办法 – Boardy 2011-01-08 21:10:55

+0

我不知道任何,但什么是你通过收到缺乏ressources的? 4个字节的文件和一个“如果”在开始。 系统例程会做同样的,他们会做同样的或使表与已lauched – 2011-01-08 21:13:49

+0

以类似的方式,你可以使用sharedpreferences,而如果不存在应用程序,则显示闪现屏幕等...并在程序第一次运行时创建它(在检查它之后的obv)。请参阅凯文在 – stealthcopter 2011-01-08 21:30:58

2

下面是一些这方面的代码 -

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
        "/Android/data/myapp/files/myfile.txt"; 

boolean exists = (new File(path)).exists(); 

if (!exists) { 
    doSomething();          
} 
else { 
    doSomethingElse(); 
} 
96

可以使用SharedPreferences来确定它是否是首次启动应用程序。 只需使用一个布尔变量(“my_first_time”)和它的值改为当你的“第一次”的任务已经结束了。

这是我的代码赶上第一次打开应用程序:

final String PREFS_NAME = "MyPrefsFile"; 

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 

if (settings.getBoolean("my_first_time", true)) { 
    //the app is being launched for first time, do something   
    Log.d("Comments", "First time"); 

      // first time task 

    // record the fact that the app has been started at least once 
    settings.edit().putBoolean("my_first_time", false).commit(); 
} 
-1
/** 
    * @author ALGO 
    */ 
    import java.io.File; 
    import java.io.FileOutputStream; 
    import java.io.IOException; 
    import java.io.RandomAccessFile; 
    import java.util.UUID; 

    import android.content.Context; 

    public class Util { 
     // =========================================================== 
     // 
     // =========================================================== 

     private static final String INSTALLATION = "INSTALLATION"; 

     public synchronized static boolean isFirstLaunch(Context context) { 
      String sID = null; 
      boolean launchFlag = false; 
      if (sID == null) { 
       File installation = new File(context.getFilesDir(), INSTALLATION); 
       try { 
        if (!installation.exists()) { 

         writeInstallationFile(installation); 
        } 
        sID = readInstallationFile(installation); 
launchFlag = true; 
       } catch (Exception e) { 
        throw new RuntimeException(e); 
       } 
      } 
      return launchFlag; 
     } 

     private static String readInstallationFile(File installation) throws IOException { 
      RandomAccessFile f = new RandomAccessFile(installation, "r");// read only mode 
      byte[] bytes = new byte[(int) f.length()]; 
      f.readFully(bytes); 
      f.close(); 

      return new String(bytes); 
     } 

     private static void writeInstallationFile(File installation) throws IOException { 
      FileOutputStream out = new FileOutputStream(installation); 
      String id = UUID.randomUUID().toString(); 
      out.write(id.getBytes()); 
      out.close(); 
     } 
    } 

> Usage (in class extending android.app.Activity) 

Util.isFirstLaunch(this); 
55

我建议不仅存储布尔标志,但完整版本的代码。 通过这种方式,您可以在开始时查询它是否是新版本中的第一次启动。例如,您可以使用这些信息来显示“Whats new”对话框。

下面的代码应该可以从任何“是上下文”(activity,services,...)的android类中工作。如果您希望将其放在单独的(POJO)课程中,则可以考虑使用“静态上下文”,如here所述。

/** 
* Distinguishes different kinds of app starts: <li> 
* <ul> 
* First start ever ({@link #FIRST_TIME}) 
* </ul> 
* <ul> 
* First start in this version ({@link #FIRST_TIME_VERSION}) 
* </ul> 
* <ul> 
* Normal app start ({@link #NORMAL}) 
* </ul> 
* 
* @author schnatterer 
* 
*/ 
public enum AppStart { 
    FIRST_TIME, FIRST_TIME_VERSION, NORMAL; 
} 

/** 
* The app version code (not the version name!) that was used on the last 
* start of the app. 
*/ 
private static final String LAST_APP_VERSION = "last_app_version"; 

/** 
* Finds out started for the first time (ever or in the current version).<br/> 
* <br/> 
* Note: This method is <b>not idempotent</b> only the first call will 
* determine the proper result. Any subsequent calls will only return 
* {@link AppStart#NORMAL} until the app is started again. So you might want 
* to consider caching the result! 
* 
* @return the type of app start 
*/ 
public AppStart checkAppStart() { 
    PackageInfo pInfo; 
    SharedPreferences sharedPreferences = PreferenceManager 
      .getDefaultSharedPreferences(this); 
    AppStart appStart = AppStart.NORMAL; 
    try { 
     pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); 
     int lastVersionCode = sharedPreferences 
       .getInt(LAST_APP_VERSION, -1); 
     int currentVersionCode = pInfo.versionCode; 
     appStart = checkAppStart(currentVersionCode, lastVersionCode); 
     // Update version in preferences 
     sharedPreferences.edit() 
       .putInt(LAST_APP_VERSION, currentVersionCode).commit(); 
    } catch (NameNotFoundException e) { 
     Log.w(Constants.LOG, 
       "Unable to determine current app version from pacakge manager. Defenisvely assuming normal app start."); 
    } 
    return appStart; 
} 

public AppStart checkAppStart(int currentVersionCode, int lastVersionCode) { 
    if (lastVersionCode == -1) { 
     return AppStart.FIRST_TIME; 
    } else if (lastVersionCode < currentVersionCode) { 
     return AppStart.FIRST_TIME_VERSION; 
    } else if (lastVersionCode > currentVersionCode) { 
     Log.w(Constants.LOG, "Current version code (" + currentVersionCode 
       + ") is less then the one recognized on last startup (" 
       + lastVersionCode 
       + "). Defenisvely assuming normal app start."); 
     return AppStart.NORMAL; 
    } else { 
     return AppStart.NORMAL; 
    } 
} 

它可以从活动中使用这样的:

public void testCheckAppStart() { 
    // First start 
    int oldVersion = -1; 
    int newVersion = 1; 
    assertEquals("Unexpected result", AppStart.FIRST_TIME, 
      service.checkAppStart(newVersion, oldVersion)); 

    // First start this version 
    oldVersion = 1; 
    newVersion = 2; 
    assertEquals("Unexpected result", AppStart.FIRST_TIME_VERSION, 
      service.checkAppStart(newVersion, oldVersion)); 

    // Normal start 
    oldVersion = 2; 
    newVersion = 2; 
    assertEquals("Unexpected result", AppStart.NORMAL, 
      service.checkAppStart(newVersion, oldVersion)); 
} 

有了多一点的努力,你大概可以:

public class MainActivity extends Activity {   
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     switch (checkAppStart()) { 
     case NORMAL: 
      // We don't want to get on the user's nerves 
      break; 
     case FIRST_TIME_VERSION: 
      // TODO show what's new 
      break; 
     case FIRST_TIME: 
      // TODO show a tutorial 
      break; 
     default: 
      break; 
     } 

     // ... 
    } 
    // ... 
} 

的基本逻辑可以用这个JUnit测试来验证测试android相关的东西(PackageManager和SharedPreferences)。 有兴趣编写测试的人吗? :)

请注意,如果您不在AndroidManifest.xml中混淆android:versionCode,上述代码才能正常工作!

1

我做了一个简单的类来检查你的代码是第一次运行/ n次!

创建一个独特的喜好

FirstTimePreference prefFirstTime = new FirstTimePreference(getApplicationContext()); 

使用runTheFirstTime,选择一键检查事件

if (prefFirstTime.runTheFirstTime("myKey")) { 
    Toast.makeText(this, "Test myKey & coutdown: " + prefFirstTime.getCountDown("myKey"), 
        Toast.LENGTH_LONG).show(); 
} 

使用runTheFirstNTimes,选择键和多少次执行

if(prefFirstTime.runTheFirstNTimes("anotherKey" , 5)) { 
    Toast.makeText(this, "ciccia Test coutdown: "+ prefFirstTime.getCountDown("anotherKey"), 
        Toast.LENGTH_LONG).show(); 
} 
  • 使用getCountDown(),以更好地处理你的代码

FirstTimePreference.java

-1

嗨,大家好,我做这样的事情。而其作品对我来说

创造共享价值preference.Default布尔字段是真的 {isFirstTime:真正} 之后的第一时间设置为false。在android系统中,没有什么比这更简单和可靠的了。

0

为什么不使用数据库帮助器?这将有一个很好的onCreate,这只是第一次启动应用程序。这将有助于那些想要在初始应用程序安装完毕后跟踪这些内容而无需跟踪的人员。

0

我喜欢在我的共享偏好设置中使用“更新计数”。如果它不存在(或默认的零值),那么这是我的应用程序的“首次使用”。

private static final int UPDATE_COUNT = 1; // Increment this on major change 
... 
if (sp.getInt("updateCount", 0) == 0) { 
    // first use 
} else if (sp.getInt("updateCount", 0) < UPDATE_COUNT) { 
    // Pop up dialog telling user about new features 
} 
... 
sp.edit().putInt("updateCount", UPDATE_COUNT); 

所以,现在,只要有一个更新的应用程序,用户应该知道,我增加UPDATE_COUNT

1

我解决,以确定应用程序是否是你第一次与否,取决于它是否是一个更新。

private int appGetFirstTimeRun() { 
    //Check if App Start First Time 
    SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0); 
    int appCurrentBuildVersion = BuildConfig.VERSION_CODE; 
    int appLastBuildVersion = appPreferences.getInt("app_first_time", 0); 

    //Log.d("appPreferences", "app_first_time = " + appLastBuildVersion); 

    if (appLastBuildVersion == appCurrentBuildVersion) { 
     return 1; //ya has iniciado la appp alguna vez 

    } else { 
     appPreferences.edit().putInt("app_first_time", 
       appCurrentBuildVersion).apply(); 
     if (appLastBuildVersion == 0) { 
      return 0; //es la primera vez 
     } else { 
      return 2; //es una versión nueva 
     } 
    } 
} 

计算结果:

  • 0:如果这是第一次。
  • 1:它已经开始了。
  • 2:它已经启动一次,但不是该版本,即它是一个更新。
1

支持库修订版本23.3.0(在v4中表示可回溯到Android 1.6)的支持。

在你的启动活动,第一个电话:

AppLaunchChecker.onActivityCreate(activity); 

然后调用:

AppLaunchChecker.hasStartedFromLauncher(activity); 

将返回如果这是第一次应用程序正式启动。

2

您可以使用Android SharedPreferences

Android SharedPreferences允许我们以键 - 值对的形式存储专用原始应用数据 。

CODE

创建一个自定义类SharedPreference

public class SharedPreference { 

    android.content.SharedPreferences pref; 
    android.content.SharedPreferences.Editor editor; 
    Context _context; 
    private static final String PREF_NAME = "testing"; 

    // All Shared Preferences Keys Declare as #public 
    public static final String KEY_SET_APP_RUN_FIRST_TIME  =  "KEY_SET_APP_RUN_FIRST_TIME"; 


    public SharedPreference(Context context) // Constructor 
    { 
     this._context = context; 
     pref = _context.getSharedPreferences(PREF_NAME, 0); 
     editor = pref.edit(); 

    } 

    /* 
    * Set Method Generally Store Data; 
    * Get Method Generally Retrieve Data ; 
    * */ 


    public void setApp_runFirst(String App_runFirst) 
    { 
     editor.remove(KEY_SET_APP_RUN_FIRST_TIME); 
     editor.putString(KEY_SET_APP_RUN_FIRST_TIME, App_runFirst); 
     editor.commit(); 
    } 

    public String getApp_runFirst() 
    { 
     String App_runFirst= pref.getString(KEY_SET_APP_RUN_FIRST_TIME, "FIRST"); 
     return App_runFirst; 
    } 

} 

现在打开你的活动&初始化

private  SharedPreference    sharedPreferenceObj; // Declare Global 

现在的OnCreate部分

sharedPreferenceObj=new SharedPreference(YourActivity.this); 

现在检查

if(sharedPreferenceObj.getApp_runFirst().equals("FIRST")) 
{ 
    // That's mean First Time Launch 
    // After your Work , SET Status NO 
    sharedPreferenceObj.setApp_runFirst("NO"); 
} 
else 
{ 
    // App is not First Time Launch 
} 
相关问题