如何在 Android 應用中呼叫 onDestroy Activity?


以下示例演示如何在 Android 應用中呼叫 OnDestroy Activity。

步驟 1 − 在 Android Studio 中建立新專案,轉到 File ⇒ New Project,填寫所有必需的詳細資訊以建立新專案。

步驟 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:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginLeft="8dp"
      android:layout_marginTop="16dp"
      android:layout_marginRight="8dp"
      android:layout_marginBottom="32dp"
      android:text="Destroy"
      android:textColor="@color/colorPrimary"
      android:textSize="32dp"
      android:textStyle="bold"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

步驟 3 − 將以下程式碼新增到 src/MainActivity.java

package com.sample.q2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
   public static final String MY_TAG = "Destroy";
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Log.i(MY_TAG, "onCreate");
   }
   protected void onDestroy() {
      super.onDestroy();
      Log.i(MY_TAG, "onDestroy");
   }
}

步驟 4 − 將以下程式碼新增到 androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

讓我們嘗試執行你的應用程式。我假設你已將實際的 Android 移動裝置與電腦連線。要從 Android Studio 執行該應用程式,開啟專案的某個 activity 檔案,然後單擊工具欄中的執行圖示。選擇你的移動裝置作為選項,然後檢視移動裝置,它將顯示你的預設螢幕 −

單擊此處下載專案程式碼。

更新於:2019 年 8 月 1 日

843 次瀏覽

啟動你的 職業

完成本課程並獲得認證

開始
廣告