編輯:關於 Android 程式設計
Service 是 Android 四大元件之一,適合執行不需要使用者互動、且必須在背景持續運作的任務。本文先釐清它的生命週期,再透過一個可直接運行的範例把啟動與綁定兩種用法講明白。
onCreate()(若需要)→ onStart()。多次呼叫 startService 會觸發多次 onStart,但不會建立多個 Service 實例,只需一次 stop。它會持續運行,直到被 stopService、呼叫自身 stopSelf(),或系統資源不足時被回收。onCreate(),不會呼叫 onStart;此時一旦解除綁定,系統即可回收該 Service(連線銷毀導致解除,解除後便銷毀)。onCreate 與 onStart 都會被呼叫。onDestroy();若沒有啟動、只是不再有綁定,則會隱式呼叫。值得注意的是,在有 bind 的情況下,stopService() 並不會生效。以下範例某些細節需搭配 logcat 觀察:
package jtapp.myservicesamples;
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.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class AcMain extends Activity implements OnClickListener {
private static final String TAG = "AcMain";
private Button btnStart, btnStop, btnBind, btnExit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findView();
}
private void findView() {
btnStart = (Button) findViewById(R.id.Start);
btnStop = (Button) findViewById(R.id.Stop);
btnBind = (Button) findViewById(R.id.Bind);
btnExit = (Button) findViewById(R.id.Exit);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
btnBind.setOnClickListener(this);
btnExit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent("jtapp.myservicesamples.myservice");
switch (v.getId()) {
case R.id.Start:
startService(intent);
Toast.makeText(this,
"myservice running " + MyService.msec / 1000.0 + "s.",
Toast.LENGTH_LONG).show();
break;
case R.id.Stop:
stopService(intent);
Toast.makeText(this,
"myservice running " + MyService.msec / 1000.0 + "s.",
Toast.LENGTH_LONG).show();
break;
case R.id.Bind:
bindService(intent, sc, Context.BIND_AUTO_CREATE);
break;
case R.id.Exit:
this.finish();
break;
}
}
private MyService serviceBinder;
private ServiceConnection sc = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "in onServiceDisconnected");
serviceBinder = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d(TAG, "in onServiceConnected");
serviceBinder = ((MyService.MyBinder) service).getService();
}
};
@Override
protected void onDestroy() {
super.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">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<Button android:text="Start MyService" android:id="@+id/Start"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:text="Stop MyService" android:id="@+id/Stop"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:text="Bind MyService" android:id="@+id/Bind"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button android:text="Exit AcMain" android:id="@+id/Exit"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>
package jtapp.myservicesamples;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
private static final String TAG = "MyService";
public static long msec = 0;
private boolean bThreadRunning = true;
private final IBinder binder = new MyBinder();
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public void onCreate() {
new Thread(new Runnable() {
@Override
public void run() {
while (bThreadRunning) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
Log.i(TAG, "myservice running " + (msec += 100) + "ms.");
}
}
}).start();
}
@Override
public void onDestroy() {
bThreadRunning = false;
super.onDestroy();
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="jtapp.myservicesamples" android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:debuggable="true">
<activity android:name=".AcMain" 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:name="MyService">
<intent-filter>
<action android:name="jtapp.myservicesamples.myservice"></action>
</intent-filter>
</service>
</application>
</manifest>
把這三部分接起來,你就能透過四顆按鈕分別測試 startService、stopService 與 bindService,並在 logcat 觀察 Service 的實際生命週期。理解「啟動」與「綁定」的差異,是掌握 Service 的關鍵。
Android WiFi 開發教學:狀態常數、權限與完整控制範例
WiFi 相關開發可以拆成三件事:知道當前狀態、拿到操作權限、呼叫 WifiManager 的方法。 一、WiFi 網卡的狀態常數 狀態資訊以整數常數形式定義在 and
Android 屏幕適配五種方案詳解:從像素密度到權重布局
什麼是屏幕適配 所謂適配,就是讓同一個應用在不同的手機上呈現一致的視覺效果。動手之前,第一步永遠是先確認當前設備屬於哪一檔像素密度(xhdpi、hdpi、mdpi 等)。
Android 源碼入門(三):AOSP 源碼同步、編譯與 Samba 刷機環境搭建
最近事情比較多,既要打理博客,又要維護視頻和公眾號,一直沒能靜下心來梳理源碼的入門脈絡。今天就來聊聊源碼的一套完整玩法,感興趣的朋友一起學習。 參考資料:官方教程 ht
Android DatePicker 的使用及自訂主題詳解
在 Android 4.n 版本中,DatePickerDialog 存在一個惱人的問題:取消選擇日期時會調用一次 onDateSet,而確認選擇日期時卻會調用兩次 on