Android 确定应用是否以编程方式首次启动?
androidmobile developmentapps/applications更新于 2026/1/17 16:52:17
此示例演示了 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 运行该应用程序,请打开项目的某个活动文件,然后点击工具栏上的"运行"图标
。选择您的移动设备作为选项,然后勾选将显示默认屏幕的移动设备 –

用户首次打开应用时,将显示如上所示的消息,否则将显示如下消息

点击此处下载项目代码

