Files
CubeAoleyunSN/app/src/main/java/com/mjsheng/myappstore/MyApplication.java
Administrator 48eaf5794e version:
update:2020.09.22
fix:修复强制安装应用为空时缓存了上次的管控信息
add:
2020-09-22 15:18:32 +08:00

975 lines
39 KiB
Java
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.mjsheng.myappstore;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadEntity;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PathUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.cookie.store.PersistentCookieStore;
import com.lzy.okserver.download.DownloadService;
import com.mjsheng.myappstore.Statistics.AppInformation;
import com.mjsheng.myappstore.Statistics.StatisticsInfo;
import com.mjsheng.myappstore.activity.MainActivity;
import com.mjsheng.myappstore.comm.CommonDatas;
import com.mjsheng.myappstore.jpush.TagAliasOperatorHelper;
import com.mjsheng.myappstore.network.HTTPInterface;
import com.mjsheng.myappstore.network.Network;
import com.mjsheng.myappstore.network.api.newapi.GetLockState;
import com.mjsheng.myappstore.receiver.BootReceiver;
import com.mjsheng.myappstore.receiver.NewAppReceiver;
import com.mjsheng.myappstore.server.GuardService;
import com.mjsheng.myappstore.server.InitJpushServer;
import com.mjsheng.myappstore.server.MyDownloadService;
import com.mjsheng.myappstore.server.StepService;
import com.mjsheng.myappstore.utils.Configure;
import com.mjsheng.myappstore.utils.MySQLData;
import com.mjsheng.myappstore.utils.SPUtils;
import com.mjsheng.myappstore.utils.ToastUtil;
import com.mjsheng.myappstore.utils.Utils;
import com.mjsheng.myappstore.utils.update.ToastTool;
import org.json.JSONArray;
import org.json.JSONObject;
import org.lzh.framework.updatepluginlib.UpdateConfig;
import org.lzh.framework.updatepluginlib.base.UpdateParser;
import org.lzh.framework.updatepluginlib.model.CheckEntity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Response;
import okhttp3.ResponseBody;
import rx.Observable;
import rx.functions.Action1;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
/**
* Created by Administrator on 2016/2/17 0017.
*/
//public class MyApplication extends MultiDexApplication implements Thread.UncaughtExceptionHandler {
public class MyApplication extends MultiDexApplication {
public static String userName = null;
private static final String TAG = "--MyApplication--";
public static Context context;
public static boolean LOOP_STOPING = false; //停止 循环
public static MainActivity mainActivity;
public static int ageType = 1;
private static int mSelectTimeLong = 10;
private static MyApplication instance;
private Date mStartTime;
private Date mEndTime;
private Calendar mCurrentCalendar = null;
private SimpleDateFormat mDateFormat = null;
private static List<Activity> activityList = new LinkedList();
private Handler mHandler;
private static AMapLocationClient locationClient = null;
public static Context getAppContext() {
return context;
}
// 单例模式中获取唯一的ExitApplication实例
public static MyApplication getInstance() {
if (null == instance) {
instance = new MyApplication();
}
return instance;
}
@Override
public void onCreate() {
super.onCreate();
Configuration config = getResources().getConfiguration();
int smallestScreenWidthDp = config.smallestScreenWidthDp;
Log.e("mjsheng", "smallestScreenWidthDp=" + smallestScreenWidthDp);
//by mjsheng 激活
MySQLData.SetData(this, CommonDatas.SP_USER_VIP, "1");
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
// .setDefaultFontPath("fonts/1234.ttf")
// .setDefaultFontPath("fonts/Roboto-RobotoRegular.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
);
// 设置开启日志,发布时请关闭日志
JPushInterface.setDebugMode(true);
JPushInterface.requestPermission(this);
// 初始化 JPush
//JPushInterface.init(this);
//解锁设备不需要初始化
context = getApplicationContext();
//Thread.setDefaultUncaughtExceptionHandler(this);
mDateFormat = new SimpleDateFormat("HH:mm");
initOKHttp();
//初始化升级框架
ToastTool.init(context);
initUpdatePulgin(context);
Aria.init(this);
Aria.get(this).getDownloadConfig().setMaxTaskNum(1);
Aria.get(this).getDownloadConfig().setConvertSpeed(true);
ToastUtil.init(this);
if (!BuildConfig.DEBUG) {
catchException();
}
mHandler = new Handler();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// 8.0之后需要在
registmNewAppReceiver();
startService(new Intent(this, InitJpushServer.class));
startService(new Intent(this, StepService.class));
startService(new Intent(this, GuardService.class));
startService(new Intent(this, MyDownloadService.class));
}
registerTimeReceiver();
// ignoreBatteryOptimization(this);
// try {
// Process exec = Runtime.getRuntime().exec(running);
// final InputStream is = exec.getInputStream();
// new LogThread(is).start();
// } catch (IOException e) {
//// e.printStackTrace();
// Log.e("第一个是Logcat", e.getMessage());
// }
initAmap();
}
public static AMapLocationClient getLocationClient() {
if (null == locationClient) {
initAmap();
}
return locationClient;
}
private static void initAmap() {
locationClient = new AMapLocationClient(context);
AMapLocationClientOption option = new AMapLocationClientOption();
option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
option.setNeedAddress(true);
//获取一次定位结果:
//该方法默认为false。
option.setOnceLocation(true);
//获取最近3s内精度最高的一次定位结果
//设置setOnceLocationLatest(boolean b)接口为true启动定位时SDK会返回最近3s内精度最高的一次定位结果。
// 如果设置其为truesetOnceLocation(boolean b)接口也会被设置为true反之不会默认为false。
option.setOnceLocationLatest(true);
locationClient.setLocationOption(option);
//设置定位模式为AMapLocationMode.Hight_Accuracy高精度模式。
//设置定位监听
locationClient.setLocationListener(new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
StringBuffer sb = new StringBuffer();
//errCode等于0代表定位成功其他的为定位失败具体的可以参照官网定位错误码说明
if (aMapLocation.getErrorCode() == 0) {
sb.append(aMapLocation.getAddress() + "\n");
SPUtils.put(context, "AmapAddress", aMapLocation.getAddress());
} else {
//定位失败
sb.append("定位失败" + "\n");
SPUtils.put(context, "AmapError", aMapLocation.getErrorInfo());
}
Log.e("addr", sb.toString());
}
});
//设置场景模式后最好调用一次stop再调用start以保证场景模式生效
locationClient.stopLocation();
locationClient.startLocation();
}
//第一个是Logcat 也就是我们想要获取的log日志
//第二个是 -s 也就是表示过滤的意思
//第三个就是 我们要过滤的类型 W表示warm ,我们也可以换成 D debug IinfoEerror等等
// String[] running = new String[]{"logcat", "-s", "adb logcat *: W"};
String[] running = new String[]{"logcat"};
String filePath = "/sdcard/Log/Log.txt";
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(filePath);
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
os = new FileOutputStream(filePath);
int len = 0;
byte[] buf = new byte[1024];
while (-1 != (len = is.read(buf))) {
os.write(buf, 0, len);
os.flush();
}
} catch (Exception e) {
Log.e("writelog", "read logcat process failed. message: "
+ e.getMessage());
} finally {
if (null != os) {
try {
os.close();
os = null;
} catch (IOException e) {
// Do nothing
}
}
}
}
}
/**
* 忽略电池优化
*/
private void ignoreBatteryOptimization(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
boolean hasIgnored = powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
// 判断当前APP是否有加入电池优化的白名单如果没有弹出加入电池优化的白名单的设置对话框。
if (!hasIgnored) {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
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);
}
//监听时间和日期变化
public void registerTimeReceiver() {
receiver = new receiver();
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(receiver, filter);
}
private receiver receiver;
Long time1 = 0L;
Long time2 = 0L;
Long time3 = 0L;
Long time4 = 0L;
public class receiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
Log.e("fht", "receiver action:" + action);
if (action.equals(Intent.ACTION_SCREEN_ON)) {
long time = System.currentTimeMillis();
getLockState("2", String.valueOf(time));
} else if (action.equals(Intent.ACTION_USER_PRESENT)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
/*在8.0以上 除了开机广播其他广播基本上没有用
*当静默安装升级时app不会被唤醒只有通过显示广播唤醒
* */
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent1 = new Intent(BootReceiver.BOOT_COMPLETED);
intent1.setComponent(new ComponentName("com.jiaoguanyi.store", "com.mjsheng.myappstore.receiver.BootReceiver"));
// 携带数据
// intent1.putExtra("test", "我是来测 A 应用的Android 8.0 系统静态广播的测试数据");
// 启动发送广播
sendBroadcast(intent1);
time2 = System.currentTimeMillis();
if ((time2 - time1) > 60 * 1000) {
//可能会多次触发1分钟之内不执行
//application中启动服务,startcommand执行会两次
startService(new Intent(context, InitJpushServer.class));
startService(new Intent(context, StepService.class));
startService(new Intent(context, GuardService.class));
time1 = time2;
}
}
}, 5000);
}
} else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
long time = System.currentTimeMillis();
getLockState("1", String.valueOf(time));
if (time3 - System.currentTimeMillis() >= 10000) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent intent1 = new Intent(BootReceiver.BOOT_COMPLETED);
intent1.setComponent(new ComponentName("com.jiaoguanyi.store", "com.mjsheng.myappstore.receiver.BootReceiver"));
sendBroadcast(intent1);
deleteScreenshots();
}
}
time3 = System.currentTimeMillis();
}
}, 10000);
} else if (action.equals("android.intent.action.FACTORY_RESET")
|| action.equals("android.intent.action.MASTER_CLEAR")
//MASTER_CLEAR 7.0可以监听
|| action.equals("android.intent.action.MASTER_CLEAR_NOTIFICATION")
|| action.equals("android.intent.action.FORCE_FACTORY_RESET")
) {
Log.e("receiver", "MASTER_CLEAR");
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
}
}
private void deleteScreenshots() {
Log.e("File", "deleteScreenshots");
String path = getExternalFilesDir("db").getAbsolutePath();
File file = new File(path);
File[] files = file.listFiles();
for (File f : files) {
if (f.isFile()) {
Log.e("File", f.getAbsolutePath());
f.delete();
}
}
}
private void getLockState(String status, String time) {
GetLockState getLockState = Network.getLockState();
getLockState.getLockState(Utils.getSerial(), status, time)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
try {
com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(responseBody.string());
int code = jsonObject.getInteger("code");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
public void onTagOperatorResult(JPushMessage jPushMessage) {
if (jPushMessage == null) {
return;
}
String s = "tags:\t";
int errorCode = jPushMessage.getErrorCode();
switch (errorCode) {
case 0:
Log.e("jiguangInterface", s + "Tag绑定成功");
break;
case 6001:
Log.e("jiguangInterface", s + "无效的设置");
break;
case 6005:
Log.e("jiguangInterface", s + "某一个 tag 字符串不合法");
ToastUtil.show("设备标签不合法,联系管理员修改\t" + "code:6005");
break;
case 6006:
Log.e("jiguangInterface", s + "某一个 tag 超长");
ToastUtil.show("设备标签过长,联系管理员修改\t" + "code:6006");
break;
case 6007:
Log.e("jiguangInterface", s + "tags 数量超出限制");
ToastUtil.show("设备标签数量超出限制,联系管理员修改\t" + "code:6007");
break;
case 6008:
Log.e("jiguangInterface", s + "tag 超出总长度限制");
ToastUtil.show("设备标签超出总长度限制,联系管理员修改\t" + "code:6008");
break;
case 6011:
Log.e("jiguangInterface", s + "短时间内操作过于频繁");
break;
case 6013:
Log.e("jiguangInterface", s + "用户设备时间轴异常");
ToastUtil.show("用户设备时间轴异常,修改后重新登陆\t" + "code:6013");
break;
case 6018:
Log.e("jiguangInterface", s + "Tags 过多");
ToastUtil.show("设备标签数量超出限制,联系管理员修改\t" + "code:6018");
break;
case 6021:
Log.e("jiguangInterface", s + "tags 操作正在进行中");
break;
//需要重新设置
case 6002:
Log.e("jiguangInterface", s + "设置超时,请重试");
setJpushTags();
break;
case 6014:
Log.e("jiguangInterface", s + "服务器繁忙,建议重试");
setJpushTags();
break;
case 6020:
Log.e("jiguangInterface", s + "建议过一段时间再设置");
setJpushTags();
break;
case 6024:
Log.e("jiguangInterface", s + "服务器内部错误");
setJpushTags();
break;
}
}
public static void setJpushTags() {
Log.e("jiguangInterface", "10s后重新设置tags");
Observable.timer(10000, TimeUnit.MILLISECONDS)
.observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
HTTPInterface.setJpushTags(context);
}
});
}
public void onAliasOperatorResult(JPushMessage jPushMessage) {
if (jPushMessage == null) {
return;
}
String s = "alias:\t";
int errorCode = jPushMessage.getErrorCode();
switch (errorCode) {
case 0:
Log.e("jiguangInterface", s + "Alias绑定成功");
break;
case 6001:
Log.e("jiguangInterface", s + "无效的设置");
break;
case 6011:
Log.e("jiguangInterface", s + "短时间内操作过于频繁");
break;
case 6013:
Log.e("jiguangInterface", s + "用户设备时间轴异常");
ToastUtil.show("用户设备时间轴异常,修改后重新登陆\t" + s + "code:6013");
break;
case 6022:
Log.e("jiguangInterface", s + "alias 操作正在进行中");
break;
//需要重新设置
case 6002:
Log.e("jiguangInterface", s + "设置超时,请重试");
setJpushAlias();
break;
case 6014:
Log.e("jiguangInterface", s + "服务器繁忙,建议重试");
setJpushAlias();
break;
case 6020:
Log.e("jiguangInterface", s + "建议过一段时间再设置");
setJpushAlias();
break;
case 6024:
Log.e("jiguangInterface", s + "服务器内部错误");
setJpushAlias();
break;
case 6017:
case 6027:
Log.e("jiguangInterface", s + "别名绑定的设备数超过限制");
clean();
setJpushAlias();
break;
}
}
public static void setJpushAlias() {
Log.e("jiguangInterface", "10s后重新设置alias");
Observable.timer(10000, TimeUnit.MILLISECONDS)
.observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
JPushInterface.setAlias(context, TagAliasOperatorHelper.sequence++, Utils.getSerial());
}
});
}
public void clean() {
//alias的绑定的设备超过10个但是alias应该是一个设备对应一个在重置设备后jpush的regid会变动所以需要清除
//https://docs.jiguang.cn/jpush/server/push/rest_api_v3_device/#_5
HTTPInterface.cleanJpushAlias(Utils.getSerial());
}
private boolean finished = false;
public boolean isFinished() {
return finished;
}
public void setFinished(boolean b) {
this.finished = b;
}
private void initOKHttp() {
//必须调用初始化
OkGo.init(this);
//以下都不是必须的,根据需要自行选择,一般来说只需要 debug,缓存相关,cookie相关的 就可以了
OkGo.getInstance()
// 打开该调试开关,打印级别INFO,并不是异常,是为了显眼,不需要就不要加入该行
// 最后的true表示是否打印okgo的内部异常一般打开方便调试错误
.debug("OkGo", Level.INFO, true)
//如果使用默认的 60秒,以下三行也不需要传
// .setConnectTimeout(3000) //全局的连接超时时间
// .setReadTimeOut(3000) //全局的读取超时时间
// .setWriteTimeOut(3000) //全局的写入超时时间
//可以全局统一设置缓存模式,默认是不使用缓存,可以不传,具体其他模式看 github 介绍 https://github.com/jeasonlzy/
.setCacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
//可以全局统一设置缓存时间,默认永不过期,具体使用方法看 github 介绍
.setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
//可以全局统一设置超时重连次数,默认为三次,那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0
.setRetryCount(4)
.setCookieStore(new PersistentCookieStore()) //cookie持久化存储如果cookie不过期则一直有效
//可以设置https的证书,以下几种方案根据需要自己设置 方法一:信任所有证书,不安全有风险
.setCertificates();
com.lzy.okserver.download.DownloadManager downloadManager = DownloadService.getDownloadManager();
// downloadManager.setTargetFolder(StorageUtils.getFileRoot(this));
downloadManager.setTargetFolder(PathUtils.getExternalDownloadsPath() + "/jgy/");
downloadManager.getThreadPool().setCorePoolSize(5);
}
private void initUpdatePulgin(Context context) {
CheckEntity checkEntity = new CheckEntity();
checkEntity.setMethod("POST");
checkEntity.setUrl(CommonDatas.UPDATE_URL);
Map<String, String> params = new HashMap<>();
params.put("package_name", CommonDatas.UPDATE_PKG);
params.put("key", Configure.HTTP_KEY);
checkEntity.setParams(params);
UpdateConfig.getConfig()
.setCheckEntity(checkEntity)
.setUpdateParser(new UpdateParser() {
@Override
public org.lzh.framework.updatepluginlib.model.Update parse(String response) throws Exception {
// Log.e("mjsehng", "下载嘻嘻嘻嘻嘻"+response);
org.lzh.framework.updatepluginlib.model.Update update = new org.lzh.framework.updatepluginlib.model.Update();
try {
JSONObject object = new JSONObject(response);
Integer code = object.optInt("code");
if (code == 200) {
JSONObject jsonObject = object.getJSONObject("data");
// 此apk包的下载地址
update.setUpdateUrl(jsonObject.optString("url"));
// 此apk包的版本号
update.setVersionCode(jsonObject.optInt("version_code"));
// 此apk包的版本名称
update.setVersionName(jsonObject.optString("version_name"));
// 此apk包的更新内容
update.setUpdateContent(jsonObject.optString("desc"));
//强制更新内容
if (jsonObject.optString("forced_update").equals("1")) {
update.setForced(true);
} else {
update.setForced(false);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return update;
}
});
}
// 添加Activity到容器中
public static void addActivity(Activity activity) {
activityList.add(activity);
}
// 遍历所有Activity并finish
public void exit() {
for (Activity activity : activityList) {
activity.finish();
}
}
public static void sendAppUsedTime(String random, String type) {
StatisticsInfo statisticsInfo = null;
if (type.equals("0")) {
statisticsInfo = new StatisticsInfo(getAppContext());
} else if (type.equals("1")) {
statisticsInfo = new StatisticsInfo(getAppContext(), StatisticsInfo.WEEK);
}
List<AppInformation> list = null;
List<AppInformation> localAppList = new ArrayList<>();
if (statisticsInfo != null) {
list = statisticsInfo.getShowList();
if (list != null && list.size() > 0) {
for (AppInformation appInformation : list) {
if (!Utils.isSystemApp(getAppContext(), appInformation.getPackageName())) {
localAppList.add(appInformation);
}
}
} else Log.e("fht", "今日没有打开的应用");
} else Log.e("fht", "获取信息失败");
JSONObject data = new JSONObject();
JSONArray appinfo = new JSONArray();
try {
if (localAppList.size() > 0) {
for (int i = 0; i < 5; i++) {
AppInformation information = localAppList.get(i);
JSONObject jsonObject = new JSONObject();
jsonObject.put("package", information.getPackageName());
jsonObject.put("use_time", (int) information.getUsedTimebyDay() / 1000);
appinfo.put(jsonObject);
}
data.put("data", appinfo);
}
} catch (Exception e) {
Log.e("fht", e.getMessage());
}
OkGo.post(Configure.SEND_USEDTIME)
.params("sn", Utils.getSerial())
.params("random", random)
.params("data", data.toString())
.execute(new StringCallback() {
@Override
public void onSuccess(String s, Call call, Response response) {
com.alibaba.fastjson.JSONObject object = JSON.parseObject(s);
int code = object.getInteger("code");
String msg = object.getString("msg");
Log.e("fht", "code:" + code + "," + msg);
}
@Override
public void onError(Call call, Response response, Exception e) {
super.onError(call, response, e);
Log.e("fht", e.getMessage());
}
});
}
private static long totalTime;
private static int totalTimes;
synchronized public static void setAPPUsage() {
StatisticsInfo statisticsInfo = new StatisticsInfo(getAppContext());
totalTime = statisticsInfo.getTotalTime();//全部时间
totalTimes = statisticsInfo.getTotalTimes();//全部次数
}
synchronized public static void setAPPUsage(List<String> lists) {
StatisticsInfo statisticsInfo = new StatisticsInfo(getAppContext());
List<AppInformation> list = null;
List<AppInformation> localAppList = new ArrayList<>();
totalTime = statisticsInfo.getTotalTime();//全部时间
totalTimes = statisticsInfo.getTotalTimes();//全部次数
list = statisticsInfo.getShowList();
if (list != null && list.size() > 0) {
for (AppInformation appInformation : list) {
if (lists.indexOf(appInformation.getPackageName()) != -1) {
localAppList.add(appInformation);
}
}
} else {
}
}
synchronized public void getWhitePackageList() {
OkGo.post(Configure.SET_WHITE_PACKAGE_LIST)
.params("sn", Utils.getSerial())
.params("key", Configure.HTTP_KEY)
.execute(new StringCallback() {
@Override
public void onSuccess(String s, Call call, Response response) {
com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(s);
int code = jsonObject.getInteger("code");
String msg = jsonObject.getString("msg");
String data = jsonObject.getString("data");
if (code == 200) {
com.alibaba.fastjson.JSONObject resultJson = JSON.parseObject(data);
String result = resultJson.getString("result");
writeAppPackageList(result);
// setAPPUsage(allList);
} else {
// setAPPUsage();
}
}
@Override
public void onError(Call call, Response response, Exception e) {
super.onError(call, response, e);
}
});
}
private void writeAppPackageList(String result) {
String appstore = "com.jiaoguanyi.appstore";
String store = "com.jiaoguanyi.store";
if (!TextUtils.isEmpty(result)) {
LogUtils.e(result);
if (!result.contains(appstore)) {
result = result + "," + appstore;
}
if (!result.contains(store)) {
result = result + "," + store;
}
Settings.System.putString(context.getContentResolver(), "qch_app_forbid", result);
Log.e("mjsheng", "qch_app_forbid :" + result);
} else {
Log.e("mjsheng", "writeAppPackageList is null:");
Settings.System.putString(context.getContentResolver(), "qch_app_forbid", appstore + "," + store);
}
}
private void catchException() {
Thread.setDefaultUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
Log.d("捕获异常子线程:", Thread.currentThread().getName() +
"在:" + e.getStackTrace()[0].getClassName());
}
}
);
//下面是新增方法!
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
while (true) {
try {
Looper.loop(); //会先执行这个方法,然后在执行下面的异常捕获方法!
} catch (Exception e) {
Log.d("捕获异常主线程:", Thread.currentThread().getName() + "在:" + e.getStackTrace()[0].getClassName());
e.printStackTrace();
}
}
}
});
}
// @Override
// public void uncaughtException(Thread thread, Throwable ex) {
//// Log.e(TAG, ex.getMessage(), new Exception(ex));
//// Utils.showToast(this, "程序出现异常,即将退出。。。");
//// try {
//// Thread.sleep(3000);
//// } catch (InterruptedException e) {
//// e.printStackTrace();
//// }
//// Intent i = getBaseContext().getPackageManager()
//// .getLaunchIntentForPackage(getBaseContext().getPackageName());
//// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//// startActivity(i);
//// //退出程序
//// android.os.Process.killProcess(android.os.Process.myPid());
//// System.exit(1);
//
// }
// static List<FileData> fileList = new ArrayList<>();
//
//
// static String packageName = "";
//
// public void setInstallIngPackageName(String packageNames) {
// packageName = packageNames;
// Log.e("fht", "正在安装:" + packageNames);
// }
//
// public String getInstallIngPackageName() {
// return packageName;
// }
//
// public void addFileData(FileData data) {
// fileList.add(data);
// updateList();
// }
//
// public void removeDate(String packageName) {
// if (fileList != null && fileList.size() > 0) {
// for (FileData data : fileList) {
// if (data.getPackageName().equals(packageName)) {
// fileList.remove(data);
// break;
// } else {
// Log.e("fht", "not found object");
// }
// }
// }
// setInstallIngPackageName("");
// if (fileList.size() > 0) {
// updateList();
// } else {
// Log.e("fht", "fileList为空");
// setInstallIngPackageName("");
// }
//
// }
//
// public void updateList() {
// if (getInstallIngPackageName().equals("") || ApkUtils.isAvailable(getAppContext(), packageName)) {
// if (fileList != null && fileList.size() > 0) {
// if (!fileList.get(0).getPackageName().equals("") || ApkUtils.isAvailable(getAppContext(), fileList.get(0).getPackageName())) {
// String s = packageName;
// ApkUtils.installApp(this, fileList.get(0).getFilePath());
// setInstallIngPackageName(fileList.get(0).getPackageName());
// } else {
// removeDate(fileList.get(0).getPackageName());
// Log.e("fht", "已安装");
// setInstallIngPackageName("");
// }
// } else {
// Log.e("fht", "任务为空");
// }
// } else {
// Log.e("fht", "安装中:" + packageName);
//
// }
// }
boolean isForecDownload = false;
public boolean isDownloading() {
return isForecDownload;
}
public void setDownloadState(boolean state) {
isForecDownload = state;
}
public void checkIsDownloading() {
List<DownloadEntity> list = Aria.download(this).getDRunningTask();
if (list == null || list.size() == 0) {
MyApplication.getInstance().setDownloadState(false);
} else {
MyApplication.getInstance().setDownloadState(true);
}
Log.e("MyApplication", "isDownloading=" + MyApplication.getInstance().isDownloading());
}
@Override
public void onTerminate() {
super.onTerminate();
//销毁时需要销毁定位client
if (null != locationClient) {
locationClient.onDestroy();
}
}
}