編輯:關於 Android 程式設計
Service 是 Android 四大元件中相當重要的一塊。網路上現成的範例不少,看起來都不難,但要真正用得順手,還是得自己動手寫一遍。
本文以程式碼為主,不多談理論。以下範例參考網路上的寫法,原帖程式碼有幾處不完整,我做了修正。
<intent-filter> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <!-- 註冊 Service --> <service android:name="LocalService"> <intent-filter></intent-filter> </service>
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;
}
};
}
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;
}
}
}
<?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 完全沒弹出來。在論壇上有人說可能是被手機遮蔽了,但我更傾向於呼叫方式有問題——在 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 顯示不出來
《從 JAVA 到 Android》JAVA 篇之打好基礎:認識 JAVA
本篇將帶你打好 Java 的基礎,內容涵蓋:標識符與關鍵字、基本資料型別、常量與變數、運算子、資料型別轉換,以及註解與程式碼撰寫規範。 1、標識符與關鍵字 通俗地說,標識
Android AlertDialog 五種對話框完整實戰:確認、單選、多選、列表與自定義
幾乎每一款 App 都離不開對話框:刪除前的二次確認、性別選擇、興趣勾選、部門挑選,甚至是帶輸入框與圖片的「自定義彈窗」。本文用一個可直接跑起來的示例,把 AlertDi
Android 兩數相乘範例:Intent 傳值、跨頁跳轉與 Options Menu 一次學會
開發環境:Android 4.1 這個看起來很單純的計算機,其實包辦了 Android 入門階段最該練會的三件事:Intent 帶值跳頁、跨 Activity 取回資料
Android Touch 事件分發機制全解析:dispatch、intercept 與 onTouch 的順序
在 Android 的 Touch 分發裡,經常看到 ACTION_DOWN → ACTION_MOVE → ACTION_UP 這樣的流程。如果不了解它究竟怎麼傳遞,一