Files
assistant-android/app/src/main/java/com/gh/gamecenter/MainActivity.java
huangzhuanghua 6ec976ccb6 项目整理
2016-07-06 09:37:33 +08:00

1259 lines
41 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

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.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.Spanned;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
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.util.DataUtils;
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.Utils;
import com.gh.download.DataWatcher;
import com.gh.download.DownloadEntry;
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.AppEntity;
import com.gh.gamecenter.entity.GameUpdateEntity;
import com.gh.gamecenter.eventbus.EBPackage;
import com.gh.gamecenter.eventbus.EBPutUrl;
import com.gh.gamecenter.eventbus.EBRedDot;
import com.gh.gamecenter.eventbus.EBShowDialog;
import com.gh.gamecenter.eventbus.EBTopState;
import com.gh.gamecenter.eventbus.EBUISwitch;
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.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 项目的主Activity3个Fragment都嵌入在这里。
*/
public class MainActivity extends BaseFragmentActivity implements
OnClickListener {
public static ArrayMap<String, String> uninstallMap;
public static String searchHint;
private NewsFragment newsFragment;
private GameFragment pluginFragmentActivity;
private PersonalFragment home3Fragment;
private View home1Layout, home2Layout, home3Layout;
private ImageView home1Image, home2Image, home3Image;
private TextView home1Title, home2Title, home3Title;
private SharedPreferences sp;
private ArrayMap<String, String> entryMap;
private ArrayMap<String, String> doneMap;
private int currentTab;
private boolean isFirst;
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(
HashMap<String, DownloadEntry> downloadingEntries) {
for (Map.Entry<String, DownloadEntry> entry : downloadingEntries
.entrySet()) {
final DownloadEntry downloadEntry = entry.getValue();
// 链接被劫持
if (DownloadStatus.hijack.equals(downloadEntry.getStatus())) {
// 删除任务
DownloadManager.getInstance(getApplicationContext()).cancel(downloadEntry.getUrl());
// 弹出提示框
EventBus.getDefault().post(new EBShowDialog("hijack"));
//记录链接被劫持
Map<String, Object> map = new HashMap<String, Object>();
map.put("url", downloadEntry.getUrl());
map.put("game", downloadEntry.getName());
map.put("platform", downloadEntry.getMeta().get("platform"));
map.put("createdOn", System.currentTimeMillis() / 1000);
DataCollectionManager.onEvent(MainActivity.this, "hijack", map);
continue;
}
if (downloadEntry.getName().contains("光环助手") && isShowDownload) {
app_tv_speed.setText(SpeedUtils.getSpeed(downloadEntry.getSpeed())
+ "(剩" + SpeedUtils.getRemainTime(downloadEntry.getSize(),
downloadEntry.getProgress(),
downloadEntry.getSpeed() * 1024) + ")");
app_pb_progress.setProgress((int) (downloadEntry
.getPercent() * 10));
app_tv_percent.setText(downloadEntry.getPercent() + "%");
if (DownloadStatus.done.equals(downloadEntry.getStatus())) {
DownloadManager.getInstance(getApplicationContext())
.cancel(downloadEntry.getUrl(), false);
dialog.dismiss();
isShowDownload = false;
}
}
if (DownloadStatus.done.equals(downloadEntry.getStatus())) {
if (doneMap.get(downloadEntry.getUrl()) == null) {
doneMap.put(downloadEntry.getUrl(), "done");
if (downloadEntry.getName().contains("光环助手")) {
DataUtils.onEvent(MainActivity.this, "软件更新", "下载完成");
startActivity(PackageUtils
.getInstallIntent(downloadEntry.getPath()));
if (appEntity != null && appEntity.isIs_force()) {
finish();
}
} else {
Map<String, Object> kv = new HashMap<String, Object>();
kv.put("版本", downloadEntry.getMeta()
.get("platform"));
kv.put("状态", "下载完成");
String isUpdate = downloadEntry.getMeta().get(
"isUpdate");
String entrance = downloadEntry.getMeta().get(
"entrance");
if (isUpdate != null && "true".equals(isUpdate)) {
DataUtils.onEvent(MainActivity.this, "游戏更新",
downloadEntry.getName(), kv);
} else {
DataUtils.onEvent(MainActivity.this, "游戏下载",
downloadEntry.getName(), kv);
Map<String, Object> kv2 = new HashMap<String, Object>();
kv2.put("版本",
downloadEntry.getMeta().get("platform"));
kv2.put("状态", "下载完成");
kv2.put("位置", entrance + "-完成");
DataUtils.onEvent(MainActivity.this, "游戏下载位置",
downloadEntry.getName(), kv2);
}
if (downloadEntry.getMeta().get("isPlugin") != null) {
Map<String, Object> kv6 = new HashMap<String, Object>();
kv6.put("下载", "下载完成");
kv6.put("版本",
downloadEntry.getMeta().get("platform"));
DataUtils.onEvent(MainActivity.this, "插件化",
downloadEntry.getName(), kv6);
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("game", downloadEntry.getName());
if (downloadEntry.getMeta().get("isPlugin") != null) {
map.put("method", "插件化");
} else {
map.put("method", "正常");
}
map.put("platform",
PlatformUtils.getInstance(
getApplicationContext())
.getPlatformName(
downloadEntry.getMeta()
.get("platform")));
map.put("status", "完成");
map.put("location",
downloadEntry.getMeta().get("location"));
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(),
downloadEntry.getPath()), downloadEntry
.getUrl());
if (RunningUtils
.isApplicationBroughtToBackground(getApplicationContext())) {
if (downloadEntry.getMeta().get("isPlugin") != null) {
NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String path = downloadEntry.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(
downloadEntry.getMeta()
.get("platform"));
String title = downloadEntry.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(
downloadEntry.getMeta().get(
"platform"));
if (platform != null) {
String msg = downloadEntry.getName()
+ " - " + platform;
if (downloadEntry.getMeta().get("isPlugin") != null) {
msg = msg + " - 插件化安装包下载完成";
} else {
msg = msg + " - 下载完成";
}
toast(msg);
} else {
toast(downloadEntry.getName() + " - 下载完成");
}
if (downloadEntry.getMeta().get("isPlugin") == null) {
if (sp.getBoolean("autoinstall", true)) {
if (FileUtils.isEmptyFile(entry
.getValue().getPath())) {
toast("解析包错误");
} else {
PackageManager manager = new PackageManager(
getApplicationContext());
if (manager.launchSetup(entry
.getValue().getPath())) {
startActivity(PackageUtils
.getInstallIntent(downloadEntry
.getPath()));
} else {
// 记录自动弹出卸载框
// 弹出卸载提示框
EventBus.getDefault().post(new EBShowDialog("delete", downloadEntry
.getPath()));
}
}
}
}
}
// 统计下载完成
uploadData(downloadEntry.getMeta().get("gameId"),
downloadEntry.getMeta().get("platform"));
}
} else {
Utils.log("It is already done!");
DataUtils.onEvent(
MainActivity.this,
"多次弹框数据",
downloadEntry.getName()
+ "-"
+ downloadEntry.getMeta().get(
"platform"));
}
} else {
if (doneMap.containsKey(downloadEntry.getUrl())) {
doneMap.remove(downloadEntry.getUrl());
}
}
}
}
};
/*
* 黄壮华 按连续按返回键两次才退出应用
*/
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);
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);
entryMap = new ArrayMap<String, String>();
doneMap = new ArrayMap<String, String>();
uninstallMap = new ArrayMap<String, String>();
isFirst = true;
getSearchHints();
sp = getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
if (!sp.getBoolean("isFirstLaunch", true)
&& sp.getBoolean("autoupdate", true)) {
checkUpdate();
}
if (sp.getBoolean("isFirstLaunch", true)) {
getPluginUpdate();
getDisclaimer(true);
sp.edit().putBoolean("isFirstLaunch", 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<String> concernList = new ArrayList<String>();
ConcernManager concernManager = new ConcernManager(
MainActivity.this);
for (ConcernInfo entity : concernManager.getAllConcern()) {
if (entity.isConcern()) {
concernList.add(entity.getGameName());
}
}
Map<String, Object> map = new HashMap<String, Object>();
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();
Utils.log("TD_CHANNEL_ID = " + (String) PackageUtils.getMetaData(this, getPackageName(), "TD_CHANNEL_ID"));
}
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<JSONArray>() {
@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<JSONObject>() {
@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) {
showDisclaimerDialog(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 void showDisclaimerDialog(String content) {
final Dialog disclaimerDialog = new Dialog(this);
View view = View
.inflate(this, R.layout.setting_disclaimer_dialog, null);
TextView title = (TextView) view
.findViewById(R.id.disclaimer_dialog_title);
title.setText("免责声明");
TextView message = (TextView) view
.findViewById(R.id.disclaimer_dialog_message);
Spanned spanned = Html.fromHtml(content);
message.setText(spanned);
view.findViewById(R.id.disclaimer_dialog_confirm).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
disclaimerDialog.dismiss();
}
});
disclaimerDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
disclaimerDialog.setContentView(view);
disclaimerDialog.show();
}
Runnable runnable = new Runnable() {
@Override
public void run() {
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,
NewsActivity.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,
GameDetailsActivity.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<String> list = new ArrayList<String>();
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<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
if (!isDestroy) {
Type listType = new TypeToken<ArrayList<String>>() {}.getType();
Gson gson = new Gson();
List<String> 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 EBTopState("搜索", 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<JSONObject>() {
@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);
EventBus.getDefault()
.post(new EBRedDot(-1));
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) {
dialog = new Dialog(this);
View view = View.inflate(this, R.layout.search_history_delete_dialog,
null);
TextView title = (TextView) view.findViewById(R.id.delete_dialog_title);
title.setText("更新");
TextView content = (TextView) view
.findViewById(R.id.delete_dialog_message);
Spanned dialogContent = Html
.fromHtml("<p>发现新版本!</p>"
+ "<font color='#1ba4fc' style='line-height:1.5'>更新不会影响用户信息!</font><br>"
+ "<font style='line-height:1.5'>最新版本:</font><font color='#3D3D3D' style='line-height:1.5'><b>V"
+ appEntity.getVersion()
+ "</b></font><br>"
+ "<font style='line-height:1.5'>更新包大小:</font><font color='#3D3D3D' style='line-height:1.5'><b>"
+ appEntity.getSize()
+ "</b></font><br>"
+ "更新内容:<br><font color='#2E2E2E' style='line-height:1.5'><b>"
+ appEntity.getContent() + "</b></font><br>"
+ "<br> 确定更新吗?");
content.setText(dialogContent);
if (appEntity.isIs_force()) {
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
}
view.findViewById(R.id.delete_dialog_cancel).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
if (appEntity.isIs_force()) {
finish();
} else {
dialog.dismiss();
}
}
});
view.findViewById(R.id.delete_dialog_confirm).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
dialog.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);
}
}
});
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.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();
}
DownloadEntry downloadEntry = new DownloadEntry();
downloadEntry.setUrl(appEntity.getUrl());
downloadEntry.setName("光环助手V" + appEntity.getVersion());
downloadEntry.setPath(path);
HashMap<String, String> meta = new HashMap<String, String>();
meta.put("platform", "官方版");
downloadEntry.setMeta(meta);
DownloadManager.getInstance(getApplicationContext()).cancel(
downloadEntry.getUrl(), false);
DownloadManager.getInstance(getApplicationContext()).pauseAll();
DownloadManager.getInstance(getApplicationContext()).add(downloadEntry);
}
// 获取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 = findViewById(R.id.home1_layout);
home2Layout = findViewById(R.id.home2_layout);
home3Layout = findViewById(R.id.home3_layout);
home1Image = (ImageView) findViewById(R.id.message_image);
home2Image = (ImageView) findViewById(R.id.contacts_image);
home3Image = (ImageView) findViewById(R.id.news_image);
home1Title = (TextView) findViewById(R.id.message_title);
home2Title = (TextView) findViewById(R.id.contacts_title);
home3Title = (TextView) findViewById(R.id.news_title);
home1Layout.setOnClickListener(this);
home2Layout.setOnClickListener(this);
home3Layout.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.home1_layout:
EventBus.getDefault().post(new EBUISwitch("MainActivity", 0));
setTabSelection(0);
break;
case R.id.home2_layout:
EventBus.getDefault().post(new EBUISwitch("MainActivity", 1));
if (isFirst) {
isFirst = false;
}
setTabSelection(1);
break;
case R.id.home3_layout:
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:
home1Layout.setClickable(false);
home1Image.setImageResource(R.drawable.home1_selected);
home1Title.setTextColor(getResources().getColor(
R.color.theme_colors));
if (pluginFragmentActivity == null) {
List<Fragment> list = getSupportFragmentManager().getFragments();
if (list != null) {
for (Fragment fragment : list) {
if (fragment.getClass().equals(GameFragment.class)) {
pluginFragmentActivity = (GameFragment) fragment;
transaction.show(pluginFragmentActivity);
break;
}
}
}
if (pluginFragmentActivity == null) {
pluginFragmentActivity = new GameFragment();
transaction.add(R.id.main_content, pluginFragmentActivity);
}
} else {
transaction.show(pluginFragmentActivity);
}
currentTab = 0;
break;
case 1:
home2Layout.setClickable(false);
home2Image.setImageResource(R.drawable.home2_selected);
home2Title.setTextColor(getResources().getColor(
R.color.theme_colors));
if (newsFragment == null) {
List<Fragment> 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:
home3Layout.setClickable(false);
home3Image.setImageResource(R.drawable.home3_selected);
home3Title.setTextColor(getResources().getColor(
R.color.theme_colors));
if (home3Fragment == null) {
List<Fragment> list = getSupportFragmentManager().getFragments();
if (list != null) {
for (Fragment fragment : list) {
if (fragment.getClass().equals(PersonalFragment.class)) {
home3Fragment = (PersonalFragment) fragment;
transaction.show(home3Fragment);
break;
}
}
}
if (home3Fragment == null) {
home3Fragment = new PersonalFragment();
transaction.add(R.id.main_content, home3Fragment);
}
} else {
transaction.show(home3Fragment);
}
currentTab = 2;
break;
default:
break;
}
transaction.commit();
}
/**
* 清除掉所有的选中状态。
*/
private void clearSelection() {
home1Layout.setClickable(true);
home2Layout.setClickable(true);
home3Layout.setClickable(true);
home1Image.setImageResource(R.drawable.home1_unselected);
home2Image.setImageResource(R.drawable.home2_unselected);
home3Image.setImageResource(R.drawable.home3_unselected);
home1Title.setTextColor(0xFF333333);
home2Title.setTextColor(0xFF333333);
home3Title.setTextColor(0xFF333333);
}
/**
* 将所有的Fragment都置为隐藏状态。
*/
private void hideFragments(FragmentTransaction transaction) {
if (home3Fragment != null) {
transaction.hide(home3Fragment);
}
if (pluginFragmentActivity != null) {
transaction.hide(pluginFragmentActivity);
}
if (newsFragment != null) {
transaction.hide(newsFragment);
}
List<Fragment> list = getSupportFragmentManager().getFragments();
if (list != null) {
for (Fragment fragment : list) {
transaction.hide(fragment);
}
}
}
private void uploadData(String id, String platform) {
HashMap<String, String> params = new HashMap<String, String>();
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<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.addToRequestQueue(request, MainActivity.class);
}
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);
EventBus.getDefault().post(new EBRedDot(-1));
} else if ("卸载".equals(busFour.getType())) {
PackageManager.removeInstalled(packageName);
}
if ("安装".equals(busFour.getType())) {
String url = entryMap.get(packageName);
if (url != null) {
entryMap.remove(packageName);
DownloadEntry downloadEntry = DownloadManager.getInstance(
getApplicationContext()).get(url);
if (downloadEntry != null
&& downloadEntry.getMeta().get("isPlugin") != null) {
Map<String, Object> kv6 = new HashMap<String, Object>();
kv6.put("安装或卸载", "安装完成");
DataUtils.onEvent(this, "插件化", downloadEntry.getName(), kv6);
}
// 删除数据库 和 文件
DownloadManager.getInstance(getApplicationContext()).cancel(
url, sp.getBoolean("autodelete", true));
}
} else if ("卸载".equals(busFour.getType())) {
for (DownloadEntry downloadEntry : DownloadManager.getInstance(
getApplicationContext()).getAll()) {
if (downloadEntry.getMeta().get("isPlugin") != null
&& downloadEntry.getMeta().get("package_name")
.equals(packageName)) {
Map<String, Object> kv6 = new HashMap<String, Object>();
kv6.put("安装或卸载", "卸载完成");
DataUtils.onEvent(this, "插件化", downloadEntry.getName(), kv6);
break;
}
}
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, true);
} 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<GameUpdateEntity> list = PackageManager.getUpdateList();
GameUpdateEntity game = null;
int index = -1;
for (int i = 0, size = list.size(); i < size; i++) {
game = list.get(i);
if (!game.isPlugin()) {
continue;
}
if (game.getPackageName().equals(packageName)) {
index = i;
break;
}
}
if (index != -1) {
PackageManager.removeUpdateList(packageName);
}
}
Map<String, Object> map = new HashMap<String, Object>();
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);
pluginFragmentActivity = null;
home3Fragment = null;
home1Layout = null;
home2Layout = null;
home3Layout = null;
home1Image = null;
home2Image = null;
home3Image = null;
home1Title = null;
home2Title = null;
home3Title = null;
sp = null;
entryMap = null;
doneMap = 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;
}
}