編輯:關於 Android 程式設計
以前我總覺得四大元件裡的 Service 和 BroadcastReceiver 用得少,其實不然,只是因為它們比較抽象,總是默默無聞地在後台提供服務。
我寫了個 demo 測試了一下,一個著眼於生命週期,一個則示範綁定服務與解綁服務,用 MP3 播放來類比會比較形象。
下面是工程列表:

MainActivity.java:
package cn.edu.sjzc.fanyafeng.activity;
import android.app.Activity;
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 cn.edu.sjzc.fanyafeng.service.MyService;
import cn.edu.sjzc.fanyafeng.servicedemo.R;
public class MainActivity extends Activity implements OnClickListener {
private Button start, end, bind, unbind;
private static String TAG = "生命周期";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "onCreate方法執行");
initView();
}
private void initView() {
this.start = (Button) MainActivity.this.findViewById(R.id.start);
this.start.setOnClickListener(this);
this.end = (Button) MainActivity.this.findViewById(R.id.end);
this.end.setOnClickListener(this);
this.bind = (Button) MainActivity.this.findViewById(R.id.bind);
this.bind.setOnClickListener(this);
this.unbind = (Button) MainActivity.this.findViewById(R.id.unbind);
this.unbind.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,MyService.class);
switch (v.getId()) {
case R.id.start:
startService(intent);
break;
case R.id.end:
stopService(intent);
break;
case R.id.bind:
bindService(intent, conn, BIND_AUTO_CREATE);
break;
case R.id.unbind:
unbindService(conn);
break;
default:
break;
}
}
final ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
};}
MyService.java:
package cn.edu.sjzc.fanyafeng.service;
import cn.edu.sjzc.fanyafeng.servicedemo.R;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
private static String TAG = "生命周期";
private MediaPlayer mPlayer;
private MyBinder mBinder = new MyBinder();
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind()執行");
return mBinder;
}
@Override
public void onCreate() {
Log.i(TAG, "onCreate()執行");//第一個執行
mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.qimiaozhongdejiyi);
mPlayer.setLooping(true);
super.onCreate();
}
@Override
public void onDestroy() {
Log.i(TAG, "onDestroy()執行");//停止播放時執行
mPlayer.stop();
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand()執行");//第二個執行
mPlayer.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "onUnbind()執行");
return super.onUnbind(intent);
}
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
Log.i(TAG, "onStart()執行");//第三個執行
super.onStart(intent, startId);
}
public class MyBinder extends Binder{
MyService getService(){
return MyService.this;
}
}
}
佈局檔 activity_main.xml:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/unbind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/bind"
android:layout_alignBottom="@+id/bind"
android:layout_alignParentRight="true"
android:layout_marginRight="88dp"
android:text="解綁" />
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_toLeftOf="@+id/unbind"
android:text="開啟音樂播放" />
<Button
android:id="@+id/bind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/start"
android:layout_below="@+id/end"
android:layout_marginTop="22dp"
android:text="綁定Service" />
<Button
android:id="@+id/end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/start"
android:layout_below="@+id/start"
android:layout_marginTop="16dp"
android:text="停止音樂播放服務" />
</RelativeLayout>
最容易被忽略、卻至關重要的一步是別忘了在清單檔中註冊 Service——Android 四大元件都需要註冊才能生效。
以下是 demo 的運行畫面:


如此一來,程式就能在後台持續運行了。
最後附上程式日誌,幫助大家理解 Service 的生命週期:

從日誌可以清楚看到,startService 會依序觸發 onCreate、onStartCommand(以及已被棄用的 onStart);而透過 bindService 綁定則會走到 onBind,解綁時觸發 onUnbind。理解這套順序,就能更從容地駕馭後台服務了。
Android 直播推流學習筆記:逐段拆解 spydroid 的 RTSP 實現
第一部:先看整體結構 本文以 spydroid 的源碼為主線,一步步梳理 Android 端 RTSP 推流的實現方式。spydroid 採用 RTSP 協議,目前支援
搞懂 Android 控件的寬高,以及 layout_gravity 與 gravity 的差別
從 layout_width/height 談起 寫法一 結果跟預期不一樣: 寫法二 這個就符合預期了: 為什麼只是換了個寫法,結果就差那麼多?答案藏在 Andr
Android 動態載入 APK 實作:Fragment 與 Activity 兩種做法
起因是專案膨脹到編譯不過——Android 對單一應用中的方法數量有上限(就是知名的 65536 或 DEX 64K 限制)。於是開始研究能否把某些模塊做成獨立 APK,
Android AIDL 入門:跨進程通信的介面定義與使用
前言 AIDL 是 Android Interface Definition Language 的縮寫,用於定義跨進程通信的介面。Android 中每個應用通常運行於自己