Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธี Override ปุ่ม Home ในแอป Android

ภาพรวม

ตัวอย่างนี้สาธิตการจับเหตุการณ์เมื่อผู้ใช้กดปุ่ม Home โดยใช้ onUserLeaveHint()

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio ไปที่ File → New Project กรอกข้อมูลที่จำเป็น

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (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"
    tools:context=".MainActivity">
    <TextView
        android:text="Press Home Button"
        android:textSize="16sp"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>
</RelativeLayout>

ขั้นตอนที่ 3: เขียนโค้ดหลัก (MainActivity.java)

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onUserLeaveHint() {
        Toast.makeText(getApplicationContext(), "Home Button is Pressed", Toast.LENGTH_SHORT).show();
        super.onUserLeaveHint();
    }
}

คำอธิบาย

  • onUserLeaveHint() เรียกเมื่อผู้ใช้กดปุ่ม Home หรือ Switch แอป
  • ไม่สามารถ ป้องกันไม่ให้ Home ทำงานได้ (เป็นปุ่มระบบ)
  • เหมาะสำหรับ: บันทึกสถานะ, หยุดเพลง, ปิดการเชื่อมต่อ ก่อนแอปไปพื้นหลัง
  • ต่างจาก onBackPressed() ที่สามารถ Override และบล็อกได้

ขั้นตอนที่ 4: 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>

การทดสอบ

รันแอป กดปุ่ม Home จะเห็น Toast "Home Button is Pressed" แสดงสั้นๆ ก่อนแอปยุบ

วิธี Override ปุ่ม Home ในแอป Android