ภาพรวม
ตัวอย่างนี้แสดงวิธีตรวจสอบสถานะแอปพลิเคชันว่าอยู่ Foreground หรือ Background โดยใช้ ActivityManager (หมายเหตุ: วิธีนี้เหมาะสำหรับ API เก่า สำหรับ API ใหม่แนะนำให้ใช้ ProcessLifecycleOwner หรือ Lifecycle Observer)
ขั้นตอนการสร้าง
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project และกรอกข้อมูลที่จำเป็น
ขั้นตอนที่ 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp" />
</LinearLayout>
ขั้นตอนที่ 3: เขียนโค้ดหลัก (src/MainActivity.java)
package com.example.myapplication;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends FragmentActivity {
TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
if (!isApplicationBroughtToBackground()) {
textView.setText("Application is foreground");
} else {
textView.setText("Application is background");
}
}
private boolean isApplicationBroughtToBackground() {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(getPackageName())) {
return true; // อยู่ Background
}
}
return false; // อยู่ Foreground
}
}
หมายเหตุสำคัญ
- เมธอด
getRunningTasks()ถูก Deprecated ตั้งแต่ API 21 (Lollipop) - สำหรับแอปสมัยใหม่ ควรใช้ ProcessLifecycleOwner จาก Architecture Components หรือ Lifecycle Observer
- ตัวอย่างนี้เหมาะสำหรับการเรียนรู้หลักการพื้นฐานเท่านั้น
วิธีแนะนำสำหรับ API ใหม่
// ใช้ ProcessLifecycleOwner
ProcessLifecycleOwner.get().getLifecycle().addObserver(new DefaultLifecycleObserver() {
@Override
public void onStop(LifecycleOwner owner) {
// App ไป Background
}
@Override
public void onStart(LifecycleOwner owner) {
// App กลับม Foreground
}
});