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

Android Background Music Service là gì? Hướng dẫn tạo dịch vụ phát nhạc nền

Khái niệm Service trong Android

Service là thành phần chạy nền (background) thực hiện các tác vụ lâu dài mà không cần giao diện người dùng (UI). Service tiếp tục chạy ngay cả khi Activity bị hủy.

Đặc điểm chính:

  • Không có UI
  • Chạy độc lập với vòng đời Activity
  • Phù hợp cho: phát nhạc, tải file, đồng bộ dữ liệu, GPS tracking...

Ví dụ: Tạo Music Service chạy nền

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

Android Studio → File → New Project → Empty Activity.

Bước 2: Layout (res/layout/activity_main.xml)

Một TextView đóng vai trò nút bấm Start/Stop:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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" />

</androidx.constraintlayout.widget.ConstraintLayout>

Bước 3: MainActivity.java - Điều khiển Service

package com.example.andy.myapplication;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
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;
    }
}

Bước 4: Tạo 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 {
    private MediaPlayer mediaPlayer;

    @Override
    public IBinder onBind(Intent intent) {
        return null; // Không cho binding
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // Chuẩn bị file nhạc trong res/raw/abc.mp3
        mediaPlayer = MediaPlayer.create(this, R.raw.abc);
        mediaPlayer.setLooping(false); // false = phát một lần, true = lặp lại
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Music Service started", Toast.LENGTH_LONG).show();
        mediaPlayer.start();
        return START_STICKY; // Khởi động lại nếu bị hệ thống kill
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        Toast.makeText(this, "Music Service destroyed", Toast.LENGTH_LONG).show();
    }
}

Bước 5: Manifest (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>

Chuẩn bị tài nguyên

Tạo thư mục res/raw/ (chuột phải res → New → Android Resource Directory → Type: raw) và đặt file nhạc abc.mp3 vào đó.

Chạy ứng dụng

  1. Nhấn TextView "Start Service" → nhạc phát, text đổi thành "Started"
  2. Nhấn lại → nhạc dừng, text đổi thành "Stopped"
  3. Thoát app (Home) → nhạc vẫn phát do START_STICKY
Lưu ý: Từ Android 8.0 (API 26), Service nền bị hạn chế. Để phát nhạc ổn định, hãy dùng Foreground Service với Notification (xem bài tiếp theo).