Detect Home Button Press - Phát hiện nút Home
Android không cho phép ghi đè (override) trực tiếp sự kiện nút Home vì lý do bảo mật và trải nghiệm người dùng. Tuy nhiên, có thể phát hiện khi ứng dụng bị chuyển ra background do nhấn Home thông qua onUserLeaveHint().
Bước 1: Tạo dự án mới
Khởi tạo project Android Studio.
Bước 2: Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click here"
android:textSize="30sp"
android:gravity="center" />
</LinearLayout>
Bước 3: MainActivity.java
package com.example.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Giả lập gọi onUserLeaveHint để test
onUserLeaveHint();
}
});
}
@Override
protected void onUserLeaveHint() {
// Được gọi khi user nhấn Home hoặc chuyển app khác
text.setText("Home button pressed");
Toast.makeText(MainActivity.this, "Home button pressed", Toast.LENGTH_LONG).show();
super.onUserLeaveHint();
}
}
Giải thích cơ chế
onUserLeaveHint()là callback của Activity lifecycle- Được gọi khi user nhấn Home, Recent apps, hoặc khi có interruption (cuộc gọi, alarm...)
- Không đảm bảo 100% chỉ là nút Home - cũng kích hoạt khi chuyển app khác
- Được gọi trước
onPause()
Lưu ý quan trọng
- Không thể intercept/chặn nút Home - đây là thiết kế cố định của Android
onUserLeaveHint()chỉ là thông báo, không thể hủy bỏ hành động- Để xử lý "thoát app", hãy dùng
onPause()/onStop()hoặconDestroy() - Kiểm tra
isTaskRoot()hoặcActivityManagerđể biết app có thực sự bị ẩn không
Cách test thực tế
- Chạy app trên thiết bị thật
- Nhấn nút Home vật lý hoặc gesture
- App chuyển background,
onUserLeaveHint()được gọi - Mở lại app → TextView hiển thị "Home button pressed" và Toast hiện ra
Alternatives cho các nhu cầu phổ biến
| Nhu cầu | Giải pháp |
|---|---|
| Lưu dữ liệu khi user thoát | Override onPause() hoặc onStop() |
| Dừng music/video khi Home | Override onPause() gọi pause() |
| Clear sensitive data | Override onStop() hoặc dùng FLAG_SECURE |
| Detect app vào background | Dùng ProcessLifecycleOwner (Architecture Components) |