Ví dụ này minh họa cách đóng hoàn toàn ứng dụng Android bằng code (finish activity và exit process).
Bước 1: Tạo dự án mới
Tạo dự án mới trong Android Studio.
Bước 2: Cấu hình layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:textSize="20sp"
android:textStyle="bold"
android:text="Nhấn nút để thoát ứng dụng" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="quitApp"
android:text="THOÁT ỨNG DỤNG"
android:textAllCaps="false" />
</RelativeLayout>
Bước 3: Code MainActivity (src/MainActivity.java)
package com.app.sample;
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) {
// Cách 1: Chỉ finish activity hiện tại
// finish();
// Cách 2: Thoát hoàn toàn process (không khuyến khích cho app bình thường)
finishAffinity(); // Đóng tất cả activities trong task
System.exit(0); // Kill process
}
}
Lưu ý: Android khuyến khích dùng finishAffinity() (API 16+) thay vì System.exit(0) để hệ thống quản lý lifecycle đúng cách.
Bước 4: Cấu hình Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://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>
Chạy ứng dụng
Nhấn nút "THOÁT ỨNG DỤNG", app sẽ đóng hoàn toàn và về màn hình home.