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

Android Service 入門 Demo:startService 與 bindService 完整示例

編輯:關於 Android 程式設計

Service 是 Android 四大元件中相當重要的一塊。網路上現成的範例不少,看起來都不難,但要真正用得順手,還是得自己動手寫一遍。

本文以程式碼為主,不多談理論。以下範例參考網路上的寫法,原帖程式碼有幾處不完整,我做了修正。

AndroidManifest.xml

<intent-filter>
  <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- 註冊 Service -->
<service android:name="LocalService">
  <intent-filter></intent-filter>
</service>

ServiceMainActivity.java

package cn.fansunion.service;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ServiceMainActivity extends Activity {
  private Button startBtn, stopBtn, bindBtn, unBindBtn;
  private static final String TAG = "MainActivity";
  private LocalService myService;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.service);
    startBtn = (Button) findViewById(R.id.start);
    stopBtn = (Button) findViewById(R.id.stop);
    bindBtn = (Button) findViewById(R.id.bind);
    unBindBtn = (Button) findViewById(R.id.unbind);
    startBtn.setOnClickListener(new MyOnClickListener());
    stopBtn.setOnClickListener(new MyOnClickListener());
    bindBtn.setOnClickListener(new MyOnClickListener());
    unBindBtn.setOnClickListener(new MyOnClickListener());
  }

  class MyOnClickListener implements OnClickListener {
    @Override public void onClick(View v) {
      Intent intent = new Intent();
      intent.setClass(ServiceMainActivity.this, LocalService.class);
      switch (v.getId()) {
        case R.id.start:
          startService(intent);
          toast("startService");
          break;
        case R.id.stop:
          stopService(intent);
          toast("stopService");
          break;
        case R.id.bind:
          bindService(intent, conn, Service.BIND_AUTO_CREATE);
          toast("bindService");
          break;
        case R.id.unbind:
          unbindService(conn);
          toast("unbindService");
          break;
      }
    }
  }

  private void toast(final String tip) {
    runOnUiThread(new Runnable() {
      @Override public void run() {
        Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_SHORT).show();
      }
    });
  }

  private ServiceConnection conn = new ServiceConnection() {
    @Override public void onServiceConnected(ComponentName name, IBinder service) {
      Log.e(TAG, "連接成功");
      // 連線建立後,取得與 Service 互動的物件
      myService = ((LocalService.LocalBinder) service).getService();
    }
    @Override public void onServiceDisconnected(ComponentName name) {
      Log.e(TAG, "斷開連接");
      myService = null;
    }
  };
}

LocalService.java

package cn.fansunion.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class LocalService extends Service {
  private static final String TAG = "MyService";
  private final IBinder myBinder = new LocalBinder();

  // 建立 Service 時呼叫(startService 或 bindService 首次觸發)
  @Override public void onCreate() {
    super.onCreate();
    Log.e(TAG, "onCreate()");
  }

  @Override public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e(TAG, "onStartCommand()");
    return START_STICKY;
  }

  @Override public IBinder onBind(Intent intent) {
    Log.e(TAG, "onBind()");
    return myBinder;
  }

  @Override public void onDestroy() {
    super.onDestroy();
    Log.e(TAG, "onDestroy()");
  }

  // 提供給客戶端存取
  public class LocalBinder extends Binder {
    LocalService getService() {
      return LocalService.this;
    }
  }
}

service.xml 版面檔

<?xml version="1.0" encoding="utf-8"?>
<linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent"
  android:orientation="vertical" xmlns:android="https://schemas.android.com/apk/res/android">
  <button android:id="@+id/start" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="啟動Service" />
  <button android:id="@+id/stop" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="停止Service" />
  <button android:id="@+id/bind" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="綁定Service" />
  <button android:id="@+id/unbind" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="解除Service" />
</linearlayout>

執行結果

踩過的坑:Toast 不顯示

原範例中 Toast 完全沒弹出來。在論壇上有人說可能是被手機遮蔽了,但我更傾向於呼叫方式有問題——在 Service 的 onCreate 裡直接呼叫 Toast,本來就不是合適的做法:

public void onCreate() {
  Log.e(TAG, "onCreate()");
  // Toast.makeText(this, "onCreate()", Toast.LENGTH_SHORT).show();
}

最後參考網友的作法,切到 UI 執行緒再彈:

private void toast(final String tip) {
  runOnUiThread(new Runnable() {
    @Override public void run() {
      Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_SHORT).show();
    }
  });
}

順帶一提,我在新版 API 上實作時把已棄用的 onStart() 換成了 onStartCommand(),並回傳 START_STICKY,行為更明確。

這件事也提醒我:再漂亮的網路範例,還是要自己跑一遍才算數。何況那份貼子是 2011 年的,實在很老了。

參考資料

Android 中 Service 元件詳解
Android Toast 顯示不出來

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