Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách phát hiện người dùng nhấn phím Home trong Activity Android

Giới thiệu

Bài viết này minh họa cách phát hiện khi người dùng nhấn phím Home (quay về màn hình chính) trong một Activity. Android không cho phép ghi đè trực tiếp sự kiện phím Home vì lý do bảo mật, nhưng có thể dùng callback onUserLeaveHint() – được gọi khi Activity sắp mất focus do người dùng nhấn Home hoặc chuyển app.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và tạo dự án.

Bước 2: Thiết kế giao diện (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/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Nhấn Home để test"
        android:textSize="30sp"
        android:gravity="center" />

</LinearLayout>

Bước 3: Viết code logic (src/MainActivity.java)

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textView);
        textView.setOnClickListener(v -> onUserLeaveHint());
    }

    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
        textView.setText("Đã nhấn phím Home");
        Toast.makeText(this, "Phím Home được nhấn", Toast.LENGTH_SHORT).show();
    }
}

Bước 4: Cấu hình AndroidManifest.xml

<?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

Kết nối thiết bị, nhấn Run. Nhấn phím Home trên thiết bị -> Toast hiển thị "Phím Home được nhấn", TextView cập nhật nội dung khi quay lại app.

Giải thích onUserLeaveHint()

  • Được gọi khi Activity sắp chuyển sang background do hành động của người dùng (nhấn Home, mở notification, chuyển app...)
  • KHÔNG được gọi khi: màn hình tắt, system dialog hiện lên, hoặc gọi finish() tự chủ động
  • Thường dùng để: tạm dừng nhạc/video, lưu trạng thái tạm thời, ẩn keyboard

Phân biệt với các callback vòng đời khác

CallbackKhi nào gọi
onPause()Activity mất focus (luôn gọi trước onStop)
onStop()Activity hoàn toàn không nhìn thấy
onUserLeaveHint()Chỉ khi user chủ động rời (Home, recent apps)

Lưu ý

  • Không thể ngăn chặn hoặc hủy bỏ hành động nhấn Home
  • Không thể phân biệt chính xác Home vs Recent Apps vs Notification shade – tất cả đều gọi onUserLeaveHint()
  • Để phát hiện Back button: override onBackPressed()