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());
}
}
}

View File

@@ -0,0 +1,36 @@
package com.aoleyun.sn.service;
import com.aoleyun.sn.utils.Logutils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
public class JWebSocketClient extends WebSocketClient {
public JWebSocketClient(URI serverUri) {
super(serverUri, new Draft_6455());
}
@Override
public void onOpen(ServerHandshake handshakedata) {
Logutils.e("JWebSocketClient", "onOpen()");
}
@Override
public void onMessage(String message) {
Logutils.e("JWebSocketClient", "onMessage()");
}
@Override
public void onClose(int code, String reason, boolean remote) {
Logutils.e("JWebSocketClient", "onClose():" + reason);
}
@Override
public void onError(Exception ex) {
Logutils.e("JWebSocketClient", "onError():" + ex.getMessage());
}
}

View File

@@ -0,0 +1,249 @@
package com.aoleyun.sn.service;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.text.TextUtils;
import com.aoleyun.sn.utils.Logutils;
import com.aoleyun.sn.utils.Utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LogcatService extends Service {
public final static String LOGCAT_START_ACTION = "START";
public final static String LOGCAT_STOP_ACTION = "STOP";
private String TAG = LogcatService.class.getSimpleName();
public LogcatService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
logFilePath = getExternalCacheDir() + File.separator + "LOG" + File.separator;
File file = new File(logFilePath);
if (!file.exists()) {
file.mkdirs();
}
// try {
// exec = Runtime.getRuntime().exec(running);
// final InputStream is = exec.getInputStream();
// logThread = new LogThread(is);
// logThread.start();
// // is.close();
//// exec.destroy();
// } catch (IOException e) {
//// e.printStackTrace();
// Logutils.e("第一个是Logcat", e.getMessage());
// }
registerLogcatReceiver();
}
LogcatReceiver receiver;
private void registerLogcatReceiver() {
receiver = new LogcatReceiver();
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(LOGCAT_START_ACTION);
filter.addAction(LOGCAT_STOP_ACTION);
registerReceiver(receiver, filter);
}
Thread thread = null;
private void creatLogThread() {
if (thread == null) {
thread = new Thread(LogcatRunnale);
}
}
private void startLogThread() {
if (thread == null) {
creatLogThread();
shouldGetLog = true;
thread.start();
} else {
//已经有线程正在运行了
}
}
private void stopLogThread() {
if (thread != null) {
shouldGetLog = false;
thread = null;
//清除adb 缓存
try {
Runtime.getRuntime().exec(clearLogcat);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Process exec;
private LogThread logThread;
//第一个是Logcat 也就是我们想要获取的log日志
//第二个是 -s 也就是表示过滤的意思
//第三个就是 我们要过滤的类型 W表示warm ,我们也可以换成 D debug IinfoEerror等等
// String[] running = new String[]{"logcat", "-s", "adb logcat *: W"};
String[] running = new String[]{"logcat"};
String clearLogcat = "logcat -c";
String logFilePath;
//= getExternalCacheDir() + File.separator + "LOG" + File.separator;
String logFileName;
class LogThread extends Thread {
InputStream is;
LogThread(InputStream inputStream) {
super();
this.is = inputStream;
}
@Override
public void run() {
FileOutputStream os = null;
try {
//新建一个路径信息
File file = new File(logFilePath + logFileName);
Logutils.e(TAG, "run: " + logFilePath);
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
os = new FileOutputStream(logFilePath);
int len = 0;
byte[] buf = new byte[1024];
while (-1 != (len = is.read(buf))) {
os.write(buf, 0, len);
os.flush();
}
} catch (Exception e) {
Logutils.e("writelog", "read logcat process failed. message: "
+ e.getMessage());
} finally {
if (null != os) {
try {
os.close();
os = null;
} catch (IOException e) {
// Do nothing
}
}
}
}
}
private Runnable LogcatRunnale = new Runnable() {
@Override
public void run() {
getLog();
}
};
public static boolean shouldGetLog = true;
private void getLog() {
Process process = null;
try {
process = Runtime.getRuntime().exec(running);
} catch (IOException e) {
e.printStackTrace();
}
InputStreamReader inputStreamReader;
BufferedReader bufferedReader;
FileOutputStream fileOutputStream;
File file = new File(logFilePath);
Logutils.e(TAG, "getLog: " + logFilePath);
if (!file.exists()) {
file.mkdirs();
}
logFileName = Utils.getSerial() + "-" + getTime() + ".log";
try {
inputStreamReader = new InputStreamReader(process.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
fileOutputStream = new FileOutputStream(logFilePath + logFileName);
Logutils.e(TAG, "getLog: " + logFilePath + logFileName);
String logEntry;
while (shouldGetLog) {
logEntry = bufferedReader.readLine() + "\n";
fileOutputStream.write(logEntry.getBytes());
fileOutputStream.flush();
}
inputStreamReader.close();
bufferedReader.close();
fileOutputStream.close();
Logutils.e(TAG, "getLog: " + "closed");
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
class LogcatReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Logutils.e(TAG, "onReceive: " + action);
if (TextUtils.isEmpty(action)) {
return;
}
switch (action) {
case LOGCAT_START_ACTION:
startLogThread();
break;
case LOGCAT_STOP_ACTION:
stopLogThread();
break;
default:
break;
}
}
}
public static String getTime() {
long time = System.currentTimeMillis();//long now = android.os.SystemClock.uptimeMillis();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date d1 = new Date(time);
String t1 = format.format(d1);
return t1;
}
@Override
public void onDestroy() {
super.onDestroy();
if (receiver != null) {
unregisterReceiver(receiver);
}
}
}

View File

@@ -0,0 +1,767 @@
package com.aoleyun.sn.service;
import android.annotation.SuppressLint;
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.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aoleyun.sn.comm.PackageNames;
import com.blankj.utilcode.util.NetworkUtils;
import com.google.gson.JsonObject;
import com.aoleyun.sn.R;
import com.aoleyun.sn.action.JGYActions;
import com.aoleyun.sn.activity.MainActivity;
import com.aoleyun.sn.activity.MainContact;
import com.aoleyun.sn.activity.MainPresenter;
import com.aoleyun.sn.receiver.BootReceiver;
import com.aoleyun.sn.utils.ApkUtils;
import com.aoleyun.sn.utils.ForegroundAppUtil;
import com.aoleyun.sn.utils.Logutils;
import com.aoleyun.sn.utils.SPUtils;
import com.aoleyun.sn.utils.SaveListUtils;
import com.aoleyun.sn.utils.SysSettingUtils;
import com.aoleyun.sn.utils.TimeUtils;
import com.aoleyun.sn.utils.ToastUtil;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.RxLifecycle;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.RxLifecycleAndroid;
import java.util.Arrays;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.subjects.BehaviorSubject;
public class MainService extends Service implements MainContact.MainView, NetworkUtils.OnNetworkStatusChangedListener, LifecycleProvider<ActivityEvent> {
@SuppressLint("StaticFieldLeak")
public static MainPresenter mPresenter;
private static final String TAG = MainService.class.getSimpleName();
public static boolean netWorkIsRunning = false;
@Override
public void onDisconnected() {
Log.e("OnNetworkStatusChangedListener", "onDisconnected: ");
ToastUtil.betaShow("网络断开连接");
}
@Override
public void onConnected(NetworkUtils.NetworkType networkType) {
Log.e("OnNetworkStatusChangedListener", "onConnected: ");
runningTime = SystemClock.elapsedRealtime();
//直接获取数据
ToastUtil.betaShow("网络已连接");
start.onstar(SystemClock.elapsedRealtime());
}
private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();
@Override
public Observable<ActivityEvent> lifecycle() {
return lifecycleSubject.hide();
}
@Override
public <T> LifecycleTransformer<T> bindUntilEvent(ActivityEvent event) {
return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
}
@Override
public <T> LifecycleTransformer<T> bindToLifecycle() {
return RxLifecycleAndroid.bindActivity(lifecycleSubject);
}
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("TimeObserver", "onNext: " + aLong);
startCommandTime = runningTime = SystemClock.elapsedRealtime();
mPresenter.getFirstConnect();
mPresenter.getLockedState();
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
};
public MainService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
lifecycleSubject.onNext(ActivityEvent.CREATE);
mPresenter = new MainPresenter(this);
mPresenter.attachView(this);
mPresenter.setProvider(this);
if ((int) SPUtils.get(this, "first_connect", 0) == 0) {
// TODO: 2021/5/26 待底层修改,临时解决办法
Logutils.e(TAG, "onCreate: " + "Disable All Settings");
mPresenter.setDisableSetting();
}
registerReceivers();
NetworkUtils.registerNetworkStatusChangedListener(this);
addShortcut();
Observable.create(subscribe)
.throttleFirst(3, TimeUnit.HOURS)
.subscribe(timeObserver);
Observable.create(timeChangedSubscribe)
.throttleFirst(3, TimeUnit.HOURS)
.subscribe(timeChangedObserver);
// cleanLauncherCache();
timeChangedStart.onstar(System.currentTimeMillis());
setStatusbar();
//发送设备mac地址和信息
mPresenter.sendMACAddress();
setFloatingWindow(this);
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
unRegisterReceivers();
NetworkUtils.unregisterNetworkStatusChangedListener(this);
lifecycleSubject.onNext(ActivityEvent.DESTROY);
mPresenter.detachView();
}
//执行所有请求的时间
long runningTime;
//MainService上次执行时间
long startCommandTime = 0;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent bootIntent = new Intent(BootReceiver.BOOT_COMPLETED);
bootIntent.setComponent(new ComponentName(PackageNames.APPSTORE, PackageNames.APP_STORE_BOOTRECEIVER));
sendBroadcast(bootIntent);
JPushInterface.init(this);
if (MainActivity.isForeground) {
Logutils.e(TAG, "onStartCommand: MainService: isForeground: " + MainActivity.isForeground);
} else {
// if (((SystemClock.elapsedRealtime() - startCommandTime) < 60000) && startCommandTime != 0) {
// Logutils.e(TAG, "onStartCommand: " + "启动时间过短");
// //一分钟内防止多次调用
// } else {
// mPresenter.getFirstConnect();
// mPresenter.getLockedState();
// startCommandTime = runningTime = SystemClock.elapsedRealtime();
// Logutils.e(TAG, "onStartCommand: isForeground: " + MainActivity.isForeground);
// Logutils.e(TAG, "onStartCommand: " + (SystemClock.elapsedRealtime() - startCommandTime));
// }
start.onstar(SystemClock.elapsedRealtime());
Logutils.e(TAG, "onStartCommand: " + (SystemClock.elapsedRealtime() - startCommandTime) + "ms");
}
return START_STICKY;
}
private void addShortcut() {
ApkUtils.addShortcut(MainService.this);
}
private void setStatusbar() {
String status = (String) SPUtils.get(this, JGYActions.ACTION_STATUS_BAR_STATUS, "");
Logutils.e(TAG, "setStatusbar: String: " + status);
if (TextUtils.isEmpty(status)) {
Logutils.e(TAG, "setStatusbar: " + "status is NULL");
return;
}
JSONObject jsonObject = JSON.parseObject(status);
SysSettingUtils.setStatusBar(this, jsonObject);
}
private void registerReceivers() {
registerLockScreenReceiver();
registerTimeReceiver();
registerInstallReceiver();
}
private void unRegisterReceivers() {
if (null != lockScreenReceiver) {
unregisterReceiver(lockScreenReceiver);
}
if (null != mTimeChangedReceiver) {
unregisterReceiver(mTimeChangedReceiver);
}
if (null != mInstallReceiver) {
unregisterReceiver(mInstallReceiver);
}
}
private static WindowManager windowManager;
private View topView;
boolean screenlocked = false;
boolean timelocked = false;
@SuppressLint("NewApi")
private void showFloatingWindow(String name) {
if (Settings.canDrawOverlays(this)) {
// 获取WindowManager服务
if (null == windowManager) {
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
}
DisplayMetrics dm = new DisplayMetrics();
windowManager.getDefaultDisplay().getRealMetrics(dm);
int width = dm.widthPixels; // 屏幕宽度(像素)
int height = dm.heightPixels; // 屏幕高度(像素)
// 新建悬浮窗控件
final Button button = new Button(getApplicationContext());
button.setText("霸屏测试");
button.setAlpha(0.9f);
button.setBackgroundColor(Color.WHITE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// windowManager.removeView(button);
}
});
if (null == topView) {
topView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.activity_top, null);
TextView textView = topView.findViewById(R.id.textView);
textView.setText(name);
} else {
if (topView.getTag().equals("added")) {
TextView textView = topView.findViewById(R.id.textView);
textView.setText(name);
return;
}
}
// topView.setAlpha(0.8f);
TextView textView = topView.findViewById(R.id.textView);
textView.setText(name);
// 设置LayoutParam
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
layoutParams.type = WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG;
} else {
layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
}
layoutParams.flags |= WindowManager.LayoutParams.FLAG_BLUR_BEHIND
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
layoutParams.format = PixelFormat.RGBA_8888;
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
//systemUiVisibility 关闭通知栏和导航栏
layoutParams.systemUiVisibility =
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
layoutParams.x = 0;
layoutParams.y = 0;
// 将悬浮窗控件添加到WindowManager
windowManager.addView(topView, layoutParams);
topView.setTag("added");
}
}
private void hideFloatingWindow() {
if (null == windowManager) {
return;
}
if (null != topView) {
windowManager.removeView(topView);
topView = null;
}
}
private LockScreenReceiver lockScreenReceiver;
private void registerLockScreenReceiver() {
if (null == lockScreenReceiver) {
lockScreenReceiver = new LockScreenReceiver();
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(LockScreenReceiver.action_lock);
filter.addAction(LockScreenReceiver.action_unlock);
registerReceiver(lockScreenReceiver, filter);
}
}
//锁屏管控广播
public class LockScreenReceiver extends BroadcastReceiver {
public static final String action_lock = "LockScreenReceiver_lockscreen";
public static final String action_unlock = "LockScreenReceiver_unlockscreen";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Logutils.e("LockScreenReceiver", "onReceive: " + action);
if (TextUtils.isEmpty(action)) {
return;
}
if (action_lock.equals(action)) {
String name = intent.getStringExtra("name");
if (!timelocked) {
showFloatingWindow(name);
}
screenlocked = true;
} else if (action_unlock.equals(action)) {
if (!timelocked) {
hideFloatingWindow();
}
screenlocked = false;
}
}
}
private interface TimeChangedStart {
void onstar(long time);
}
private TimeChangedStart timeChangedStart;
private ObservableOnSubscribe<Long> timeChangedSubscribe = new ObservableOnSubscribe<Long>() {
@Override
public void subscribe(ObservableEmitter<Long> emitter) throws Exception {
timeChangedStart = emitter::onNext;
}
};
private Observer<Long> timeChangedObserver = new Observer<Long>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Long aLong) {
setFloatingWindow(MainService.this);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
};
private TimeChangedReceiver mTimeChangedReceiver;
/**
* 监听时间变化
*/
public void registerTimeReceiver() {
mTimeChangedReceiver = new TimeChangedReceiver();
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(Intent.ACTION_DATE_CHANGED);
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
filter.addAction(Intent.ACTION_TIME_TICK);
filter.addAction(TimeChangedReceiver.ACTION_UPDATE);
registerReceiver(mTimeChangedReceiver, filter);
}
public class TimeChangedReceiver extends BroadcastReceiver {
public static final String ACTION_UPDATE = "TimeChangedReceiver_update";
@SuppressLint("NewApi")
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "onReceive: " + intent.getAction());
if (Intent.ACTION_DATE_CHANGED.equals(intent.getAction())) {
Logutils.e("TimeChangedReceiver", "onReceive:" + "data changed");
} else if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
Logutils.e("TimeChangedReceiver", "onReceive:" + "time changed");
} else if (Intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
Logutils.e("TimeChangedReceiver", "onReceive:" + "timezone changed");
} else if (Intent.ACTION_TIME_TICK.equals(intent.getAction())) {
Logutils.e("TimeChangedReceiver", "onReceive:" + "time tick");
setFloatingWindow(MainService.this);
} else if (ACTION_UPDATE.equals(intent.getAction())) {
setFloatingWindow(MainService.this);
mPresenter.getScreenLockState();
Logutils.e("TimeChangedReceiver", "onReceive:" + "date update");
}
timeChangedStart.onstar(System.currentTimeMillis());
}
}
synchronized private void setFloatingWindow(Context context) {
ForegroundAppUtil.openTopApp(context);
long nowTime = System.currentTimeMillis();
TimeUtils.ContralTime contralTime = TimeUtils.getDefaltContralTime(MainService.this);
Log.e(TAG, "setFloatingWindow: screenlocked: " + screenlocked);
if (null != contralTime) {
if (contralTime.inControlTime(nowTime)) {
if (!screenlocked) {
showFloatingWindow("管控时间:" + contralTime.toString());
} else {
TextView textView = topView.findViewById(R.id.textView);
textView.setText("管控时间:" + contralTime.toString());
}
timelocked = true;
} else {
if (!screenlocked) {
hideFloatingWindow();
}
timelocked = false;
}
} else {
if (!screenlocked) {
hideFloatingWindow();
}
timelocked = false;
}
}
private void registerInstallReceiver() {
if (mInstallReceiver == null) {
mInstallReceiver = new InstallReceiver();
}
IntentFilter intentFilter = new IntentFilter(INSTALLAPK_ACTION);
registerReceiver(mInstallReceiver, intentFilter, INSTALLAPK_PREMISSIONS, null);
}
private String INSTALLAPK_ACTION = "JGY_INSTALLAPK_ACTION";
private String INSTALLAPK_PREMISSIONS = "com.aoleyun.sn.permissions.INSTALL_APK";
private InstallReceiver mInstallReceiver;
/**
* https://blog.csdn.net/jdsjlzx/article/details/82630113
*/
class InstallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (TextUtils.isEmpty(action)) {
Logutils.e(TAG, "onReceive: " + "Action is NULL!");
return;
}
Logutils.e(TAG, "onReceive: " + "Sender is " + intent.getPackage());
String packageName = intent.getStringExtra("packageName");
String filePath = intent.getStringExtra("filePath");
if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(filePath)) {
Logutils.e(TAG, "onReceive: " + "packageName: " + packageName + "filePath: " + filePath);
installApkByPackage(filePath, packageName);
} else if (!TextUtils.isEmpty(filePath)) {
String pkg = ApkUtils.getPackageName(MainService.this, filePath);
if (TextUtils.isEmpty(pkg)) {
Logutils.e(TAG, "onReceive: " + "unknow packageName");
} else {
Logutils.e(TAG, "onReceive: " + "pkg: " + pkg + "\tfilePath: " + filePath);
installApkByPackage(filePath, pkg);
}
} else {
Logutils.e(TAG, "onReceive: " + "no filePath and packageName");
}
}
}
/**
* @param filePath 路径
* @param pkg 包名
*/
@SuppressLint("NewApi")
synchronized private void installApkByPackage(String filePath, String pkg) {
String oldListString = Settings.System.getString(getContentResolver(), "qch_app_forbid");
HashSet<String> packageList = new HashSet<>(Arrays.asList(oldListString.split(",")));
if (!packageList.contains(pkg)) {
Logutils.e(TAG, "installApkByPackage: " + "packageName: " + pkg + " not in whitelist");
} else {
Logutils.e(TAG, "installApkByPackage: " + "packageName: " + pkg);
ApkUtils.installApp(MainService.this, filePath);
}
}
@Override
public void setQRImage(Bitmap qrImage) {
}
@Override
public void setBatchText(String text, int visibility) {
}
@Override
public void setClassText(String text, int visibility) {
}
@Override
public void setNumberText(String text, int visibility) {
}
@Override
public void setNameText(String text, int visibility) {
}
@Override
public void setLockedState(boolean loocked) {
if (loocked) {
ToastUtil.betaShow("设备已上锁");
Logutils.e(TAG, "setLockedState: " + netWorkIsRunning);
//上传APP信息
ApkUtils.getAppInfo(this);
//发送设备mac地址和信息
mPresenter.sendMACAddress();
//设置极光推送别名
mPresenter.setJpushAlias();
//设置极光推送标签
SaveListUtils.getList();
if (netWorkIsRunning) {
//如果正在执行,不执行
// return;
}
//获取系统管控
mPresenter.setJpushTags();
netWorkIsRunning = true;
} else {
ToastUtil.betaShow("设备已解锁");
netWorkIsRunning = false;
SysSettingUtils.setEnableSetting(this);
}
}
/**
* 首次使用默认关闭所有功能
*
* @param state
*/
@Override
public void setFirstConnect(boolean state) {
Logutils.e(TAG, "isFirstConnect: " + "end request: " + state);
if (state) {
mPresenter.setDisableSetting();
} else {
}
}
@Override
public void sendMACFinished() {
mPresenter.updateDeviceInfo();
}
@Override
public void updateDeviceInfoFinished() {
mPresenter.getSnTimeControl();
}
@Override
public void getSnTimeControlFinished() {
mPresenter.getEBagCode();
}
@Override
public void getEBagCodeFinished() {
}
@Override
public void setAliasFinished() {
mPresenter.checkStoreUpdate();
}
@Override
public void setJpushPlatformTagsFinished() {
}
@Override
public void checkStoreUpdateFinished() {
mPresenter.checkInfoUpdate();
}
@Override
public void checkInfoUpdateFinished() {
mPresenter.checkTestUpdate();
}
@Override
public void checkTestUpdateFinished() {
}
@Override
public void buttonCheckUpdateFinished(boolean update, JsonObject jsonObject) {
}
@Override
public void setTagsFinished(boolean noTag) {
if (noTag) {
Log.e(TAG, "setTagsFinished: " + "not set tag");
netWorkIsRunning = false;
Log.e(TAG, "SettingFinished: " + (SystemClock.elapsedRealtime() - runningTime) + " ms");
} else {
mPresenter.getSystemSettingbegin();
}
}
@Override
public void getSystemSettingbegin() {
mPresenter.getAppLimit();
}
@Override
public void getAppLimitFinished(String packageList) {
mPresenter.getDeviceBatch(packageList);
}
@Override
public void getDeviceBatchFinished() {
mPresenter.getForceDownload();
}
@Override
public void getForceDownloadFinished() {
mPresenter.getBrowserList();
}
@Override
public void getBrowserListFinished(String whitelist) {
mPresenter.getBrowserBookmarks(whitelist);
}
@Override
public void getBrowserBookmarksFinished() {
mPresenter.getBrowserWhiteList();
mPresenter.getDesktopIcon();
}
@Override
public void getDesktopIconFinished() {
mPresenter.getAppAutoStartUpdateAndNet();
}
@Override
public void getAppAutoStartUpdateAndNetFinished() {
mPresenter.getAppIDControl();
}
@Override
public void getAppIDControlFinished() {
mPresenter.setAppinsideWeb();
}
@Override
public void setAppinsideWebFinished() {
mPresenter.setSystemSetting();
}
@Override
public void setSystemSettingFinished() {
mPresenter.getDefaultApp();
}
@Override
public void setDefaultAppFinished() {
mPresenter.getROMApp();
}
@Override
public void getROMAppFinished() {
mPresenter.getDeveloper();
}
@Override
public void getDeveloperFinished() {
mPresenter.setLogoImg();
}
@Override
public void setLogoImgFinished() {
mPresenter.setTopApp();
}
@Override
public void setTopAppFinished() {
mPresenter.getDefaultDesktop();
}
@Override
public void getDefaultDesktopFinished() {
netWorkIsRunning = false;
Log.e(TAG, "SettingFinished: " + (SystemClock.elapsedRealtime() - runningTime) + " ms");
}
@Override
public void setScreenLockStateFinished(boolean locked, String tips) {
if (locked) {
if (!timelocked) {
showFloatingWindow(tips);
}
screenlocked = true;
SPUtils.put(MainService.this, "is_screen_lock", true);
SPUtils.put(MainService.this, "screen_tips", tips);
} else {
if (!timelocked) {
hideFloatingWindow();
}
screenlocked = false;
SPUtils.put(MainService.this, "is_screen_lock", false);
SPUtils.put(MainService.this, "screen_tips", "");
}
}
}

