package com.mjsheng.myappstore; import android.app.Activity; import android.content.BroadcastReceiver; 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.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.server.GuardService; import com.mjsheng.myappstore.server.InitJpushServer; import com.mjsheng.myappstore.server.StepService; import com.mjsheng.myappstore.utils.Configure; import com.mjsheng.myappstore.utils.MySQLData; 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.IOException; 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 activityList = new LinkedList(); 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(); } // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //8.0之后需要在 registerTimeReceiver(); // } ignoreBatteryOptimization(this); } /** * 忽略电池优化 */ 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 receiver receiver; //监听时间和日期变化 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); registerReceiver(receiver, filter); } Long time1 = 0L; Long time2 = 0L; public class receiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.e("fht", "receiver action:" + action); if (action.equals(Intent.ACTION_SCREEN_ON) || action.equals(Intent.ACTION_USER_PRESENT) ) { 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; } else { } long time = System.currentTimeMillis(); getLockState("2", String.valueOf(time)); } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { long time = System.currentTimeMillis(); getLockState("1", String.valueOf(time)); } } } 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() { @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", "30s后重新设置tags"); Observable.timer(30000, TimeUnit.MILLISECONDS) .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread()) .subscribe(new Action1() { @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", "30s后重新设置alias"); Observable.timer(30000, TimeUnit.MILLISECONDS) .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread()) .subscribe(new Action1() { @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() + "/ygj/"); downloadManager.getThreadPool().setCorePoolSize(5); } private void initUpdatePulgin(Context context) { CheckEntity checkEntity = new CheckEntity(); checkEntity.setMethod("POST"); checkEntity.setUrl(CommonDatas.UPDATE_URL); Map 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 list = null; List 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 lists) { StatisticsInfo statisticsInfo = new StatisticsInfo(getAppContext()); List list = null; List 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 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 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()); } }