編輯:關於 Android 程式設計
Service 與 Activity 最大的不同在於:它沒有界面,無法與用戶直接交互,也不能自行啟動,它是運行在後台的程序。當我們退出應用時,Activity 可能被銷毀,但只要 Service 仍處於啟動狀態,它就會繼續在後台運行。
什麼場景下需要它呢?最典型的就是播放音樂——我們常常希望一邊聽歌一邊做別的事情,此時如果依賴 Activity,退出播放界面音樂就斷了,所以必須把播放邏輯放到 Service 裡。再比如應用需要從網絡獲取數據,而不同時間點的數據各不相同,這時可以用 Service 在後台定時更新,而不必每次打開應用都重新拉取一次。
相比 Activity,Service 的生命周期要簡單得多。通過 startService 啟動的 Service,主要涉及三個回調:
首次啟動時,系統會先後調用 onCreate() 和 onStart();停止時執行 onDestroy()。這裡有一個容易忽略的細節:如果 Service 已經啟動,再次調用 startService 不會重新執行 onCreate(),而是直接走 onStart()。下面的實例會驗證這一點。
Service 在後台算出的數據,最終還是要呈現在前端的 Activity 上。而 Service 通常運行在獨立進程中,這就涉及跨進程通信(AIDL)的問題,本文暫不展開。
如果我們只是想拿到已啟動的 Service 實例並調用它的方法,可以使用 bindService 與 unbindService 這兩個 API,它們分別對應 Service 中的 onBind() 與 onUnbind() 回調。
第一步,新建一個 Android 工程,命名為 ServiceDemo。
第二步,修改 main.xml,放入四個按鈕:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/startservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="startService" />
<Button
android:id="@+id/stopservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="stopService" />
<Button
android:id="@+id/bindservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="bindService" />
<Button
android:id="@+id/unbindservice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="unbindService" />
</LinearLayout>
第三步,新建 MyService.java:
package com.tutor.servicedemo;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;
public class MyService extends Service {
private static final String TAG = "MyService";
// 供 onBind() 返回,Activity 側可借此拿到 Service 實例
private MyBinder mBinder = new MyBinder();
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "start IBinder~~~");
return mBinder;
}
@Override
public void onCreate() {
Log.e(TAG, "start onCreate~~~");
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
Log.e(TAG, "start onStart~~~");
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
Log.e(TAG, "start onDestroy~~~");
super.onDestroy();
}
@Override
public boolean onUnbind(Intent intent) {
Log.e(TAG, "start onUnbind~~~");
return super.onUnbind(intent);
}
/** 獲取當前系統時間 */
public String getSystemTime() {
Time t = new Time();
t.setToNow();
return t.toString();
}
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
}
第四步,修改 ServiceDemo.java:
package com.tutor.servicedemo;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ServiceDemo extends Activity implements OnClickListener {
private MyService mMyService;
private TextView mTextView;
private Button startServiceButton, stopServiceButton;
private Button bindServiceButton, unbindServiceButton;
private Context mContext;
// bindService / unbindService 都需要用到 ServiceConnection
private ServiceConnection mServiceConnection = new ServiceConnection() {
// 綁定成功後,讓 TextView 顯示 MyService 中 getSystemTime() 的返回值
public void onServiceConnected(ComponentName name, IBinder service) {
mMyService = ((MyService.MyBinder) service).getService();
mTextView.setText("I am from Service :" + mMyService.getSystemTime());
}
public void onServiceDisconnected(ComponentName name) { }
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupViews();
}
public void setupViews() {
mContext = ServiceDemo.this;
mTextView = (TextView) findViewById(R.id.text);
startServiceButton = (Button) findViewById(R.id.startservice);
stopServiceButton = (Button) findViewById(R.id.stopservice);
bindServiceButton = (Button) findViewById(R.id.bindservice);
unbindServiceButton = (Button) findViewById(R.id.unbindservice);
startServiceButton.setOnClickListener(this);
stopServiceButton.setOnClickListener(this);
bindServiceButton.setOnClickListener(this);
unbindServiceButton.setOnClickListener(this);
}
public void onClick(View v) {
Intent i = new Intent();
i.setClass(ServiceDemo.this, MyService.class);
if (v == startServiceButton) {
mContext.startService(i);
} else if (v == stopServiceButton) {
mContext.stopService(i);
} else if (v == bindServiceButton) {
mContext.bindService(i, mServiceConnection, BIND_AUTO_CREATE);
} else {
mContext.unbindService(mServiceConnection);
}
}
}
第五步,别忘了在 AndroidManifest.xml 中註冊 Service:
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.tutor.servicedemo"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<application>
<activity android:name=".ServiceDemo">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:exported="true" android:name=".MyService" />
</application>
</manifest>
第六步,運行工程,界面如下:

點擊 startService 按鈕,Logcat 中可以看到 onCreate() → onStart() 依次執行:

此時按 HOME 鍵進入 Settings → Applications → Running Services,可以看到新啟動的服務確實在運行:

點擊 stopService,Service 執行 onDestroy():

再次點擊 startService,然後點擊 bindService(實踐中通常是綁定一個已啟動的 Service),可以看到 Service 執行了 onBind(),同時 TextView 上的值也變成了 Service 返回的時間:

最後點擊 unbindService,Service 執行 onUnbind():

最常見的寫法是通過 Class 指定目標:
Intent i = new Intent(); i.setClass(ServiceDemo.this, MyService.class); mContext.startService(i);
但這種方式只能啟動與 Activity 位於同一個 package 內的 Service。如果目標 Service 屬於另一個應用該怎麼辦?這時需要用 setClassName(),第一個參數是 Service 所在應用的包名,第二個參數是 Service 的完整類名。
下面是一個打開 modem silent log 相關 Service 的實際例子,注意第一個參數就是 SilentLogService 所在應用在 AndroidManifest.xml 中聲明的 package 名:
Intent SvcIntent = new Intent();
SvcIntent.setClassName("com.sec.modem.settings",
"com.sec.modem.settings.cplogging.SilentLogService");
SvcIntent.putExtra("action", 2 /* = SilentLog.SILENT_LOG_START */);
startService(SvcIntent);
需要補充的是,從 Android 8.0(API 26)開始,後台啟動 Service 受到限制,長時間的後台任務應改用 startForegroundService 並展示通知,或直接使用 WorkManager、JobScheduler 等更合適的方案。
Android SpannableString 複合文本實戰
當需要在一個 TextView 中同時呈現不同顏色、字體大小、底線、刪除線、圖片或點擊事件時,SpannableString 是非常實用的工具。 常見 Span 前景色
Android 原生 org.json 實戰:JSON 的產生與解析
行動裝置與伺服器溝通,十次有九次靠 JSON。它結構扁平、可讀性高、解析成本低,幾乎成了 App 與後端之間的通用語言。網路上能撿到大量現成的 JSON 元件,但那些元件
Android Studio 多渠道路徑打包與工程定制實作(上)
同一份源碼要產出多個 apk,每個包的包名與圖示還不一樣——這種需求很常見,而 Android Studio 的 productFlavors 就是為它準備的。設定一次,
自定義 ViewGroup 打造多風格 SlidingMenu:測量、滑動與沖突處理全解析
用 HorizontalScrollView 做側滑菜單確實方便——它已經幫你解決了滑動與手勢處理。但滑動與事件沖突本身就是 Android 裡最該弄懂的知識點,一旦掌握