View File

@@ -0,0 +1,34 @@
package com.aoleyun.sn.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
// 下载管理服务
public class MyDownloadService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
flags = START_STICKY;
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
startService(new Intent(this, StepService.class));
startService(new Intent(this, GuardService.class));
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}

View File

@@ -0,0 +1,42 @@
package com.aoleyun.sn.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import com.aoleyun.sn.IGetLicenseInterface;
import com.aoleyun.sn.utils.Logutils;
import com.aoleyun.sn.utils.SPUtils;
public class RemoteService extends Service {
private String TAG = RemoteService.class.getSimpleName();
public RemoteService() {
}
@Override
public IBinder onBind(Intent intent) {
Logutils.e(TAG, "onBind: ");
return mBinde;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
IGetLicenseInterface.Stub mBinde = new IGetLicenseInterface.Stub() {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
}
@Override
public String getLicense() throws RemoteException {
String ebagCode = (String) SPUtils.get(RemoteService.this, "ebagCode", "");
Logutils.e(TAG, "getLicense: " + ebagCode);
return ebagCode;
}
};
}

View File

@@ -0,0 +1,316 @@
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.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.Nullable;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.NetworkUtils;
import com.aoleyun.sn.KeepAliveConnection;
import com.aoleyun.sn.manager.NetInterfaceManager;
import com.aoleyun.sn.utils.Logutils;
import com.aoleyun.sn.utils.ServiceAliveUtils;
import com.aoleyun.sn.utils.Utils;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
/**
* 主进程 双进程通讯
*
* @author LiGuangMin
* @time Created by 2018/8/17 11:26
*/
public class StepService extends Service implements NetworkUtils.OnNetworkStatusChangedListener {
private final static String TAG = StepService.class.getSimpleName();
public JWebSocketClient client;
private JWebSocketClientBinder mBinder = new JWebSocketClientBinder();
@Override
public void onDisconnected() {
}
@Override
public void onConnected(NetworkUtils.NetworkType networkType) {
connect();
}
//用于Activity和service通讯
public class JWebSocketClientBinder extends Binder {
public StepService getService() {
return StepService.this;
}
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Logutils.w(TAG, "StepService:建立链接");
boolean isServiceRunning = ServiceAliveUtils.isServiceAlive(StepService.this, GuardService.class.getName());
if (!isServiceRunning) {
Intent i = new Intent(StepService.this, GuardService.class);
startService(i);
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
// 断开链接
startService(new Intent(StepService.this, GuardService.class));
// 重新绑定
bindService(new Intent(StepService.this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new KeepAliveConnection.Stub() {
};
}
@Override
public void onCreate() {
super.onCreate();
NetworkUtils.registerNetworkStatusChangedListener(this);
registerScreenLockReceiver();
//初始化websocket
initSocketClient();
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// startForeground(1, new Notification());
// 绑定建立链接
Logutils.e("JWebSocketClientService", "onStartCommand: ");
bindService(new Intent(this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);
return START_STICKY;
}
private ScreenLockReceiver screenLockReceiver;
private void registerScreenLockReceiver() {
if (null == screenLockReceiver) {
screenLockReceiver = new ScreenLockReceiver();
}
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(Intent.ACTION_SHUTDOWN);
filter.addAction(Intent.ACTION_FACTORY_RESET);
filter.addAction(Intent.ACTION_MASTER_CLEAR);
registerReceiver(screenLockReceiver, filter);
}
private class ScreenLockReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e(TAG, "onReceive:" + action);
if (TextUtils.isEmpty(action)) {
Log.e(TAG, "onReceive: is NULL");
return;
}
switch (action) {
case Intent.ACTION_BOOT_COMPLETED:
case Intent.ACTION_USER_PRESENT:
case Intent.ACTION_SCREEN_ON:
sendMsg(1);
break;
case Intent.ACTION_SCREEN_OFF:
case Intent.ACTION_SHUTDOWN:
case Intent.ACTION_FACTORY_RESET:
case Intent.ACTION_MASTER_CLEAR:
sendMsg(2);
break;
default:
break;
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
NetworkUtils.unregisterNetworkStatusChangedListener(this);
closeConnect();
if (screenLockReceiver != null) {
unregisterReceiver(screenLockReceiver);
}
}
/**
* 初始化websocket连接
*/
private void initSocketClient() {
URI uri = URI.create(NetInterfaceManager.WEBSOCKET_URL);
// URI uri = URI.create("ws://echo.websocket.org");
// URI uri = URI.create("ws://123.207.136.134:9010/ajaxchattest");
client = new JWebSocketClient(uri) {
@Override
public void onMessage(String message) {
Logutils.i("JWebSocketClientService", "收到服务器发来的消息:" + message);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
super.onOpen(handshakedata);
Logutils.i("JWebSocketClientService", "websocket连接成功");
sendMsg(1);
}
@Override
public void onClose(int code, String reason, boolean remote) {
super.onClose(code, reason, remote);
Logutils.i("JWebSocketClientService", "websocket连接关闭");
// client.close();
// initSocketClient();
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
}
@Override
public void onError(Exception ex) {
super.onError(ex);
Logutils.i("JWebSocketClientService", "websocket连接错误:" + ex.getMessage());
// client.close();
// initSocketClient();
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
}
};
connect();
}
/**
* 连接websocket
*/
private void connect() {
new Thread() {
@Override
public void run() {
try {
//connectBlocking多出一个等待操作会先连接再发送否则未连接发送会报错
Logutils.i("JWebSocketClientService", "websocket链接中");
client.connectBlocking();
} catch (Exception e) {
Logutils.i("JWebSocketClientService", e.getMessage());
// e.printStackTrace();
}
}
}.start();
}
/**
* 发送消息
*/
public void sendMsg() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("sn", Utils.getSerial());
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (!pm.isScreenOn()) {
jsonObject.put("online", 2);
//熄屏状态
} else {
jsonObject.put("online", 1);
}
if (null != client) {
Logutils.i("JWebSocketClientService", "发送的消息:" + jsonObject.toJSONString());
client.send(jsonObject.toJSONString());
}
}
public void sendMsg(int state) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("sn", Utils.getSerial());
jsonObject.put("online", state);
try {
if (null != client) {
Logutils.i("JWebSocketClientService", "发送的消息:" + jsonObject.toJSONString());
client.send(jsonObject.toJSONString());
} else {
Logutils.i("JWebSocketClientService", "未连接");
}
} catch (Exception e) {
Log.e(TAG, "sendMsg: " + e.getMessage());
}
}
/**
* 断开连接
*/
private void closeConnect() {
try {
if (null != client) {
client.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client = null;
}
}
// -------------------------------------websocket心跳检测------------------------------------------------
private static final long HEART_BEAT_RATE = 30 * 1000;//每隔50秒进行一次对长连接的心跳检测
private Handler mHandler = new Handler();
private Runnable heartBeatRunnable = new Runnable() {
@Override
public void run() {
Logutils.i("JWebSocketClientService", "心跳包检测websocket连接状态");
if (client != null) {
if (client.isOpen()) {
Logutils.i("JWebSocketClientService", "websocket已连接");
sendMsg();
} else if (client.isClosed()) {
Logutils.i("JWebSocketClientService", "websocket重连中");
reconnectWs();
}
} else {
//如果client已为空重新初始化连接
client = null;
initSocketClient();
}
//每隔一定的时间,对长连接进行一次心跳检测
mHandler.postDelayed(this, HEART_BEAT_RATE);
}
};
/**
* 开启重连
*/
private void reconnectWs() {
mHandler.removeCallbacks(heartBeatRunnable);
new Thread() {
@Override
public void run() {
try {
Logutils.i("JWebSocketClientService", "开启重连");
client.reconnectBlocking();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}