การตรวจสอบสถานะแอป Android ว่าทำงานในพื้นหลังหรือไม่
ตัวอย่างนี้สาธิตวิธีการตรวจสอบว่าแอปพลิเคชัน Android กำลังทำงานอยู่ในโหมดพื้นหลัง (Background) หรือไม่ โดยใช้คลาส ActivityManager เพื่อดูสถานะกระบวนการของแอป
ขั้นตอนที่ 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"
android:padding="4dp"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textStyle="bold"
android:layout_centerInParent="true"
android:text="Checking if Android App is running in Background"/>
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ดหลัก (MainActivity.java)
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActivityManager;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Boolean appRunningBackground;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityManager.RunningAppProcessInfo runningAppProcessInfo = new ActivityManager.RunningAppProcessInfo();
ActivityManager.getMyMemoryState(runningAppProcessInfo);
appRunningBackground = runningAppProcessInfo.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
if (appRunningBackground) {
Toast.makeText(getApplicationContext(), "Your Android Application is Running in Background", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Your Android Application is not Running in Background", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPause() {
super.onPause();
Toast.makeText(getApplicationContext(), "Your Android Application is Running in Background", Toast.LENGTH_SHORT).show();
}
}
ขั้นตอนที่ 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>
การทดสอบ
เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ แล้วคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณ แล้วตรวจสอบหน้าจอว่าจะแสดงผลตามที่ต้องการ