检查应用程序是否首次运行

Wan*_*bal 94 android

我是Android开发新手,我想在安装后首先根据应用程序设置一些应用程序的属性.有没有办法找到应用程序第一次运行,然后设置其第一个运行属性?

Squ*_*onk 236

以下是SharedPreferences用于实现"首次运行"检查的示例.

public class MyActivity extends Activity {

    SharedPreferences prefs = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Perhaps set content view here

        prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (prefs.getBoolean("firstrun", true)) {
            // Do first run stuff here then set 'firstrun' as false
            // using the following line to edit/commit prefs
            prefs.edit().putBoolean("firstrun", false).commit();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当代码运行时,prefs.getBoolean(...)如果没有使用键"firstrun" boolean保存,SharedPreferences则表示应用程序从未运行过(因为没有任何东西保存过该键的布尔值,或者用户已清除应用程序数据以强制"第一次运行"场景.如果这不是第一次运行,那么该行将prefs.edit().putBoolean("firstrun", false).commit();被执行,因此prefs.getBoolean("firstrun", true)它将实际返回false,因为它会覆盖作为第二个参数提供的默认值true.

  • @Squonk你能告诉我将代码分别放在onCreate()和onResume()中的好处吗? (6认同)
  • 如果应用将android:allowBackup =“ true”(默认设置为true)设置为默认值,并且在卸载后在设备上启用备份后在安装后恢复了sharedpreference,则此方法将无效。因此,还要确保在AndroidManifest.xml中设置android:allowBackup =“ false”。 (4认同)
  • 您好,如果用户清除应用程序数据怎么办?共享偏好数据会被清除吗? (2认同)

Sur*_*gch 113

接受的答案不区分第一次运行和后续升级.只需在共享首选项中设置布尔值,只会告诉您它是否是首次安装应用程序后的第一次运行.稍后如果您想升级您的应用并在第一次升级时进行一些更改,您将无法再使用该布尔值,因为共享首选项会在升级过程中保存.

此方法使用共享首选项来保存版本代码而不是布尔值.

import com.yourpackage.BuildConfig;
...

private void checkFirstRun() {

    final String PREFS_NAME = "MyPrefsFile";
    final String PREF_VERSION_CODE_KEY = "version_code";
    final int DOESNT_EXIST = -1;

    // Get current version code
    int currentVersionCode = BuildConfig.VERSION_CODE;

    // Get saved version code
    SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    int savedVersionCode = prefs.getInt(PREF_VERSION_CODE_KEY, DOESNT_EXIST);

    // Check for first run or upgrade
    if (currentVersionCode == savedVersionCode) {

        // This is just a normal run
        return;

    } else if (savedVersionCode == DOESNT_EXIST) {

        // TODO This is a new install (or the user cleared the shared preferences)

    } else if (currentVersionCode > savedVersionCode) {

        // TODO This is an upgrade
    }

    // Update the shared preferences with the current version code
    prefs.edit().putInt(PREF_VERSION_CODE_KEY, currentVersionCode).apply();
}
Run Code Online (Sandbox Code Playgroud)

您可能会onCreate在主活动中调用此方法,以便每次应用启动时都会检查此方法.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkFirstRun();
    }

    private void checkFirstRun() {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

如果需要,您可以调整代码以执行特定操作,具体取决于用户以前安装的版本.

想法来自这个答案.这些也有帮助:

如果您在获取版本代码时遇到问题,请参阅以下问答:


AZ_*_*AZ_ 5

    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()) {
                    launchFlag = true;                          
                        writeInstallationFile(installation);
                    }
                    sID = readInstallationFile(installation);

                } 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);
Run Code Online (Sandbox Code Playgroud)