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

Android 四大元件之 Service 篇

編輯:關於 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。理解這套順序,就能更從容地駕馭後台服務了。

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