編輯:關於 Android 開發
在 Android 開發中,一旦需要讓某些工作離開 Activity 的生命週期、在背景持續執行,Service 就是標配答案。Service 與 Activity 最根本的差別在於「前台與背景」的分工:Activity 負責使用者看得見的介面,Service 則在螢幕之外默默運轉。
啟動與停止 Service 的呼叫鏈相當清晰:
context.startService() → onCreate() → onStart() → Service running context.stopService() → onDestroy() → Service stopped
其中 onCreate() 適合進行服務的初始化工作,onStart() 則是真正讓服務開始運作的地方。以下用一個「點擊 start 播放音樂、點擊 stop 停止播放」的小範例,把整個流程走一遍。
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;
}
}
}
除了 Activity,別忘了在 AndroidManifest.xml 中把服務宣告出來,否則執行期會找不到元件:
<?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>
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 onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Start", Toast.LENGTH_LONG).show();
Log.i(TAG, "onStart");
player.start();
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stoped", Toast.LENGTH_LONG).show();
Log.i(TAG, "onDestroy");
player.stop();
}
}
這裡我們用 MediaPlayer 承載播放,在 onCreate 中建立並設定不重複播放,onStart 開始播放,onDestroy 則負責停止——資源的配置與釋放恰好對應,這是好習慣的起點。
<?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:id="@+id/buttonStop"
android:text="@string/stop"></Button>
</LinearLayout>
<?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>
把這個範例跑起來,你會看到服務的三個生命週期節點分別跳出 Toast 提示,並在 logcat 中留下紀錄。理解了這條最基礎的骨架,後續要擴充成音樂播放器、檔案下載器或資料同步器,都只是在同一副骨架上加肉而已。
Gradle 混淆與打包 JAR 的實戰入門:模組化 SDK 交付流程
本文為原創文章,轉載請注明出處。文末附有源碼下載位址。 開發 Android App 時經常會遇到三個需求:程式碼混淆、模組化拆分,以及把成果打包成 JAR 交給第三方。
資料結構入門:符號表是什麼,以及它為何重要
定義 符號表(Symbol Table)是一種儲存鍵值對的資料結構,只需支援兩個基本操作: 插入(put):把一組新的鍵值對存進表中。查找(get):依給定的鍵取出對應的
Android React Native 加載圖片資源的正確方式
Android React Native 加載圖片資源的正確方式 在先前探討 React Native 使用細節的文章中,曾提到圖片使用的問題,也提到無論用哪種方法都無法
把 Eclipse 專案搬進 Android Studio:直接匯入與間接轉換兩種做法
從 Eclipse 過渡到 Android Studio 時,舊專案總得想辦法帶過去。實務上有兩條路:一是讓 Android Studio 直接吃下 Eclipse 專案