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

Android 實作開機自動啟動 Service 的範例

編輯:關於 Android 程式設計

最近把 HevSocks5Client 移植到 Android 上。在補上 signalfd 與 timerfd 相關的系統呼叫支援之後,就能直接用 NDK 編譯出可執行檔了。不過純 native executable 在 Android 系統上終究不太方便使用,還是包成一個 apk 比較妥當——這次先只做一個沒有 Activity、開機自動啟動的 Service。

以 JNI 載入 native 程式

Java 呼叫 native 程式,我選擇 JNI 方式:直接在 JNI_OnLoad 中建立執行緒去跑原本的 main 函式。

...
#if defined(ANDROID)
#include <jni.h>
#include <pthread.h>
#endif

int
main (int argc, char *argv[])
{
    ...
}

#if defined(ANDROID)
static void *
thread_handler (void *data)
{
    main (0, NULL);
    return NULL;
}

jint
JNI_OnLoad (JavaVM *vm, void *reserved)
{
    pthread_t thread;
    pthread_create (&thread, NULL, thread_handler, NULL);
    return JNI_VERSION_1_4;
}
#endif

Android 服務

服務的職責很單純:載入 JNI 介面的 hev-socks5-client 函式庫,讓服務跑起來。

package hev.socks5;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MainService extends Service {

    static {
        System.loadLibrary("hev-socks5-client");
    }

    public IBinder onBind(Intent intent) {
        return null;
    }
}

BroadcastReceiver

ServiceReceiver 負責監聽系統的 BOOT_COMPLETED 事件,用來實現開機自動啟動:

package hev.socks5;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class ServiceReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            Intent i = new Intent(context, MainService.class);
            context.startService(i);
        }
    }
}

AndroidManifest.xml

最後在 manifest 中註冊 Service 與 Receiver,並加上網路與開機完成權限:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="hev.socks5"
    android:versionCode="1"
    android:versionName="1.0">

    <application android:label="@string/app_name" >
        <service android:name=".MainService">
            <intent-filter>
                <action android:name="hev.socks5.MainService" />
            </intent-filter>
        </service>

        <receiver android:enabled="true" android:name=".ServiceReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>

實務注意事項

這個做法在 Android 2.3.3 及之前版本有效。之後的版本有一個行為變更:如果應用在安裝後從未被打開過,Broadcast Receiver 將收不到 boot completed 廣播。解法是先手動啟動一次 Service:

am startservice hev.socks5/.MainService

另外還有兩點值得留意。其一,從 Android 8.0 開始,背景應用無法用 startService() 啟動背景服務,必須改用 startForegroundService() 並在 5 秒內呼叫 startForeground() 顯示常駐通知,否則會收到 ANR 或 RemoteServiceException。其二,從 Android 3.1 起,App 若被使用者強制停止或長時間未啟動,系統會將其標記為 stopped 狀態,直到使用者再次明確開啟才會接收廣播——這是「安裝後沒開過就收不到開機廣播」的根本原因。若要做真正的常駐背景工作,WorkManager 加上適當的約束條件,會比裸的 Service 更可靠。

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