|
@@ -0,0 +1,76 @@
|
|
|
+package com.zedu.launcher.daemon;
|
|
|
+
|
|
|
+import android.content.Intent;
|
|
|
+import android.os.IBinder;
|
|
|
+
|
|
|
+import com.blankj.utilcode.util.LogUtils;
|
|
|
+import com.xdandroid.hellodaemon.AbsWorkService;
|
|
|
+import com.zedu.launcher.socket.MyWebSocketServer;
|
|
|
+
|
|
|
+import java.util.concurrent.TimeUnit;
|
|
|
+
|
|
|
+import io.reactivex.Observable;
|
|
|
+import io.reactivex.disposables.Disposable;
|
|
|
+
|
|
|
+public class DaemonService extends AbsWorkService {
|
|
|
+
|
|
|
+ //是否 任务完成, 不再需要服务运行?
|
|
|
+ public static boolean sShouldStopService;
|
|
|
+
|
|
|
+ public static Disposable sDisposable;
|
|
|
+
|
|
|
+ public static void stopService() {
|
|
|
+ LogUtils.d("服务停止");
|
|
|
+ //我们现在不再需要服务运行了, 将标志位置为 true
|
|
|
+ sShouldStopService = true;
|
|
|
+ //取消对任务的订阅
|
|
|
+ if (sDisposable != null) {
|
|
|
+ sDisposable.dispose();
|
|
|
+ }
|
|
|
+ //取消 Job / Alarm / Subscription
|
|
|
+ cancelJobAlarmSub();
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public Boolean isWorkRunning(Intent intent, int flags, int startId) {
|
|
|
+ //若还没有取消订阅, 就说明任务仍在运行.
|
|
|
+ return sDisposable != null && !sDisposable.isDisposed();
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public IBinder onBind(Intent intent, Void v) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void startWork(Intent intent, int flags, int startId) {
|
|
|
+ LogUtils.d("服务开始:检查磁盘中是否有上次销毁时保存的数据");
|
|
|
+ sDisposable = Observable.interval(5, TimeUnit.SECONDS)
|
|
|
+ //取消任务时取消定时唤醒
|
|
|
+ .doOnDispose(() -> {
|
|
|
+ LogUtils.d("取消任务");
|
|
|
+ cancelJobAlarmSub();
|
|
|
+ }).subscribe(count -> {
|
|
|
+ // 2、每隔60秒,更新设备信息
|
|
|
+ if (count > 0 && count % 10 == 0) {
|
|
|
+ MyWebSocketServer.tryBroadcast("keepSelfLive");
|
|
|
+ }
|
|
|
+ }, throwable -> LogUtils.d(throwable.getMessage()));
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void stopWork(Intent intent, int flags, int startId) {
|
|
|
+ LogUtils.d("服务结束");
|
|
|
+ stopService();
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public Boolean shouldStopService(Intent intent, int flags, int startId) {
|
|
|
+ return sShouldStopService;
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void onServiceKilled(Intent rootIntent) {
|
|
|
+ LogUtils.d("服务关闭");
|
|
|
+ }
|
|
|
+}
|