如何以程式設計方式退出應用程式?


此示例演示如何在 Android 中以程式設計方式退出應用程式。

步驟 1 − 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必要資訊以建立一個新專案。

步驟 2 − 將以下程式碼新增到 res/layout/activity_main.xml。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="4dp"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="50dp"
      android:textSize="24sp"
      android:textStyle="bold"
      android:textAlignment="center"
      android:text="Click the button to close the application"/>
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:onClick="QuitApp"
      android:textAlignment="center"
      android:text="QUIT APPLICATION"/>
</RelativeLayout>

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

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   public void QuitApp(View view) {
      MainActivity.this.finish();
      System.exit(0);
   }
}

步驟 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 執行應用程式,開啟一個專案活動檔案,然後單擊工具欄中的執行  圖示。選擇你的移動裝置作為選項,然後檢查顯示預設螢幕的移動裝置 −

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

更新時間:2019 年 11 月 26 日

已檢視 3K+ 次

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.