下载管理-游戏更新接入PackageViewModel

重构PackageManager相关
This commit is contained in:
kehaoyuan
2018-11-13 16:30:30 +08:00
parent 1cc0c51390
commit 03ce6f80a1
14 changed files with 131 additions and 831 deletions

View File

@ -17,7 +17,6 @@ import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
@ -32,7 +31,6 @@ import com.gh.base.AppUncaughtHandler;
import com.gh.base.BaseActivity;
import com.gh.base.fragment.BaseFragment_ViewPager;
import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import com.gh.common.exposure.ExposureUtils;
import com.gh.common.exposure.meta.MetaUtil;
import com.gh.common.im.ImManager;
@ -47,24 +45,18 @@ import com.gh.common.util.DeviceUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DirectUtils;
import com.gh.common.util.EntranceUtils;
import com.gh.common.util.GameUtils;
import com.gh.common.util.GsonUtils;
import com.gh.common.util.LogUtils;
import com.gh.common.util.MtaHelper;
import com.gh.common.util.NetworkUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.PlatformUtils;
import com.gh.common.util.TrafficUtils;
import com.gh.common.util.UrlFilterUtils;
import com.gh.download.DownloadManager;
import com.gh.download.DownloadNotification;
import com.gh.gamecenter.db.info.GameInfo;
import com.gh.gamecenter.db.info.InstallInfo;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.CommunityEntity;
import com.gh.gamecenter.entity.GameDigestEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.entity.GameUpdateEntity;
import com.gh.gamecenter.entity.InnerMetaInfoEntity;
import com.gh.gamecenter.entity.SettingsEntity;
import com.gh.gamecenter.eventbus.EBNetworkState;
@ -75,15 +67,10 @@ import com.gh.gamecenter.eventbus.EBSkip;
import com.gh.gamecenter.fragment.MainWrapperFragment;
import com.gh.gamecenter.install.PackageViewModel;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.FilterManager;
import com.gh.gamecenter.manager.GameManager;
import com.gh.gamecenter.manager.InstallManager;
import com.gh.gamecenter.manager.PackageManager;
import com.gh.gamecenter.manager.UpdateManager;
import com.gh.gamecenter.manager.UserManager;
import com.gh.gamecenter.normal.NormalFragment;
import com.gh.gamecenter.qa.AskFragment;
import com.gh.gamecenter.retrofit.ObservableUtil;
import com.gh.gamecenter.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.gh.gamecenter.suggest.SuggestType;
@ -104,7 +91,6 @@ import com.tencent.bugly.crashreport.CrashReport;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
@ -112,24 +98,20 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.HttpException;
import static com.gh.common.util.EntranceUtils.KEY_TO;
import static com.gh.gamecenter.fragment.MainWrapperFragment.INDEX_PERSONAL;
@ -152,7 +134,6 @@ public class MainActivity extends BaseActivity {
private MainWrapperFragment mMainWrapperFragment;
private SharedPreferences sp;
private InstallManager mInstallManager;
private static final int SKIP_SETTING_REQUEST = 14;
private boolean isSkipped;
@ -449,260 +430,7 @@ public class MainActivity extends BaseActivity {
if (installedList.isEmpty()) {
toast("读取应用列表失败");
} else {
getInstalledListFromServer();
}
}
}
// 获取已安装游戏
private void getInstalledListFromServer() {
ArrayList<String> list = PackageUtils.getAllPackageName(getApplicationContext());
PackageManager.INSTANCE.initData(list);
// 忽略 xposed 安装器
list.remove(Constants.XPOSED_INSTALLER_PACKAGE_NAME);
//应用上报
uploadAppList();
// 过滤助手收录的包
ArrayList<String> localList = new ArrayList<>();
FilterManager filterManager = new FilterManager(this);
for (int i = 0, size = list.size(); i < size; i++) {
if (filterManager.isFilter(list.get(i))) {
localList.add(list.get(i));
}
}
final CountDownLatch latch = ObservableUtil.latch(localList.size(), o -> updateInstall(), new Object());
for (int i = 0, size = localList.size(); i < size; i++) {
final String packageName = localList.get(i);
RetrofitManager.getInstance(this).getApi().getGameDigestByPackageName(UrlFilterUtils.getFilterQuery("package", packageName))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Response<List<GameDigestEntity>>() {
@Override
public void onResponse(List<GameDigestEntity> response) {
for (GameDigestEntity gameDigestEntity : response) {
GameInfo gameInfo = new GameInfo();
gameInfo.setId(gameDigestEntity.getId());
gameInfo.setGameIcon(gameDigestEntity.getIcon());
gameInfo.setPackageName(packageName);
gameInfo.setGameName(gameDigestEntity.getName());
mInstallManager.updateByEntity(gameInfo);
}
latch.countDown();
}
@Override
public void onFailure(HttpException e) {
latch.countDown();
}
});
}
}
private void uploadAppList() {
//检查是否符合应用上报周期
long time = sp.getLong("last_upload_applist_time", 0);
if (Utils.getTime(this) - time >= 604800L) {//一周为一个周期
DataCollectionUtils.uploadAppList(this, PackageUtils.getAppList(this));
}
}
/**
* 为已安装的游戏添加助手后台存在的包
*/
private void updateInstall() {
ArrayList<String> concernIdList = new ArrayList<>();
for (InstallInfo entity : mInstallManager.getAllInstall()) {
concernIdList.add(entity.getId());
}
if (concernIdList.isEmpty()) {
update();
} else {
List<Observable<GameEntity>> sequences = new ArrayList<>();
for (String id : concernIdList) {
sequences.add(RetrofitManager.getInstance(this).getApi().getGameDigest(id));
}
Observable.mergeDelayError(sequences)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Response<GameEntity>() {
@Override
public void onNext(GameEntity response) {
InstallInfo installInfo = mInstallManager.findInstallById(response.getId());
if (installInfo != null && response.getApk().size() != 0) {
HashMap<String, Boolean> packageNames = new HashMap<>();
for (ApkEntity apkEntity : response.getApk()) {
if (PackageManager.INSTANCE.isInstalled(apkEntity.getPackageName())) {
packageNames.put(apkEntity.getPackageName(), true);
} else {
packageNames.put(apkEntity.getPackageName(), false);
}
}
installInfo.setTime(System.currentTimeMillis());
installInfo.setPackageNames(packageNames);
mInstallManager.updateInstall(installInfo);
}
}
@Override
public void onFailure(@Nullable HttpException e) {
update();
}
@Override
public void onComplete() {
update();
}
});
}
}
/**
* 更新安装列表数据
*/
private void update() {
HaloApp.getInstance().getMainExecutor().execute(() -> {
final List<String> installed = new ArrayList<>();
TrafficUtils spy = TrafficUtils.getInstance(getApplicationContext(), true);
List<InstallInfo> concernList = mInstallManager.getAllInstall();
for (InstallInfo concernEntity : concernList) {
concernEntity.setTime(System.currentTimeMillis());
int quantity = 0;
HashMap<String, Boolean> packageNames = new HashMap<>();
for (String packageName : concernEntity.getPackageNames().keySet()) {
if (PackageManager.INSTANCE.isInstalled(packageName)) {
quantity++;
packageNames.put(packageName, true);
installed.add(packageName);
} else {
packageNames.put(packageName, false);
}
}
concernEntity.setPackageNames(packageNames);
concernEntity.setInstalledQuantity(quantity);
int weight = 0;
long traffic = spy.getTraffic(new ArrayList<>(concernEntity.getPackageNames().keySet()));
concernEntity.setTraffic(traffic);
if (traffic > 0) {
weight++;
}
concernEntity.setWeight(weight);
mInstallManager.updateInstall(concernEntity);
}
// 更新用户已安装游戏
RequestBody body = RequestBody.create(MediaType.parse("application/json"),
new JSONArray(installed).toString());
RetrofitManager.getInstance(MainActivity.this).getApi().putPackage(UserManager.getInstance().getUserId(), body)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(new Response<ResponseBody>());
handler.postDelayed(() -> DataCollectionUtils.uploadUser(MainActivity.this), 1000);
// 检查游戏更新
checkGameUpdate();
// 检查可插件化游戏
checkGamePlugin();
});
}
private void checkGameUpdate() {
List<InstallInfo> infos = mInstallManager.getAllInstall();
ArrayList<String> packageList = PackageUtils.getAllPackageName(this);
for (InstallInfo info : infos) {
for (String packageName : info.getPackageNames().keySet()) {
if (info.getPackageNames().get(packageName)
&& packageList.contains(packageName)) {
checkGameUpdate(packageName);
}
}
}
}
private void checkGamePlugin() {
final List<GameEntity> list = new ArrayList<>();
List<Observable<GameEntity>> sequences = new ArrayList<>();
for (InstallInfo info : mInstallManager.getAllInstall()) {
sequences.add(RetrofitManager.getInstance(this).getApi().getGameDigest(info.getId()));
}
Observable.mergeDelayError(sequences)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Response<GameEntity>() {
@Override
public void onNext(GameEntity response) {
list.add(response);
}
@Override
public void onFailure(@Nullable HttpException e) {
processPluginData(list);
}
@Override
public void onComplete() {
processPluginData(list);
}
});
}
private void checkGameUpdate(String packageName) {
Object gh_id = PackageUtils.getMetaData(this, packageName, "gh_id");
Observable<GameEntity> observable;
if (gh_id == null) {
observable = RetrofitManager.getInstance(this).getApi().getGameUpdate(UrlFilterUtils.getFilterQuery("packages", packageName));
} else {
observable = RetrofitManager.getInstance(this).getApi().getGameUpdateById((String) gh_id);
}
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Response<GameEntity>() {
@Override
public void onResponse(GameEntity response) {
List<GameUpdateEntity> updateList = PackageUtils.isCanUpdate(getApplication(), response);
if (updateList.size() > 0) {
PackageManager.INSTANCE.addUpdateList(updateList);
}
}
});
}
private void processPluginData(List<GameEntity> list) {
if (list == null || list.isEmpty()) {
return;
}
List<InstallInfo> infos = mInstallManager.getAllInstall();
HashMap<String, Boolean> map;
for (InstallInfo info : infos) {
for (GameEntity gameEntity : list) {
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)) {
for (ApkEntity apkEntity : gameEntity.getApk()) {
if (apkEntity.getPackageName().equals(key)
&& !TextUtils.isEmpty(apkEntity.getGhVersion())
&& !PackageUtils.isSignature(this, apkEntity.getPackageName())) {
PackageManager.INSTANCE.addUpdate(GameUtils.getGameUpdateEntity(gameEntity, apkEntity));
break;
}
}
GameManager manager = new GameManager(this);
manager.addOrUpdate(gameEntity);
}
}
break;
}
// getInstalledListFromServer();
}
}
}
@ -732,8 +460,6 @@ public class MainActivity extends BaseActivity {
}
replaceFragment(mMainWrapperFragment);
mInstallManager = new InstallManager(getApplicationContext());
// 检查助手更新
UpdateManager.getInstance(this).checkUpdate(true, null);
@ -978,7 +704,7 @@ public class MainActivity extends BaseActivity {
startActivityForResult(intent, SKIP_SETTING_REQUEST);
}, null);
} else {
getInstalledListFromServer();
// getInstalledListFromServer();
}
}
@ -1059,6 +785,7 @@ public class MainActivity extends BaseActivity {
DownloadEntity mDownloadEntity = null;
for (DownloadEntity downloadEntity : DownloadManager.getInstance(getApplicationContext()).getAll()) {
//todo 根据包名获取DownloadEntity? 假如存在相同包名的下载任务,有可能会删除错误
if (packageName.equals(downloadEntity.getPackageName())) {
mDownloadEntity = downloadEntity;
break;
@ -1072,9 +799,6 @@ public class MainActivity extends BaseActivity {
NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nManager.cancel(packageName.hashCode());
// 添加进已安装map中
PackageManager.INSTANCE.addInstalled(packageName);
if (mDownloadEntity != null) {
if (mDownloadEntity.isPluggable()) {
Map<String, Object> kv6 = new HashMap<>();
@ -1092,11 +816,6 @@ public class MainActivity extends BaseActivity {
mDownloadEntity.getUrl(), false); // 默认不删除安装包 sp.getBoolean("autodelete", true)
}
GameManager gameManager = new GameManager(getApplicationContext());
GameInfo gameInfo = gameManager.findGame(packageName);
if (gameInfo != null) {
mInstallManager.updateByEntity(gameInfo);
}
if (sp.getBoolean("concerngame", true)) { //设置页面控制是否安装后自动关注
// 安装后关注游戏
@ -1108,8 +827,6 @@ public class MainActivity extends BaseActivity {
@Override
public void onResponse(List<GameDigestEntity> response) {
for (GameDigestEntity gameDigestEntity : response) {
concernGame(gameDigestEntity.getId(), packageName);
if (!TextUtils.isEmpty(gameDigestEntity.getId())) { // 关注游戏
if (finalDownloadEntity != null && gameDigestEntity.getId().equals(finalDownloadEntity.getGameId())) {
ConcernUtils.INSTANCE.postConcernGameId(MainActivity.this, gameDigestEntity.getId(), null);
@ -1117,11 +834,6 @@ public class MainActivity extends BaseActivity {
}
}
if (PackageUtils.getMetaData(getApplicationContext(),
packageName, "gh_version") != null) {
checkGameUpdate(packageName);
}
// 更新已安装游戏
RetrofitManager.getInstance(MainActivity.this).getApi()
.postPackage(UserManager.getInstance().getUserId(), packageName)
@ -1135,8 +847,6 @@ public class MainActivity extends BaseActivity {
}
if ("卸载".equals(busFour.getType())) {
mPackageViewModel.addUninstalledGame(packageName);
// 删除map中数据
PackageManager.INSTANCE.removeInstalled(packageName);
if (mDownloadEntity != null && mDownloadEntity.isPluggable()) {
Map<String, Object> kv6 = new HashMap<>();
@ -1153,11 +863,6 @@ public class MainActivity extends BaseActivity {
startActivity(PackageUtils.getInstallIntent(this, mDownloadEntity.getPath()));
}
FilterManager filterManager = new FilterManager(getApplicationContext());
if (filterManager.isFilter(packageName)) {
mInstallManager.updateByPackageName(packageName);
}
// 更新已安装游戏
RetrofitManager.getInstance(this).getApi()
.deletePackage(UserManager.getInstance().getUserId(), packageName)
@ -1167,36 +872,9 @@ public class MainActivity extends BaseActivity {
}
if ("卸载".equals(busFour.getType()) || "安装".equals(busFour.getType())) {
PackageManager.INSTANCE.removeUpdate(packageName);
}
DataCollectionUtils.uploadInorunstall(this, busFour.getType(), busFour.getPackageName());
}
private void concernGame(final String id, final String packageName) {
RetrofitManager.getInstance(this).getApi().getGameDigest(id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Response<GameEntity>() {
@Override
public void onResponse(GameEntity response) {
GameManager manager = new GameManager(getApplicationContext());
manager.addOrUpdate(response);
// 检查是否能插件化
if (response.getTag() != null && response.getTag().size() != 0) {
for (ApkEntity apkEntity : response.getApk()) {
if (packageName.equals(apkEntity.getPackageName())
&& !TextUtils.isEmpty(apkEntity.getGhVersion())
&& !PackageUtils.isSignature(getApplicationContext(), apkEntity.getPackageName())) {
PackageManager.INSTANCE.addUpdate(GameUtils.getGameUpdateEntity(response, apkEntity));
break;
}
}
}
}
});
}
// 接收登录和登出更新事件统计的 Meta
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(EBReuse reuse) {