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

Android Background Music Service คืออะไร? การสร้างเพลงพื้นหลังใน Android

ภาพรวม

Service ใน Android คือคอมโพเนนต์ที่ทำงานในพื้นหลัง (Background) โดยไม่มี UI และยังคงทำงานต่อไปแม้ Activity จะถูกทำลายแล้วก็ตาม บทความนี้สาธิตการสร้าง Background Music Service เพื่อเล่นเพลงในพื้นหลัง

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

ในโค้ดด้านบน เราใช้ TextView เมื่อผู้ใช้คลิก จะเริ่ม/หยุด Music Service

ขั้นตอนที่ 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(MusicService.class)) {
                    text.setText("Stopped");
                    stopService(new Intent(MainActivity.this, MusicService.class));
                } else {
                    text.setText("Started");
                    startService(new Intent(MainActivity.this, MusicService.class));
                }
            }
        });
    }

    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/MusicService.java)

package com.example.andy.myapplication;

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

public class MusicService extends Service {
    MediaPlayer musicPlayer;

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

    @Override
    public void onCreate() {
        super.onCreate();
        // วางไฟล์เพลง abc.mp3 ในโฟลเดอร์ res/raw
        musicPlayer = MediaPlayer.create(this, R.raw.abc);
        musicPlayer.setLooping(false);
    }

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

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

ขั้นตอนที่ 4: ลงทะเบียน Service ใน 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=".MusicService"/>
    </application>
</manifest>

การทดสอบ

เชื่อมต่ออุปกรณ์ Android จริง ใน Android Studio คลิก Run เลือกอุปกรณ์ หน้าจอแรกจะแสดง "Start Service" คลิกเพื่อเริ่มเพลง คลิกอีกครั้งเพื่อหยุด

จุดสำคัญ

  • วางไฟล์เสียง (เช่น abc.mp3) ในโฟลเดอร์ res/raw/
  • ใช้ START_STICKY เพื่อให้ Service รีสตาร์ทอัตโนมัติหากระบบฆ่าซัก
  • จัดการ MediaPlayer อย่างถูกต้องใน onCreate/onDestroy เพื่อหลีกเลี่ยง Memory Leak