package com.aoleyun.sn.service; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.BatteryManager; import android.os.Build; import android.os.IBinder; import android.os.SystemClock; import android.provider.Settings; import android.text.TextUtils; import android.text.format.Formatter; import android.util.Log; import androidx.annotation.Nullable; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.amap.api.location.AMapLocationClient; import com.aoleyun.sn.bean.BaseResponse; import com.aoleyun.sn.comm.CommonConfig; import com.aoleyun.sn.comm.PackageNames; import com.aoleyun.sn.network.api.newapi.SendScreenStatusApi; import com.aoleyun.sn.rlog.LogDBManager; import com.aoleyun.sn.service.main.MainService; import com.arialyy.annotations.Download; import com.arialyy.aria.core.Aria; import com.arialyy.aria.core.download.DownloadEntity; import com.arialyy.aria.core.task.DownloadTask; import com.aoleyun.sn.BuildConfig; import com.aoleyun.sn.manager.AmapManager; import com.aoleyun.sn.network.HTTPInterface; import com.aoleyun.sn.network.api.newapi.GetLockStateApi; import com.aoleyun.sn.receiver.BootReceiver; import com.aoleyun.sn.receiver.NewAppReceiver; import com.aoleyun.sn.utils.JGYUtils; import com.aoleyun.sn.utils.SPUtils; import com.aoleyun.sn.utils.XAPKUtils; import com.aoleyun.sn.KeepAliveConnection; import com.aoleyun.sn.base.BaseApplication; import com.aoleyun.sn.network.NetInterfaceManager; import com.aoleyun.sn.utils.ApkUtils; import com.aoleyun.sn.utils.ServiceAliveUtils; import com.aoleyun.sn.utils.ToastUtil; import com.aoleyun.sn.utils.Utils; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import okhttp3.ResponseBody; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * 守护进程 双进程通讯 * * @author LiGuangMin * @time Created by 2018/8/17 11:27 */ public class GuardService extends Service { private final static String TAG = GuardService.class.getSimpleName(); private ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { Log.w(TAG, "GuardService:建立链接"); boolean isServiceRunning = ServiceAliveUtils.isServiceAlive(GuardService.this, StepService.class.getName()); if (!isServiceRunning) { startService(new Intent(GuardService.this, StepService.class)); } } @Override public void onServiceDisconnected(ComponentName componentName) { // 断开链接 startService(new Intent(GuardService.this, StepService.class)); // 重新绑定 bindService(new Intent(GuardService.this, StepService.class), mServiceConnection, Context.BIND_IMPORTANT); } }; @Nullable @Override public IBinder onBind(Intent intent) { return new KeepAliveConnection.Stub() { }; } private interface Start { void onstar(long time); } private Start start; private ObservableOnSubscribe subscribe = new ObservableOnSubscribe() { @Override public void subscribe(ObservableEmitter emitter) throws Exception { start = emitter::onNext; } }; private Observer timeObserver = new Observer() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Long aLong) { Log.e(TAG, "timeObserver: onNext: " + aLong); startService(new Intent(GuardService.this, MainService.class)); } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }; @Override public void onCreate() { super.onCreate(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 8.0之后需要在 registmNewAppReceiver(); JGYUtils.startServices(GuardService.this); } registerPresentReceiver(); registerBatteryReceiver(); Observable.create(subscribe) .throttleFirst(10, TimeUnit.MINUTES) .subscribe(timeObserver); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, "onStartCommand: "); Aria.init(this); Aria.download(this).register(); // 绑定建立链接 bindService(new Intent(this, StepService.class), mServiceConnection, Context.BIND_IMPORTANT); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); if (null != mNewAppReceiver) { unregisterReceiver(mNewAppReceiver); } if (null != presentReceiver) { unregisterReceiver(presentReceiver); } if (null != batteryReceiver) { unregisterReceiver(batteryReceiver); } } private NewAppReceiver mNewAppReceiver; private void registmNewAppReceiver() { mNewAppReceiver = new NewAppReceiver(); IntentFilter filter = new IntentFilter(); filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); filter.addAction(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REPLACED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addDataScheme("package"); registerReceiver(mNewAppReceiver, filter); } private PresentReceiver presentReceiver; //监听亮屏息屏 public void registerPresentReceiver() { presentReceiver = new PresentReceiver(); IntentFilter filter = new IntentFilter(); filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); filter.addAction(Intent.ACTION_USER_PRESENT); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_USER_UNLOCKED); filter.addAction(Intent.ACTION_FACTORY_RESET); filter.addAction(Intent.ACTION_MASTER_CLEAR); filter.addAction(Intent.ACTION_MASTER_CLEAR_NOTIFICATION); filter.addAction("android.intent.action.FORCE_FACTORY_RESET"); filter.addAction(Intent.ACTION_SHUTDOWN); filter.addAction(Intent.ACTION_REBOOT); registerReceiver(presentReceiver, filter); } public class PresentReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, Intent intent) { String action = intent.getAction(); Log.e(TAG, "action:" + action); switch (action) { default: break; case Intent.ACTION_USER_PRESENT: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { /*在8.0以上 除了开机广播其他广播基本上没有用 *当静默安装升级时,app不会被唤醒,只有通过显示广播唤醒 * */ Intent intent1 = new Intent(BootReceiver.BOOT_COMPLETED); intent1.setComponent(new ComponentName(PackageNames.APPSTORE, PackageNames.APP_STORE_BOOTRECEIVER)); // 携带数据 //intent1.putExtra("test", "我是来测 A 应用的Android 8.0 系统静态广播的测试数据"); // 启动发送广播 sendBroadcast(intent1); JGYUtils.startServices(GuardService.this); if (JGYUtils.getInstance().checkAppPlatform() == JGYUtils.ZhanruiPlatform) { int setting_statusbar = Settings.System.getInt(context.getContentResolver(), "qch_hide_statusBar", 0); String statusbarStatus = ""; if (setting_statusbar == 0) { statusbarStatus = "qch_show_statusBar"; } else if (setting_statusbar == 1) { statusbarStatus = "qch_hide_statusBar"; } Intent navIntent = new Intent(statusbarStatus).setPackage("com.android.systemui"); context.sendBroadcast(navIntent); } } break; case Intent.ACTION_SCREEN_ON: { long time = System.currentTimeMillis(); AMapLocationClient aMapLocationClient = AmapManager.getInstance().getLocationClient(); aMapLocationClient.stopLocation(); aMapLocationClient.startLocation(); getLockState("2", String.valueOf(time)); // if (JGYUtils.getInstance().checkAppPlatform() == JGYUtils.ZhanruiPlatform) { // String statusbarStatus = "qch_hide_statusBar"; // Intent navIntent = new Intent(statusbarStatus).setPackage("com.android.systemui"); // context.sendBroadcast(navIntent); // } sendScreenStatus(1); } break; case Intent.ACTION_SCREEN_OFF: { HTTPInterface.getAppLimit(GuardService.this); long time = System.currentTimeMillis(); getLockState("1", String.valueOf(time)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Intent intent1 = new Intent(BootReceiver.BOOT_COMPLETED); intent1.setComponent(new ComponentName(PackageNames.APPSTORE, PackageNames.APP_STORE_BOOTRECEIVER)); sendBroadcast(intent1); JGYUtils.getInstance().deleteScreenshots(); } // if (JGYUtils.getInstance().checkAppPlatform() == JGYUtils.ZhanruiPlatform) { // String statusbarStatus = "qch_show_statusBar"; // Intent navIntent = new Intent(statusbarStatus).setPackage("com.android.systemui"); // context.sendBroadcast(navIntent); // } sendScreenStatus(2); } break; case Intent.ACTION_SHUTDOWN: case Intent.ACTION_REBOOT: int restart_count = (int) SPUtils.get(context, "restart_count", 0); SPUtils.put(context, "restart_count", restart_count + 1); // android.os.Process.killProcess(android.os.Process.myPid()); break; case Intent.ACTION_FACTORY_RESET: case Intent.ACTION_MASTER_CLEAR: case Intent.ACTION_MASTER_CLEAR_NOTIFICATION: case "android.intent.action.FORCE_FACTORY_RESET": sendRestoreTimes(); Log.e("PresentReceiver", "MASTER_CLEAR"); // android.os.Process.killProcess(android.os.Process.myPid()); // System.exit(0); break; } } } private void sendRestoreTimes() { NetInterfaceManager.getInstance().getRestoreTimesApi() .subscribe(new Observer() { @Override public void onSubscribe(Disposable d) { Log.e("sendRestoreTimes", "onSubscribe: "); } @Override public void onNext(BaseResponse baseResponse) { Log.e("sendRestoreTimes", "onNext: "); } @Override public void onError(Throwable e) { Log.e("sendRestoreTimes", "onError: " + e.getMessage()); } @Override public void onComplete() { Log.e("sendRestoreTimes", "onComplete: "); } }); } private void sendScreenStatus(int status) { Retrofit retrofit = new Retrofit.Builder() .client(NetInterfaceManager.getInstance().getOkHttpClient()) .baseUrl(BuildConfig.SCREEN_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); SendScreenStatusApi sendScreenStatusApi = retrofit.create(SendScreenStatusApi.class); sendScreenStatusApi.sendScreenStatus(NetInterfaceManager.HTTP_KEY, Utils.getSerial(), status) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer() { @Override public void onSubscribe(Disposable d) { Log.e("sendScreenStatus", "onSubscribe: "); } @Override public void onNext(BaseResponse baseResponse) { Log.e("sendScreenStatus", "onNext: " + baseResponse.msg); } @Override public void onError(Throwable e) { Log.e("sendScreenStatus", "onError: " + e.getMessage()); } @Override public void onComplete() { Log.e("sendScreenStatus", "onComplete: "); } }); } private void getLockState(String status, String time) { if (JGYUtils.isOfficialVersion()) { return; } GetLockStateApi getLockState = NetInterfaceManager.getInstance().getLockState(); getLockState.getLockState(Utils.getSerial(), status, time) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer() { @Override public void onSubscribe(Disposable d) { Log.e("getLockState", "onSubscribe: "); } @Override public void onNext(ResponseBody responseBody) { try { com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(responseBody.string()); Log.e("getLockState", "onNext: " + jsonObject); int code = jsonObject.getInteger("code"); Log.e("getLockState", "onNext: code: " + code); } catch (IOException e) { e.printStackTrace(); } } @Override public void onError(Throwable e) { Log.e("getLockState", "onError: " + e.getMessage()); } @Override public void onComplete() { Log.e("getLockState", "onComplete: "); } }); } private void registerBatteryReceiver() { if (null == batteryReceiver) { batteryReceiver = new BatteryReceiver(); } IntentFilter filter = new IntentFilter(); filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); filter.addAction(Intent.ACTION_BATTERY_CHANGED); filter.addAction(Intent.ACTION_BATTERY_LOW); filter.addAction(Intent.ACTION_BATTERY_OKAY); filter.addAction(Intent.ACTION_POWER_CONNECTED); filter.addAction(Intent.ACTION_POWER_DISCONNECTED); registerReceiver(batteryReceiver, filter); } BatteryReceiver batteryReceiver; private class BatteryReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { // 当前电量 int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0); // 最大电量 int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0); int elec = (level * 100) / scale; // Log.e(TAG, "electricity:=" + elec + "%"); if (elec == 50) { start.onstar(SystemClock.elapsedRealtime()); } } else { if (Intent.ACTION_POWER_CONNECTED.equals(action)) { LogDBManager.getInstance().creatOtherLog(LogDBManager.LOG_EVENT_BATTERY, "开始充电", "rlectricity: " + JGYUtils.getInstance().getBatteryLevel() + "%"); } if (Intent.ACTION_POWER_DISCONNECTED.equals(action)) { LogDBManager.getInstance().creatOtherLog(LogDBManager.LOG_EVENT_BATTERY, "停止充电", "rlectricity: " + JGYUtils.getInstance().getBatteryLevel() + "%"); } if (Intent.ACTION_BATTERY_LOW.equals(action)) { LogDBManager.getInstance().creatOtherLog(LogDBManager.LOG_EVENT_BATTERY, "电量偏低", "rlectricity: " + JGYUtils.getInstance().getBatteryLevel() + "%"); } if (Intent.ACTION_BATTERY_OKAY.equals(action)) { LogDBManager.getInstance().creatOtherLog(LogDBManager.LOG_EVENT_BATTERY, "电量充足", "rlectricity: " + JGYUtils.getInstance().getBatteryLevel() + "%"); } setDefaultUSBStatus(); Log.e(TAG, action); start.onstar(SystemClock.elapsedRealtime()); } } } private void setDefaultUSBStatus() { String setting_usb = Settings.System.getString(getContentResolver(), "qch_usb_choose"); Log.e("setDefaultUSBStatus", "setting_usb---------" + setting_usb); String usbStatus = ""; if (TextUtils.isEmpty(setting_usb)) { usbStatus = "qch_action_usb_usb_charge"; } else { switch (setting_usb) { case "usb_charge": usbStatus = "qch_action_usb_usb_charge"; break; case "usb_mtp": usbStatus = "qch_action_usb_usb_mtp"; break; case "usb_midi": usbStatus = "qch_action_usb_usb_midi"; break; default: break; } } Intent usbIntent = new Intent(usbStatus).setPackage("com.android.settings"); sendBroadcast(usbIntent); } //在这里处理任务执行中的状态,如进度进度条的刷新 @Download.onTaskRunning protected void running(DownloadTask task) { JSONObject jsonObject = JSON.parseObject(task.getExtendField()); String app_name = jsonObject.getString("app_name"); String app_package = jsonObject.getString("app_package"); Log.e("aria", "正在下载:" + task.getPercent() + ":" + task.getExtendField()); ToastUtil.show("正在下载:" + app_name + "-" + task.getPercent() + "%" + "\t" + Formatter.formatFileSize(GuardService.this, task.getSpeed()) + "/s"); } @Download.onTaskComplete void taskComplete(DownloadTask task) { //在这里处理任务完成的状态 String filepath = task.getFilePath(); String extendField = task.getExtendField(); Log.e("taskComplete", "downloadPath::" + filepath); Log.e("taskComplete", "extendField::" + extendField); if (filepath.endsWith("apk")) { JSONObject jsonObject = JSON.parseObject(extendField); String app_name = jsonObject.getString("app_name"); String app_package = jsonObject.getString("app_package"); String app_id = jsonObject.getString("app_id"); ToastUtil.show(app_name + "\t:下载完成"); if (filepath.endsWith(".xapk")) { XAPKUtils.getInstance().installXAPK(filepath); Log.e(TAG, "taskComplete: " + filepath); } else if (filepath.endsWith(".apk")) { new Thread(() -> ApkUtils.installApp(GuardService.this, filepath)).start(); List list = Aria.download(this).getDRunningTask(); if (list == null || list.size() == 0) { BaseApplication.getInstance().setDownloadState(false); Log.e("taskComplete", "isDownloading=" + BaseApplication.getInstance().isDownloading()); } } NetInterfaceManager.getInstance() .getSendTimesApi() .sendDownloadTimes(NetInterfaceManager.HTTP_KEY, Utils.getSerial(), app_package, app_id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer() { @Override public void onSubscribe(Disposable d) { Log.e("SEND_DOWNLOAD_TIMES", "onSubscribe: "); } @Override public void onNext(BaseResponse baseResponse) { Log.e("SEND_DOWNLOAD_TIMES", "onNext: " + baseResponse.msg); } @Override public void onError(Throwable e) { Log.e("SEND_DOWNLOAD_TIMES", "onError: " + e.getMessage()); } @Override public void onComplete() { Log.e("SEND_DOWNLOAD_TIMES", "onComplete: "); } }); int userId = (int) SPUtils.get(GuardService.this, CommonConfig.ADMIN_ID, 0); long appSize = task.getFileSize(); NetInterfaceManager.getInstance() .getSendInfoApi() .sendDownloadTimes(NetInterfaceManager.HTTP_KEY, Utils.getSerial(), userId, app_package, appSize) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer() { @Override public void onSubscribe(Disposable d) { Log.e("SEND_DOWNLOAD_FILE_INFO", "onSubscribe: "); } @Override public void onNext(BaseResponse baseResponse) { Log.e("SEND_DOWNLOAD_FILE_INFO", "onNext: " + baseResponse.msg); } @Override public void onError(Throwable e) { Log.e("SEND_DOWNLOAD_FILE_INFO", "onError: " + e.getMessage()); } @Override public void onComplete() { Log.e("SEND_DOWNLOAD_FILE_INFO", "onComplete: "); } }); } else if (filepath.endsWith(".zip")) { Log.e("taskComplete", "下载完成:" + task.getPercent() + ":" + task.getExtendField()); JGYUtils.getInstance().setBootanimation(task.getFilePath()); } } @Download.onTaskFail void taskFail(DownloadTask task, Exception e) { try { final String filepath = task.getFilePath(); final String packageName = task.getExtendField(); JSONObject jsonObject = JSON.parseObject(task.getExtendField()); String app_name = jsonObject.getString("app_name"); String app_package = jsonObject.getString("app_package"); Log.e("aria", "taskFail: " + packageName + "filepath: " + filepath + "Exception: " + e.getMessage()); // ToastUtil.show(app_name + "\t:下载失败"); } catch (Exception e1) { Log.e("aria", "taskFail: " + e1.getMessage()); } } }