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

วิธีตรวจสอบว่า Service กำลังทำงานอยู่ใน Android

ภาพรวม

บทความนี้สาธิตวิธีตรวจสอบว่า Service เฉพาะเจาะจงกำลังทำงานอยู่หรือไม่ใน Android โดยใช้ ActivityManager.getRunningServices()

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

เปิด Android Studio ไปที่ File → New Project กรอกรายละเอียดที่จำเป็นทั้งหมดเพื่อสร้างโปรเจกต์ใหม่

ขั้นตอนที่ 2: จัดทำ Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Service"
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

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

package com.example.andy.myapplication;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView text = findViewById(R.id.text);

        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isMyServiceRunning(CheckService.class)) {
                    text.setText("Stopped");
                    stopService(new Intent(MainActivity.this, CheckService.class));
                } else {
                    text.setText("Started");
                    startService(new Intent(MainActivity.this, CheckService.class));
                }
            }
        });
    }

    // เมธอดตรวจสอบว่า Service กำลังทำงานอยู่
    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}

สร้าง Service ทั่วไป (src/CheckService.java)

package com.example.andy.myapplication;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class CheckService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service destroyed", Toast.LENGTH_LONG).show();
    }
}

โค้ดสำคัญสำหรับตรวจสอบ Service

// เมธอดตรวจสอบ
private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

// การเรียกใช้
isMyServiceRunning(YourService.class)

ขั้นตอนที่ 4: ลงทะเบียนใน AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.andy.myapplication">
    <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>
        <service android:name=".CheckService"/>
    </application>
</manifest>

การทดสอบ

รันแอป คลิก TextView เพื่อเริ่ม/หยุด Service ข้อความจะเปลี่ยนตามสถานะของ Service

ข้อควรระวัง

  • getRunningServices() ต้องการสิทธิ์ GET_TASKS ในบางเวอร์ชัน Android
  • Android 8.0+ จำกัดการเข้าถึงข้อมูล Service ของแอปอื่น
  • วิธีนี้เหมาะสำหรับตรวจสอบ Service ของแอปตัวเองเท่านั้น

ทางเลือกอื่น

สำหรับ Android ใหม่ๆ ควรพิจารณาใช้ JobScheduler, WorkManager หรือ Foreground Service แทน เพื่อความเข้ากันได้และประสิทธิภาพที่ดีกว่า