Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Service 完整實例:用背景服務播放音樂

編輯:關於 Android 開發

在 Android 開發中,一旦需要讓某些工作離開 Activity 的生命週期、在背景持續執行,Service 就是標配答案。Service 與 Activity 最根本的差別在於「前台與背景」的分工:Activity 負責使用者看得見的介面,Service 則在螢幕之外默默運轉。

啟動與停止 Service 的呼叫鏈相當清晰:

context.startService() → onCreate() → onStart() → Service running
context.stopService()  → onDestroy() → Service stopped

其中 onCreate() 適合進行服務的初始化工作,onStart() 則是真正讓服務開始運作的地方。以下用一個「點擊 start 播放音樂、點擊 stop 停止播放」的小範例,把整個流程走一遍。

Activity 端:ServicesDemo.java

package com.android.myservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ServiceDemo extends Activity implements OnClickListener {
    private static final String TAG = "ServiceDemo";
    Button buttonStart, buttonStop;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        buttonStart = (Button) findViewById(R.id.buttonStart);
        buttonStop = (Button) findViewById(R.id.buttonStop);

        buttonStart.setOnClickListener(this);
        buttonStop.setOnClickListener(this);
    }

    public void onClick(View src) {
        switch (src.getId()) {
            case R.id.buttonStart:
                Log.i(TAG, "onClick: starting service");
                startService(new Intent(this, MyService.class));
                break;
            case R.id.buttonStop:
                Log.i(TAG, "onClick: stopping service");
                stopService(new Intent(this, MyService.class));
                break;
        }
    }
}

除了 Activity,別忘了在 AndroidManifest.xml 中把服務宣告出來,否則執行期會找不到元件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.android.myservice">
    <application android:label="@string/app_name">
        <activity android:name=".ServiceDemo" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:enabled="true" android:name=".MyService" />
    </application>
</manifest>

Service 端:MyService.java

package com.android.myservice;

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

public class MyService extends Service {
    private static final String TAG = "MyService";
    MediaPlayer player;

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

    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service created", Toast.LENGTH_LONG).show();
        Log.i(TAG, "onCreate");
        player = MediaPlayer.create(this, R.raw.braincandy);
        player.setLooping(false);
    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Start", Toast.LENGTH_LONG).show();
        Log.i(TAG, "onStart");
        player.start();
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stoped", Toast.LENGTH_LONG).show();
        Log.i(TAG, "onDestroy");
        player.stop();
    }
}

這裡我們用 MediaPlayer 承載播放,在 onCreate 中建立並設定不重複播放,onStart 開始播放,onDestroy 則負責停止——資源的配置與釋放恰好對應,這是好習慣的起點。

版面:main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/services_demo"
        android:gravity="center"
        android:textSize="20sp"
        android:padding="20dp" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/buttonStart"
        android:text="@string/start"></Button>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/buttonStop"
        android:text="@string/stop"></Button>
</LinearLayout>

字串資源:strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="start">Start</string>
    <string name="stop">Stop</string>
    <string name="services_demo">Service Demo</string>
</resources>

把這個範例跑起來,你會看到服務的三個生命週期節點分別跳出 Toast 提示,並在 logcat 中留下紀錄。理解了這條最基礎的骨架,後續要擴充成音樂播放器、檔案下載器或資料同步器,都只是在同一副骨架上加肉而已。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved