Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Service 服務實例教學

編輯:Android 開發實例

在 Android 開發中,當需要建立於後台運行的程式時,就要使用到 Service。Service 可分為無限生命與有限生命兩種。特別需要注意的是,Service 與 Activity 是不同的(簡單理解就是後台與前台的差別)。若要使用 Service,需呼叫 startService(),進而觸發 Service 中的 onCreate() 與 onStart() 方法來啟動後台服務。

Service 的生命週期

啟動一個 Service 的流程:

context.startService() -> onCreate() -> onStart() -> Service running

其中 onCreate() 可進行服務的初始化工作,onStart() 則負責啟動服務。

停止一個 Service 的流程:

context.stopService() -> onDestroy() -> Service stop

接下來的實例是一個利用後台服務播放音樂的小範例:點擊 start 執行服務,點擊 stop 停止服務。

一、Activity:ServiceDemo.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;
        }
    }
}

二、在 Manifest 中聲明服務

<?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 onDestroy() {
        Toast.makeText(this, "My Service Stoped", Toast.LENGTH_LONG).show();
        Log.i(TAG, "onDestroy");
        player.stop();
    }

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

四、版面與字串資源

layout 資料夾中的 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:text="@string/stop" android:id="@+id/buttonStop"></Button>
</LinearLayout>

values 資料夾中的 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>

透過這個範例,你便能掌握 Android Service 的建立、啟動、停止以及生命週期各方法的呼叫時機,是理解後台服務運作的絕佳起點。

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