package com.gh.gamecenter; import android.app.Dialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.NotificationCompat; import android.support.v4.util.ArrayMap; import android.text.Html; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.gh.base.AppController; import com.gh.base.BaseFragmentActivity; import com.gh.common.constant.Config; import com.gh.common.constant.Constants; import com.gh.common.util.DataUtils; import com.gh.common.util.DialogUtils; import com.gh.common.util.FileUtils; import com.gh.common.util.MD5Utils; import com.gh.common.util.NetworkUtils; import com.gh.common.util.PackageUtils; import com.gh.common.util.PlatformUtils; import com.gh.common.util.RandomUtils; import com.gh.common.util.RunningUtils; import com.gh.common.util.SpeedUtils; import com.gh.common.util.TimestampUtils; import com.gh.common.util.Utils; import com.gh.download.DataWatcher; import com.gh.download.DownloadEntity; import com.gh.download.DownloadManager; import com.gh.download.DownloadStatus; import com.gh.gamecenter.db.info.ConcernInfo; import com.gh.gamecenter.db.info.GameInfo; import com.gh.gamecenter.db.info.SuspectedGameInfo; import com.gh.gamecenter.entity.ApkEntity; import com.gh.gamecenter.entity.AppEntity; import com.gh.gamecenter.entity.GameEntity; import com.gh.gamecenter.entity.GameUpdateEntity; import com.gh.gamecenter.eventbus.EBDownloadStatus; import com.gh.gamecenter.eventbus.EBPackage; import com.gh.gamecenter.eventbus.EBPutUrl; import com.gh.gamecenter.eventbus.EBShowDialog; import com.gh.gamecenter.eventbus.EBSkip; import com.gh.gamecenter.eventbus.EBTopStatus; import com.gh.gamecenter.eventbus.EBUISwitch; import com.gh.gamecenter.game.Game1Fragment; import com.gh.gamecenter.game.GameFragment; import com.gh.gamecenter.manager.ConcernManager; import com.gh.gamecenter.manager.DataCollectionManager; import com.gh.gamecenter.manager.FilterManager; import com.gh.gamecenter.manager.GameManager; import com.gh.gamecenter.manager.PackageManager; import com.gh.gamecenter.manager.SuspectedGameManager; import com.gh.gamecenter.news.NewsFragment; import com.gh.gamecenter.personal.PersonalFragment; import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest; import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.lang.reflect.Type; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import de.greenrobot.event.EventBus; /** * * @author 温冠超 * @email 294299195@qq.com * @update 2015-8-11 * @des 项目的主Activity,3个Fragment都嵌入在这里。 */ public class MainActivity extends BaseFragmentActivity implements OnClickListener { public static ArrayMap uninstallMap; public static String searchHint; private GameFragment gameFragment; private NewsFragment newsFragment; private PersonalFragment personalFragment; private LinearLayout home1Layout, home2Layout, home3Layout; private ImageView home1Image, home2Image, home3Image; private TextView home1Title, home2Title, home3Title; private SharedPreferences sp; private ArrayMap entryMap; private int currentTab; private boolean isDestroy = false; private boolean isShowDownload = false; private Dialog dialog; private ProgressBar app_pb_progress; private TextView app_tv_speed; private TextView app_tv_percent; private TextView app_btn_cancel; private AppEntity appEntity; // 黄壮华 添加观察者 修改2015/8/15 private DataWatcher dataWatcher = new DataWatcher() { @Override public void onDataChanged(DownloadEntity downloadEntity) { // 链接被劫持 if (DownloadStatus.hijack.equals(downloadEntity.getStatus())) { processHijack(downloadEntity); return; } if (downloadEntity.getName().contains("光环助手") && isShowDownload) { processGhAssistDownload(downloadEntity); } if (DownloadStatus.done.equals(downloadEntity.getStatus())) { if (downloadEntity.getName().contains("光环助手")) { DataUtils.onEvent(MainActivity.this, "软件更新", "下载完成"); startActivity(PackageUtils.getInstallIntent(downloadEntity.getPath())); if (appEntity != null && appEntity.isIs_force()) { finish(); } } else { Map kv = new HashMap<>(); kv.put("版本", downloadEntity.getPlatform()); kv.put("状态", "下载完成"); String entrance = downloadEntity.getEntrance(); if (downloadEntity.isUpdate()) { DataUtils.onEvent(MainActivity.this, "游戏更新", downloadEntity.getName(), kv); } else { DataUtils.onEvent(MainActivity.this, "游戏下载", downloadEntity.getName(), kv); Map kv2 = new HashMap<>(); kv2.put("版本", downloadEntity.getPlatform()); kv2.put("状态", "下载完成"); kv2.put("位置", entrance + "-完成"); DataUtils.onEvent(MainActivity.this, "游戏下载位置", downloadEntity.getName(), kv2); } if (downloadEntity.isPluggable()) { Map kv6 = new HashMap<>(); kv6.put("下载", "下载完成"); kv6.put("版本", downloadEntity.getPlatform()); DataUtils.onEvent(MainActivity.this, "插件化", downloadEntity.getName(), kv6); } Map map = new HashMap<>(); map.put("game", downloadEntity.getName()); if (downloadEntity.isPluggable()) { map.put("method", "插件化"); } else { map.put("method", "正常"); } map.put("platform", PlatformUtils.getInstance(getApplicationContext()) .getPlatformName(downloadEntity.getPlatform())); map.put("status", "完成"); map.put("location", downloadEntity.getLocation()); map.put("from", entrance); map.put("network", NetworkUtils.getConnectedType(MainActivity.this)); map.put("createdOn", System.currentTimeMillis() / 1000); DataCollectionManager.onEvent(MainActivity.this, "download", map); entryMap.put(PackageUtils.getPackageNameByPath( getApplicationContext(), downloadEntity.getPath()), downloadEntity .getUrl()); if (RunningUtils.isApplicationBroughtToBackground(getApplicationContext())) { if (downloadEntity.isPluggable()) { NotificationManager nManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); String path = downloadEntity.getPath(); Intent intent = new Intent(); intent.putExtra("path", path); intent.setAction("com.gh.gamecenter.UNINSTALL"); PendingIntent pendingIntent = PendingIntent .getBroadcast(MainActivity.this, 0, intent, PendingIntent.FLAG_ONE_SHOT); String platform = PlatformUtils .getInstance(getApplicationContext()) .getPlatformName(downloadEntity.getPlatform()); String title = downloadEntity.getName() + " - " + platform; Notification notification = new NotificationCompat.Builder( MainActivity.this) .setSmallIcon(R.drawable.logo) .setTicker(title) .setContentTitle(title) .setContentText("下载完成,点击继续插件化。") .setContentIntent(pendingIntent) .build(); notification.defaults = Notification.DEFAULT_SOUND;// 添加系统默认声音 notification.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明当通知被用户点击时,通知将被清除。 nManager.notify( ((int) System.currentTimeMillis() / 1000), notification); uninstallMap.put(PackageUtils.getPackageNameByPath( getApplicationContext(), path), path); } } else { String platform = PlatformUtils.getInstance( getApplicationContext()) .getPlatformName( downloadEntity.getPlatform()); if (platform != null) { if (downloadEntity.isPluggable()) { EventBus.getDefault().post(new EBShowDialog("plugin", downloadEntity.getPath())); } else if (platform.equals("官方版")) { toast(downloadEntity.getName() + " - 下载完成"); } else { toast(downloadEntity.getName() + " - " + platform + " - 下载完成"); } } else { toast(downloadEntity.getName() + " - 下载完成"); } if (downloadEntity.isPluggable()) { if (sp.getBoolean("autoinstall", true)) { if (FileUtils.isEmptyFile(downloadEntity.getPath())) { toast("解析包错误"); } else { PackageManager manager = new PackageManager( getApplicationContext()); if (manager.launchSetup(downloadEntity.getPath())) { startActivity(PackageUtils .getInstallIntent(downloadEntity .getPath())); } else { // 记录自动弹出卸载框 // 弹出卸载提示框 EventBus.getDefault().post(new EBShowDialog("delete", downloadEntity.getPath())); } } } } } // 统计下载完成 uploadData(downloadEntity.getGameId(), downloadEntity.getPlatform()); } } else { Utils.log("It is already done!"); DataUtils.onEvent(MainActivity.this, "多次弹框数据", downloadEntity.getName() + "-" + downloadEntity.getPlatform()); } } }; private void processGhAssistDownload(DownloadEntity downloadEntity) { app_tv_speed.setText(String.format("%s(剩%s)", SpeedUtils.getSpeed(downloadEntity.getSpeed()), SpeedUtils.getRemainTime(downloadEntity.getSize(), downloadEntity.getProgress(), downloadEntity.getSpeed() * 1024))); app_pb_progress.setProgress((int) (downloadEntity.getPercent() * 10)); app_tv_percent.setText(downloadEntity.getPercent() + "%"); if (DownloadStatus.done.equals(downloadEntity.getStatus())) { DownloadManager.getInstance(getApplicationContext()) .cancel(downloadEntity.getUrl(), false); dialog.dismiss(); isShowDownload = false; } } private void processHijack(DownloadEntity downloadEntity) { // 删除任务 DownloadManager.getInstance(getApplicationContext()).cancel(downloadEntity.getUrl()); // 弹出提示框 EventBus.getDefault().post(new EBShowDialog("hijack")); //记录链接被劫持 Map map = new HashMap<>(); map.put("url", downloadEntity.getUrl()); map.put("game", downloadEntity.getName()); map.put("platform", downloadEntity.getPlatform()); map.put("createdOn", System.currentTimeMillis() / 1000); DataCollectionManager.onEvent(MainActivity.this, "hijack", map); } /* * 黄壮华 按连续按返回键两次才退出应用 */ private long[] mHits = new long[2]; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1); mHits[mHits.length - 1] = SystemClock.uptimeMillis(); if (mHits[0] >= (SystemClock.uptimeMillis() - 1000)) { finish(); } else { toast("再按一次就退出光环助手了哦"); return true; } } return super.onKeyDown(keyCode, event); } private Handler handler = new Handler(); @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("currentTab", currentTab); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 初始化gameMap DownloadManager.getInstance(this).initGameMap(); if (savedInstanceState != null) { currentTab = savedInstanceState.getInt("currentTab"); } else { currentTab = 0; } View contentView = View.inflate(this, R.layout.activity_main, null); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTheme(R.style.AppTheme); setTranslucentStatus(true); } setContentView(contentView); initViews(); setTabSelection(currentTab); uninstallMap = new ArrayMap<>(); entryMap = new ArrayMap<>(); getSearchHints(); sp = getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE); if (!sp.getBoolean("isNewsFirstLaunch", true) && sp.getBoolean("autoupdate", true)) { checkUpdate(); } if (sp.getBoolean("isNewsFirstLaunch", true)) { getPluginUpdate(); getDisclaimer(true); sp.edit().putBoolean("isNewsFirstLaunch", false).apply(); } else { getDisclaimer(false); handler.postDelayed(runnable, 500); } // 初始化PlatformUtils PlatformUtils.getInstance(getApplicationContext()); // 添加观察者 DownloadManager.getInstance(this).addObserver(dataWatcher); handler.postDelayed(new Runnable() { @Override public void run() { ArrayList concernList = new ArrayList<>(); ConcernManager concernManager = new ConcernManager(MainActivity.this); for (ConcernInfo entity : concernManager.getAllConcern()) { if (entity.isConcern()) { concernList.add(entity.getGameName()); } } Map map = new HashMap<>(); map.put("type", Build.MODEL); map.put("system", Build.VERSION.SDK_INT + "=" + Build.VERSION.RELEASE); map.put("install", PackageManager.getInstalledList()); map.put("concern", concernList); map.put("createdOn", System.currentTimeMillis() / 1000); DataCollectionManager.upsert(MainActivity.this, "user", map); } }, 1000); // //检查是否存在更新的dex包 // checkHotfix(); // 检查游戏更新 checkGameUpdate(); // 检查可插件化游戏 checkGamePlugin(); Log.e("TD_CHANNEL_ID", (String) PackageUtils.getMetaData(this, getPackageName(), "TD_CHANNEL_ID")); } private void checkGameUpdate() { ArrayList list = new ArrayList<>(); ConcernManager concernManager = new ConcernManager(this); List infos = concernManager.getInstalledGame(); for (ConcernInfo info : infos) { for (String packageName : info.getPackageNames().keySet()) { if (info.getPackageNames().get(packageName)) { list.add(packageName); } } } Comparator comparator = new Comparator() { @Override public int compare(String lhs, String rhs) { return lhs.compareTo(rhs); } }; Collections.sort(list, comparator); StringBuilder builder = new StringBuilder(); String packages; PackageManager.clearUpdateList(); for (int i = 0, sizei = (list.size() / 10) + 1; i < sizei; i++) { builder.delete(0, builder.length()); for (int j = i * 10, sizej = (i + 1) * 10 > list.size() ? list .size() : (i + 1) * 10; j < sizej; j++) { builder.append(list.get(j)); builder.append("-"); } if (builder.length() != 0) { packages = builder.substring(0, builder.length() - 1); JsonArrayExtendedRequest request = new JsonArrayExtendedRequest( Config.HOST + "v1d45/support/package/update?package=" + packages // Config.HOST + "v1d45/support/package/latest?package=" + packages , new Response.Listener() { @Override public void onResponse(JSONArray response) { Utils.log("getUpdateList=" + response.toString()); if (response.length() != 0) { Gson gson = new Gson(); Type listType = new TypeToken>() {}.getType(); ArrayList games = gson.fromJson(response.toString(), listType); GameUpdateEntity gameUpdateEntity; for (int i = 0; i < games.size(); i++) { gameUpdateEntity = games.get(i); // 判断是否gh_version是否相同 String gh_version = (String) PackageUtils .getMetaData(MainActivity.this, gameUpdateEntity.getPackageName(), "gh_version"); if (gh_version != null) { gh_version = gh_version.substring(2); // 判断gh_version是否相同 if (gh_version.equals(gameUpdateEntity.getGhVersion())) { // 判断version是否相同 String version = PackageUtils .getVersionByPackage(MainActivity.this, gameUpdateEntity.getPackageName()); if (version != null && version.equals(gameUpdateEntity.getVersion())) { // 版本相同,无需显示插件更新,继续查看是否有可更新的游戏包 games.remove(i); i--; } } } else { games.get(i).setPluggable(true); } } PackageManager.addUpdateList(games); EventBus.getDefault().post(new EBDownloadStatus("update")); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); AppController.addToRequestQueue(request, MainActivity.class); } } } private int count; private void addCount() { synchronized (MainActivity.class) { count++; } } private void checkGamePlugin() { ConcernManager concernManager = new ConcernManager(this); List infos = concernManager.getInstalledGame(); final int size = infos.size(); final List list = new ArrayList<>(); count = 0; for (ConcernInfo info : infos) { JsonObjectExtendedRequest request = new JsonObjectExtendedRequest( TimestampUtils.addTimestamp( Config.HOST + "v2d0/game/" + info.getId() + "/digest", Constants.GAME_CD), new Response.Listener() { @Override public void onResponse(JSONObject response) { Gson gson = new Gson(); GameEntity gameEntity = gson.fromJson(response.toString(), GameEntity.class); list.add(gameEntity); addCount(); if (count == size) { processPluginData(list); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { addCount(); if (count == size) { processPluginData(list); } } }); AppController.addToRequestQueue(request, Game1Fragment.class); } } private void processPluginData(List list) { if (list == null || list.isEmpty()) { return; } ConcernManager concernManager = new ConcernManager(this); PackageManager mPackageManager = new PackageManager(this); List infos = concernManager.getInstalledGame(); HashMap map; GameEntity gameEntity; for (ConcernInfo info : infos) { for (int i = 0, size = list.size(); i < size; i++) { gameEntity = list.get(i); if (gameEntity.getId().equals(info.getId()) && gameEntity.getTag() != null && gameEntity.getTag().size() != 0 && gameEntity.getApk() != null) { map = info.getPackageNames(); for (String key : map.keySet()) { if (map.get(key) && !mPackageManager.isSignature(key)) { for (ApkEntity apkEntity : gameEntity.getApk()) { if (apkEntity.getPackageName().equals(key)) { GameUpdateEntity gameUpdateEntity = new GameUpdateEntity(); gameUpdateEntity.setId(gameEntity.getId()); gameUpdateEntity.setIcon(gameEntity.getIcon()); gameUpdateEntity.setName(gameEntity.getName()); gameUpdateEntity.setPackageName(apkEntity.getPackageName()); gameUpdateEntity.setSize(apkEntity.getSize()); gameUpdateEntity.setVersion(apkEntity.getVersion()); gameUpdateEntity.setGhVersion(apkEntity.getGhVersion()); gameUpdateEntity.setUrl(apkEntity.getUrl()); gameUpdateEntity.setPlatform(apkEntity.getPlatform()); gameUpdateEntity.setEtag(apkEntity.getEtag()); gameUpdateEntity.setPluggable(true); gameUpdateEntity.setTag(gameEntity.getTag()); gameUpdateEntity.setBrief(gameEntity.getBrief()); PackageManager.addUpdate(gameUpdateEntity); break; } } GameManager manager = new GameManager(this); manager.addOrUpdate(gameEntity.getApk(), gameEntity.getId(), gameEntity.getName()); } } break; } } } EventBus.getDefault().post(new EBDownloadStatus("plugin")); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { FrameLayout main_content = (FrameLayout) findViewById(R.id.main_content); if (main_content.getPaddingBottom() == 0) { main_content.setPadding(0, 0, 0, findViewById(R.id.main_ll_bottom).getHeight()); } } } private void checkHotfix() { String version = PackageUtils.getVersion(getApplicationContext()); String TD_CHANNEL_ID = (String) PackageUtils.getMetaData(this, getPackageName(), "TD_CHANNEL_ID"); String url = "http://api.ghzhushou.com/v1d45/hotfix?channel=" + TD_CHANNEL_ID + "&version=" + version; JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(url, new Response.Listener() { @Override public void onResponse(JSONArray response) { Utils.log("hotfix = " + response.toString()); try { for (int i = 0; i < response.length(); i++) { JSONObject jsonObject = response.getJSONObject(i); String clazz = jsonObject.getString("class"); final String url = jsonObject.getString("url"); String fileName = url.substring(url.lastIndexOf("/")); File directory = new File(getFilesDir().getAbsolutePath() + File.separator + "hotfix"); if (!directory.exists() || !directory.isDirectory()) { directory.mkdirs(); } File file = new File(directory.getAbsolutePath() + File.separator + fileName); if (file.exists()) { break; } //下载文件 final String savePath = file.getAbsolutePath(); new Thread(){ @Override public void run() { try { FileUtils.downloadFile(url, savePath); } catch (IOException e) { e.printStackTrace(); } Utils.log(savePath + " download success"); } }.start(); //存储class sp.edit().putString(file.getName(),clazz).apply(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Utils.log("hotfix = " + error.toString()); } }); AppController.addToRequestQueue(request, MainActivity.class); } // 获取免责声明 private void getDisclaimer(final boolean isFirst) { JsonObjectExtendedRequest request = new JsonObjectExtendedRequest( Config.HOST + "v2/disclaimer", new Response.Listener() { @Override public void onResponse(JSONObject response) { Utils.log(response.toString()); if (!isDestroy) { try { boolean isShow = response.getBoolean("isShow"); sp.edit().putBoolean("isShowDisclaimer", isShow).apply(); if (isShow) { String content = response.getString("content"); sp.edit().putString("disclaimer", content).apply(); if (isFirst) { DialogUtils.showDisclaimerDialog(MainActivity.this, content); } } } catch (JSONException e) { e.printStackTrace(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Utils.log(error.toString()); sp.edit().putBoolean("isShowDisclaimer", false).apply(); } }); AppController.addToRequestQueue(request, MainActivity.class); } private Class intentClass(String to) { try { return Class.forName("com.gh.gamecenter." + to); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } Runnable runnable = new Runnable() { @Override public void run() { String to = getIntent().getExtras().getString("to"); if(!TextUtils.isEmpty(to)){ Intent toIntent = new Intent(getApplicationContext(), intentClass(to)); if ("NewsDetailActivity".equals(to)) { toIntent.putExtra("newsId", getIntent().getExtras().getString("newsId")); toIntent.putExtra("entrance", getIntent().getExtras().getString("entrance")); } else if("DownloadManagerActivity".equals(to)) { toIntent.putExtra("packageName" , getIntent().getExtras().getString("packageName")); toIntent.putExtra("currentItem" , 1); } else if ("GameDetailActivity".equals(to)) { toIntent.putExtra("gameId", getIntent().getExtras().getString("gameId")); toIntent.putExtra("entrance", getIntent().getExtras().getString("entrance")); } else if ("SubjectActivity".equals(to)) { toIntent.putExtra("id", getIntent().getExtras().getString("id")); toIntent.putExtra("name", getIntent().getExtras().getString("name")); toIntent.putExtra("order", getIntent().getExtras().getBoolean("order")); } else if ("ViewImageActivity".equals(to)) { toIntent.putExtra("urls" , getIntent().getExtras().getStringArrayList("urls")); toIntent.putExtra("current" , getIntent().getExtras().getInt("current",0)); toIntent.putExtra("ScaleType" , getIntent().getExtras().getString("ScaleType")); } startActivity(toIntent); } else { String from = getIntent().getStringExtra("from"); if (!TextUtils.isEmpty(from)) { if (from.equals("plugin")) { String packageName = getIntent().getStringExtra( "packageName"); Intent intent = new Intent(MainActivity.this, DownloadManagerActivity.class); intent.putExtra("currentItem", 1); intent.putExtra("packageName", packageName); startActivity(intent); } else if (from.equals("mipush_news")) { Intent intent = new Intent(MainActivity.this, NewsDetailActivity.class); intent.putExtra("entrance", "小米推送"); intent.putExtra("entity", getIntent().getSerializableExtra("entity")); startActivity(intent); } else if (from.equals("mipush_new_game")) { Intent intent = new Intent(MainActivity.this, GameDetailActivity.class); intent.putExtra("entrance", "小米推送"); startActivity(intent); } else if (from.equals("mipush_plugin")) { try { JSONObject jsonObject = new JSONObject(getIntent() .getStringExtra("data")); JSONArray jsonArray = jsonObject.getJSONArray("apk"); ArrayList list = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject apk = jsonArray.getJSONObject(i); String packageName = apk.getString("package"); if (PackageManager.isInstalled(packageName)) { // 判断是否gh_version是否相同 String gh_version = (String) PackageUtils .getMetaData(getApplicationContext(), packageName, "gh_version"); if (gh_version != null) { gh_version = gh_version.substring(2); // 判断gh_version是否相同 if (gh_version.equals(apk .getString("gh_version"))) { // 判断version是否相同 String version = PackageUtils .getVersionByPackage( getApplicationContext(), packageName); if (version != null && version.equals(apk .getString("version"))) { // 版本相同,无需显示插件更新,继续查看是否有可更新的游戏包 continue; } } } list.add(packageName); } } Intent intent = new Intent(MainActivity.this, DownloadManagerActivity.class); intent.putExtra("currentItem", 1); intent.putExtra("isPushIntent", true); startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } else if (from.equals("plugin_install")) { Intent intent = new Intent(MainActivity.this, DownloadManagerActivity.class); intent.putExtra("currentItem", 0); intent.putExtra("path", getIntent().getStringExtra("path")); startActivity(intent); } } } } }; private void getSearchHints() { final String url = Config.HOST + "v1d45/search/game/default"; JsonArrayExtendedRequest searchRequst = new JsonArrayExtendedRequest( url, new Response.Listener() { @Override public void onResponse(JSONArray response) { if (!isDestroy) { Type listType = new TypeToken>() {}.getType(); Gson gson = new Gson(); List searchHintList = gson.fromJson( response.toString(), listType); if (searchHintList != null && !searchHintList.isEmpty()) { if (searchHintList.size() == 1) { searchHint = searchHintList.get(0); } else { searchHint = searchHintList.get(RandomUtils.nextInt(searchHintList.size())); } EventBus.getDefault().post( new EBTopStatus("搜索", searchHintList .get(0))); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Utils.log("error = " + error.toString()); } }); AppController.addToRequestQueue(searchRequst, MainActivity.class); } private void checkUpdate() { String TD_CHANNEL_ID = (String) PackageUtils.getMetaData(this, getPackageName(), "TD_CHANNEL_ID"); String url = Config.HOST + "v2/version?version_name=" + PackageUtils.getVersion(getApplicationContext()) + "&channel=" + TD_CHANNEL_ID; JsonObjectExtendedRequest updateRequest = new JsonObjectExtendedRequest( url, new Response.Listener() { @Override public void onResponse(JSONObject response) { Utils.log("update=" + response.toString()); if (!isDestroy) { if (response.length() != 0) { Gson gson = new Gson(); appEntity = gson.fromJson(response.toString(), AppEntity.class); float version = Float.valueOf(appEntity .getVersion()); float currentVersion = Float.valueOf(PackageUtils .getVersion(getApplicationContext())); if (version > currentVersion) { // 光环助手 有更新 GameUpdateEntity game = new GameUpdateEntity(); game.setName("光环助手V" + appEntity.getVersion()); game.setPackageName(getPackageName()); game.setSize(appEntity.getSize()); game.setVersion(appEntity.getVersion()); game.setUrl(appEntity.getUrl()); game.setPlatform("官方版"); PackageManager.addUpdate(0, game); String updateMD5 = MD5Utils.getUpdateMD5( appEntity.getUrl(), appEntity.getContent()); if (appEntity.isIs_force()) { // 强制更新 showUpdateDialog(updateMD5); } else { // 非强制更新 if ("EVERY_TIME_OPEN".equals(appEntity .getAlet_type())) { // 每次都提示 showUpdateDialog(updateMD5); } else { // 一天提示一次 String showUpdateTime = sp .getString( "show_update_tiem", null); SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd", Locale .getDefault()); String today = format .format(new Date()); if (!today.equals(showUpdateTime)) { sp.edit() .putString( "show_update_tiem", today).apply(); showUpdateDialog(updateMD5); } } } } } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Utils.log("update=" + error.toString()); } }); AppController.addToRequestQueue(updateRequest, MainActivity.class); } private void showUpdateDialog(final String md5) { final Dialog updateDialog = new Dialog(this); View view = View.inflate(this, R.layout.app_update_hint_dialog, null); TextView content = (TextView) view.findViewById(R.id.updeta_content); content.setText(Html.fromHtml(appEntity.getContent())); TextView versison = (TextView) view.findViewById(R.id.update_app_version); versison.setText(String.format("光环助手V%s更新内容:",appEntity.getVersion())); TextView size = (TextView) view.findViewById(R.id.update_app_size); size.setText(String.format("大小:%s", appEntity.getSize())); if (appEntity.isIs_force()) { updateDialog.setCanceledOnTouchOutside(false); updateDialog.setCancelable(false); } view.findViewById(R.id.update_cannel).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { if (appEntity.isIs_force()) { finish(); } else { updateDialog.dismiss(); } } }); view.findViewById(R.id.updeta_confirm).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { updateDialog.dismiss(); String path = FileUtils.getDownloadPath( MainActivity.this, "光环助手V" + appEntity.getVersion() + "_" + md5 + ".apk"); File file = new File(path); if (file.exists() && file.length() > 0) { startActivity(PackageUtils.getInstallIntent(path)); } else { DataUtils.onEvent(MainActivity.this, "软件更新", "下载开始"); showDownloadDialog(md5); } } }); updateDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); updateDialog.setContentView(view); updateDialog.show(); } private void showDownloadDialog(String md5) { dialog = new Dialog(this); dialog.setCanceledOnTouchOutside(false); dialog.setCancelable(false); dialog.closeOptionsMenu(); View view = View.inflate(this, R.layout.app_updating_dialog, null); app_pb_progress = (ProgressBar) view.findViewById(R.id.app_pb_progress); app_tv_speed = (TextView) view.findViewById(R.id.app_tv_speed); app_tv_percent = (TextView) view.findViewById(R.id.app_tv_percent); app_btn_cancel = (TextView) view.findViewById(R.id.app_btn_cancel); app_btn_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { DownloadManager.getInstance(getApplicationContext()).cancel( appEntity.getUrl()); if (appEntity.isIs_force()) { finish(); } else { dialog.dismiss(); isShowDownload = false; } } }); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(view); dialog.show(); isShowDownload = true; String path = FileUtils.getDownloadPath(MainActivity.this, "光环助手V" + appEntity.getVersion() + "_" + md5 + ".apk"); File file = new File(path); if (file.exists()) { file.delete(); } DownloadEntity downloadEntity = new DownloadEntity(); downloadEntity.setUrl(appEntity.getUrl()); downloadEntity.setName("光环助手V" + appEntity.getVersion()); downloadEntity.setPath(path); downloadEntity.setPlatform("官方版"); DownloadManager.getInstance(getApplicationContext()).cancel( downloadEntity.getUrl(), false); DownloadManager.getInstance(getApplicationContext()).pauseAll(); DownloadManager.getInstance(getApplicationContext()).add(downloadEntity); } // 获取META-INF中的plugin_update 文件,判断是否从游戏插件中下载的app,是则获取游戏id,启动游戏更新,下载该游戏 private void getPluginUpdate() { ApplicationInfo appinfo = getApplicationInfo(); String sourceDir = appinfo.sourceDir; ZipFile zipfile = null; try { zipfile = new ZipFile(sourceDir); Enumeration entries = zipfile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = ((ZipEntry) entries.nextElement()); String entryName = entry.getName(); if (entryName.contains("gh_assist")) { String packageName = entryName.substring(entryName .lastIndexOf("_") + 1); Intent intent = new Intent(MainActivity.this, DownloadManagerActivity.class); intent.putExtra("currentItem", 1); intent.putExtra("packageName", packageName); startActivity(intent); break; } } } catch (IOException e) { e.printStackTrace(); } finally { if (zipfile != null) { try { zipfile.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void initViews() { home1Layout = (LinearLayout) findViewById(R.id.main_ll_game); home2Layout = (LinearLayout) findViewById(R.id.main_ll_news); home3Layout = (LinearLayout) findViewById(R.id.main_ll_personal); home1Image = (ImageView) findViewById(R.id.main_iv_game); home2Image = (ImageView) findViewById(R.id.main_iv_news); home3Image = (ImageView) findViewById(R.id.main_iv_personal); home1Title = (TextView) findViewById(R.id.main_tv_game); home2Title = (TextView) findViewById(R.id.main_tv_news); home3Title = (TextView) findViewById(R.id.main_tv_personal); home1Layout.setOnClickListener(this); home2Layout.setOnClickListener(this); home3Layout.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.main_ll_game: EventBus.getDefault().post(new EBUISwitch("MainActivity", 0)); setTabSelection(0); break; case R.id.main_ll_news: EventBus.getDefault().post(new EBUISwitch("MainActivity", 1)); setTabSelection(1); break; case R.id.main_ll_personal: EventBus.getDefault().post(new EBUISwitch("MainActivity", 2)); setTabSelection(2); break; default: break; } } private void setTabSelection(int index) { clearSelection(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); hideFragments(transaction); switch (index) { case 0: home1Image.setImageResource(R.drawable.home1_selected); home1Title.setTextColor(getResources().getColor(R.color.theme)); if (gameFragment == null) { List list = getSupportFragmentManager().getFragments(); if (list != null) { for (Fragment fragment : list) { if (fragment.getClass().equals(GameFragment.class)) { gameFragment = (GameFragment) fragment; transaction.show(gameFragment); break; } } } if (gameFragment == null) { gameFragment = new GameFragment(); transaction.add(R.id.main_content, gameFragment); } } else { transaction.show(gameFragment); } currentTab = 0; break; case 1: home2Image.setImageResource(R.drawable.home2_selected); home2Title.setTextColor(getResources().getColor(R.color.theme)); if (newsFragment == null) { List list = getSupportFragmentManager().getFragments(); if (list != null) { for (Fragment fragment : list) { if (fragment.getClass().equals(NewsFragment.class)) { newsFragment = (NewsFragment) fragment; transaction.show(newsFragment); break; } } } if (newsFragment == null) { newsFragment = new NewsFragment(); transaction.add(R.id.main_content, newsFragment); } } else { transaction.show(newsFragment); } currentTab = 1; break; case 2: home3Image.setImageResource(R.drawable.home3_selected); home3Title.setTextColor(getResources().getColor(R.color.theme)); if (personalFragment == null) { List list = getSupportFragmentManager().getFragments(); if (list != null) { for (Fragment fragment : list) { if (fragment.getClass().equals(PersonalFragment.class)) { personalFragment = (PersonalFragment) fragment; transaction.show(personalFragment); break; } } } if (personalFragment == null) { personalFragment = new PersonalFragment(); transaction.add(R.id.main_content, personalFragment); } } else { transaction.show(personalFragment); } currentTab = 2; break; default: break; } transaction.commit(); } /** * 清除掉所有的选中状态。 */ private void clearSelection() { home1Image.setImageResource(R.drawable.home1_unselected); home2Image.setImageResource(R.drawable.home2_unselected); home3Image.setImageResource(R.drawable.home3_unselected); home1Title.setTextColor(getResources().getColor(R.color.title)); home2Title.setTextColor(getResources().getColor(R.color.title)); home3Title.setTextColor(getResources().getColor(R.color.title)); } /** * 将所有的Fragment都置为隐藏状态。 */ private void hideFragments(FragmentTransaction transaction) { if (personalFragment != null) { transaction.hide(personalFragment); } if (gameFragment != null) { transaction.hide(gameFragment); } if (newsFragment != null) { transaction.hide(newsFragment); } List list = getSupportFragmentManager().getFragments(); if (list != null) { for (Fragment fragment : list) { transaction.hide(fragment); } } } private void uploadData(String id, String platform) { HashMap params = new HashMap<>(); params.put("game", id); params.put("platform", platform); JSONObject jsonObject = new JSONObject(params); JsonObjectExtendedRequest request = new JsonObjectExtendedRequest( Method.POST, Config.HOST + "v2/stat/download", jsonObject.toString(), new Response.Listener() { @Override public void onResponse(JSONObject response) { Utils.log("download = " + response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Utils.log("download = " + error); if (error.networkResponse != null) { Utils.log("download = " + new String(error.networkResponse.data)); } } }); AppController.addToRequestQueue(request, MainActivity.class); } public void onEventMainThread(EBSkip skip) { if ("GameFragment".equals(skip.getType())) { home1Layout.performClick(); EventBus.getDefault().post(new EBSkip("MainActivity", skip.getCurrentItem())); } } public void onEventMainThread(EBPutUrl url) { entryMap.put(url.getPackageName(), url.getUrl()); } public void onEventMainThread(EBPackage busFour) { String packageName = busFour.getPackageName(); // 添加进已安装map中 if ("安装".equals(busFour.getType())) { PackageManager.addInstalled(packageName); } else if ("卸载".equals(busFour.getType())) { PackageManager.removeInstalled(packageName); } if ("安装".equals(busFour.getType())) { String url = entryMap.get(packageName); if (url != null) { entryMap.remove(packageName); DownloadEntity downloadEntity = DownloadManager.getInstance( getApplicationContext()).get(url); if (downloadEntity != null && downloadEntity.isPluggable()) { Map kv6 = new HashMap<>(); kv6.put("安装或卸载", "安装完成"); DataUtils.onEvent(this, "插件化", downloadEntity.getName(), kv6); } // 删除数据库 和 文件 DownloadManager.getInstance(getApplicationContext()).cancel( url, sp.getBoolean("autodelete", true)); } } else if ("卸载".equals(busFour.getType())) { try { for (DownloadEntity downloadEntity : DownloadManager.getInstance( getApplicationContext()).getAll()) { if (downloadEntity.isPluggable() && packageName.equals(downloadEntity.getPackageName())) { Map kv6 = new HashMap<>(); kv6.put("安装或卸载", "卸载完成"); DataUtils.onEvent(this, "插件化", downloadEntity.getName(), kv6); break; } } } catch (Exception e) { e.printStackTrace(); } String path = uninstallMap.get(packageName); if (path != null) { uninstallMap.remove(packageName); startActivity(PackageUtils.getInstallIntent(path)); } } if ("安装".equals(busFour.getType())) { GameManager gameManager = new GameManager(getApplicationContext()); GameInfo gameEntity = gameManager.findGame(packageName); if (gameEntity != null) { ConcernManager concernManager = new ConcernManager( getApplicationContext()); concernManager.updateByEntity(gameEntity); } else { FilterManager filterManager = new FilterManager( getApplicationContext()); if (!filterManager.isFilter(packageName)) { SuspectedGameManager suspectedGameManager = new SuspectedGameManager( getApplicationContext()); suspectedGameManager.addGame(new SuspectedGameInfo( packageName, System.currentTimeMillis())); } } } else if ("卸载".equals(busFour.getType())) { FilterManager filterManager = new FilterManager( getApplicationContext()); if (!filterManager.isFilter(packageName)) { SuspectedGameManager suspectedGameManager = new SuspectedGameManager( getApplicationContext()); suspectedGameManager.deleteSuspectedGame(packageName); ConcernManager concernManager = new ConcernManager( getApplicationContext()); concernManager.updateByPackageName(packageName); } } if ("卸载".equals(busFour.getType())) { ArrayList list = PackageManager.getUpdateList(); GameUpdateEntity game; int index = -1; for (int i = 0, size = list.size(); i < size; i++) { game = list.get(i); if (!game.isPluggable()) { continue; } if (game.getPackageName().equals(packageName)) { index = i; break; } } if (index != -1) { PackageManager.removeUpdateList(packageName); } } Map map = new HashMap<>(); map.put("type", busFour.getType()); map.put("packageName", busFour.getPackageName()); map.put("createdOn", System.currentTimeMillis() / 1000); DataCollectionManager.onEvent(this, "inorunstall", map); } @Override public void finish() { // 上传数据 DataCollectionManager.getInstance(getApplicationContext()).statClickData(); super.finish(); } @Override protected void onDestroy() { super.onDestroy(); isDestroy = true; AppController.canclePendingRequests(GameFragment.class); AppController.canclePendingRequests(NewsFragment.class); DownloadManager.getInstance(this).removeObserver(dataWatcher); gameFragment = null; personalFragment = null; home1Layout = null; home2Layout = null; home3Layout = null; home1Image = null; home2Image = null; home3Image = null; home1Title = null; home2Title = null; home3Title = null; sp = null; entryMap = null; dialog = null; app_pb_progress = null; app_tv_speed = null; app_tv_percent = null; app_btn_cancel = null; appEntity = null; handler = null; dataWatcher = null; } }