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

Cách kiểm tra ứng dụng Android đang chạy nền (background) bằng Kotlin

Ví dụ này minh họa cách kiểm tra xem ứng dụng Android có đang chạy trong nền (background) hay không sử dụng Kotlin.

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

Trong Android Studio, chọn File → New Project và điền đầy đủ thông tin để tạo dự án mới.

Bước 2: Cấu hình layout chính (activity_main.xml)

Thêm mã sau vào res/layout/activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Checking if Android Application is running in Background"
        android:textAlignment="center"
        android:textColor="@android:color/holo_red_light"
        android:textSize="24sp"
        android:textStyle="bold" />
</RelativeLayout>

Bước 3: Viết mã MainActivity.kt

Thêm mã sau vào src/MainActivity.kt:

import android.app.ActivityManager
import android.app.ActivityManager.RunningAppProcessInfo
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    var appRunningBackground: Boolean = false
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        
        val runningAppProcessInfo = RunningAppProcessInfo()
        ActivityManager.getMyMemoryState(runningAppProcessInfo)
        
        appRunningBackground = runningAppProcessInfo.importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND
        
        if (appRunningBackground) {
            Toast.makeText(applicationContext, "Your Android Application is Running in Background", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(applicationContext, "Your Android Application is not Running in Background", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onPause() {
        super.onPause()
        Toast.makeText(applicationContext, "Your Android Application is Running in Background", 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="com.example.q11">
    <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>
                
                
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị Android thực với máy tính. Từ Android Studio, mở file activity và nhấn biểu tượng Run trên thanh công cụ. Chọn thiết bị di động và kiểm tra màn hình hiển thị.

Lưu ý quan trọng: Cách dùng ActivityManager.getMyMemoryState() và RunningAppProcessInfo này đã cũ và không tin cậy trên Android hiện đại (API 26+). Hệ thống hạn chế quyền truy cập thông tin tiến trình của ứng dụng khác.

Cách hiện đại: Sử dụng ProcessLifecycleOwner từ Lifecycle (AndroidX) hoặc triển khai Application.ActivityLifecycleCallbacks để tự theo dõi trạng thái foreground/background của chính ứng dụng mình.