version:1.0

update:2021-10-13 18:52:13
fix:去除okgo,rxAndroid1,优化依赖
add:切换到奥乐云平台
This commit is contained in:
2021-10-13 18:54:20 +08:00
parent 13707fc96a
commit 3018660216
181 changed files with 2343 additions and 4445 deletions

View File

@@ -0,0 +1,532 @@
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.PackageNames;
import com.aoleyun.sn.network.api.newapi.SendScreenStatusApi;
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.Logutils;
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.manager.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) {
Logutils.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<Long> subscribe = new ObservableOnSubscribe<Long>() {
@Override
public void subscribe(ObservableEmitter<Long> emitter) throws Exception {
start = emitter::onNext;
}
};
private Observer<Long> timeObserver = new Observer<Long>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Long aLong) {
Logutils.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() {
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);
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Logutils.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("android.intent.action.FACTORY_RESET");
filter.addAction("android.intent.action.MASTER_CLEAR");
registerReceiver(presentReceiver, filter);
}
public class PresentReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
Logutils.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 "android.intent.action.FACTORY_RESET":
case "android.intent.action.MASTER_CLEAR":
case "android.intent.action.MASTER_CLEAR_NOTIFICATION":
case "android.intent.action.FORCE_FACTORY_RESET":
Logutils.e("PresentReceiver", "MASTER_CLEAR");
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
break;
}
}
}
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<BaseResponse>() {
@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<ResponseBody>() {
@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;
// Logutils.e(TAG, "electricity:=" + elec + "%");
if (elec == 50) {
start.onstar(SystemClock.elapsedRealtime());
}
} else if (Intent.ACTION_POWER_CONNECTED.equals(action)
|| Intent.ACTION_POWER_DISCONNECTED.equals(action)
|| Intent.ACTION_BATTERY_LOW.equals(action)
|| Intent.ACTION_BATTERY_OKAY.equals(action)
) {
setDefaultUSBStatus();
Logutils.e(TAG, action);
start.onstar(SystemClock.elapsedRealtime());
}
}
}
private void setDefaultUSBStatus() {
String setting_usb = Settings.System.getString(getContentResolver(), "qch_usb_choose");
Logutils.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");
Logutils.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();
Logutils.e("taskComplete", "downloadPath::" + filepath);
Logutils.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);
Logutils.e(TAG, "taskComplete: " + filepath);
} else if (filepath.endsWith(".apk")) {
new Thread(() -> ApkUtils.installApp(GuardService.this, filepath)).start();
List<DownloadEntity> list = Aria.download(this).getDRunningTask();
if (list == null || list.size() == 0) {
BaseApplication.getInstance().setDownloadState(false);
Logutils.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<BaseResponse>() {
@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, "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<BaseResponse>() {
@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")) {
Logutils.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");
Logutils.e("aria", "下载失败: " + packageName + "filepath " + filepath + "Exception: " + e.getMessage());
// ToastUtil.show(app_name + "\t:下载失败");
} catch (Exception e1) {
Logutils.e("aria", "taskFail: " + e1.getMessage());
}
}
}