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 檔案,然後點選工具欄中的執行  圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -

當用戶第一次開啟應用程式時,它將顯示如下所示的訊息,否則將顯示如下所示的訊息 -

點選 這裡 下載專案程式碼

更新於: 2019年7月30日

1K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告