在 Service 中宣告 static boolean isThreadRunning,啟動執行緒前檢查旗標,結束時重設,避免重複啟動導致相機等資源衝突。
public class MyService extends Service {
private static boolean isThreadRunning = false;
private Thread workerThread;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (isThreadRunning) return START_STICKY; // 已在運行
isThreadRunning = true;
workerThread = new Thread(() -> {
try {
// 執行緒主體:相機預覽、資料處理等
while (isThreadRunning) {
// 工作迴圈
}
} finally {
isThreadRunning = false; // 確保重設
}
});
workerThread.start();
return START_STICKY;
}
@Override
public void onDestroy() {
isThreadRunning = false; // 通知執行緒結束
if (workerThread != null) workerThread.interrupt();
super.onDestroy();
}
}
static 確保旗標跨 Service 實例共享(系統可能重建 Service)。isThreadRunning 優雅退出。onDestroy 中設為 false 並 interrupt 執行緒。FileLock 或系統級鎖。