Android 如何以编程方式确定应用是否首次启动?
此示例演示了如何以编程方式确定 Android 应用是否首次启动。
步骤 1 − 在 Android Studio 中创建一个新项目,转到 文件 ⇒ 新建项目,并填写所有必要的信息以创建新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.xml 中。
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/frstTime"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:text = "Hello World!"
android:textSize = "30sp"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintLeft_toLeftOf = "parent"
app:layout_constraintRight_toRightOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>在上面的代码中,我们使用了 TextView,当用户打开应用程序时,它将检查这是否是第一次打开。如果是第一次,它将在 TextView 中追加“首次启动”文本,否则显示“多次启动”文本。
步骤 3 − 将以下代码添加到 src/MainActivity.java 中
package com.example.andy.myapplication;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
SharedPreferences.Editor sharedEditor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
sharedEditor = sharedPreferences.edit();
TextView frstTime = findViewById(R.id.frstTime);
if (isItFirestTime()) {
frstTime.setText("First Time");
} else {
frstTime.setText("Not a First Time");
}
}
public boolean isItFirestTime() {
if (sharedPreferences.getBoolean("firstTime", true)) {
sharedEditor.putBoolean("firstTime", false);
sharedEditor.commit();
sharedEditor.apply();
return true;
} else {
return false;
}
}
}让我们尝试运行您的应用程序。我假设您已将您的实际 Android 移动设备连接到您的计算机。要从 Android Studio 运行应用程序,请打开您的项目中的某个 Activity 文件,然后点击工具栏中的运行
图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕 -

当用户第一次打开应用程序时,它将显示如下所示的消息,否则将显示如下所示的消息 -

点击 这里 下载项目代码
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP