Compare commits

..

3 Commits
v2.2 ... v1.52

Author SHA1 Message Date
f3cc84bcf3 Update modules.xml 2016-08-01 11:11:28 +08:00
4e89e623c6 Update .gitignore 2016-08-01 11:09:02 +08:00
3d07b0b025 . 2016-08-01 10:31:11 +08:00
688 changed files with 30690 additions and 32289 deletions

13
.gitignore vendored
View File

@ -1,8 +1,7 @@
/.idea
.idea/misc.xml
*.iml
.gradle
/local.properties
.DS_Store
/build
/.idea
*.iml
.gradle
/local.properties
.DS_Store
/build
/captures

4
.idea/gradle.xml generated
View File

@ -10,12 +10,16 @@
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
<option value="$PROJECT_DIR$/buildSrc" />
<option value="$PROJECT_DIR$/hackdex" />
</set>
</option>
<option name="myModules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
<option value="$PROJECT_DIR$/buildSrc" />
<option value="$PROJECT_DIR$/hackdex" />
</set>
</option>
</GradleProjectSettings>

18
.idea/modules.xml generated
View File

@ -1,9 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/GH-ASSISTv1.45.iml" filepath="$PROJECT_DIR$/GH-ASSISTv1.45.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
</modules>
</component>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/GH-ASSISTv1.45.iml" filepath="$PROJECT_DIR$/GH-ASSISTv1.45.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
<module fileurl="file://$PROJECT_DIR$/buildSrc/buildSrc.iml" filepath="$PROJECT_DIR$/buildSrc/buildSrc.iml" />
<module fileurl="file://$PROJECT_DIR$/hackdex/hackdex.iml" filepath="$PROJECT_DIR$/hackdex/hackdex.iml" />
</modules>
</component>
</project>

View File

@ -1,15 +1,45 @@
apply plugin: 'com.android.application'
task('processWithJavassist') << {
String classPath = file('build/intermediates/classes/debug')//项目编译class所在目录
dodola.patch.PatchClass.process(classPath, project(':hackdex').buildDir
.absolutePath + '/intermediates/classes/debug')//第二个参数是hackdex的class所在目录
}
task buildJar(dependsOn: ['compileReleaseJavaWithJavac'], type: Jar) {
baseName = "news"
//后缀名
extension = "jar"
//最终的 Jar 包名,如果没设置,默认为 [baseName]-[appendix]-[version]-[classifier].[extension]
archiveName = "news.jar";
//需打包的资源所在的路径集
def srcClassDir = [project.buildDir.absolutePath + "/intermediates/classes/debug"];
from srcClassDir
//去除路径集下部分的资源
exclude "com/gh/gamecenter/BuildConfig.class"
exclude "com/gh/gamecenter/R.class"
exclude "com/gh/gamecenter/BuildConfig/\$*.class"
exclude "com/gh/gamecenter/R/\$*.class"
//只导入资源路径集下的部分资源
include "com/gh/gamecenter/NewsActivity.class"
include "com/gh/gamecenter/NewsActivity\$*.class"
//注: exclude include 支持可变长参数
}
android {
compileSdkVersion 21
compileSdkVersion 19
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.gh.gamecenter"
minSdkVersion 14
targetSdkVersion 21
versionCode 17
versionName "2.2"
targetSdkVersion 19
versionCode 14
versionName "1.51"
// 默认的渠道
// manifestPlaceholders = [CHANNEL_VALUE: "GH_TEST"]
@ -39,8 +69,12 @@ android {
}
}
// applicationVariants.all { variant ->
// variant.dex.dependsOn << processWithJavassist //在执行dx命令之前将代码打入到class中
// }
/**
* 渠道打包
* 渠道打包
*/
productFlavors {
GH_100 {}
@ -49,79 +83,31 @@ android {
GH_103 {}
GH_104 {}
GH_106 {}
GH_107 {}
GH_108 {}
GH_109 {}
GH_110 {}
GH_111 {}
GH_113 {}
GH_114 {}
GH_115 {}
GH_116 {}
GH_117 {}
GH_118 {}
GH_119 {}
GH_120 {}
GH_121 {}
GH_123 {}
GH_127 {}
GH_200 {}
GH_201 {}
GH_202 {}
GH_203 {}
GH_204 {}
GH_205 {}
GH_222 {}
GH_307 {}
GH_TEST {}
GH_127 {}
}
productFlavors.all { flavor ->
flavor.manifestPlaceholders = [CHANNEL_VALUE: name]//命令 gradlew assembleRelease
}
}
//butterknife
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
apply plugin: 'com.neenbedankt.android-apt'
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:21.0.0'
compile 'com.android.support:cardview-v7:21.0.0'
// fresco图片框架
compile 'com.facebook.fresco:fresco:0.12.0'
compile 'com.facebook.fresco:animated-gif:0.12.0'
// Retrofit2所需要的包
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
// okhttp
compile 'com.squareup.okhttp3:okhttp:3.2.0'
// ConverterFactory的Gson依赖包
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
// ConverterFactory的String依赖包
compile 'com.squareup.retrofit2:converter-scalars:2.0.0-beta4'
// ConverterFactory的RxJava依赖包
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
// gson
compile 'com.google.code.gson:gson:2.8.0'
// OrmLite数据库
compile 'com.j256.ormlite:ormlite-android:5.0'
compile 'com.j256.ormlite:ormlite-core:5.0'
// butterknife
compile 'com.jakewharton:butterknife:8.4.0'
apt 'com.jakewharton:butterknife-compiler:8.4.0'
// RxJava && RxAndroid
compile 'io.reactivex:rxandroid:1.1.0'
compile 'io.reactivex:rxjava:1.1.0'
// RxBinding
compile 'com.jakewharton.rxbinding:rxbinding:0.3.0'
// compile 'com.jakewharton.rxbinding:rxbinding-appcompat-v7:0.3.0'
// compile 'com.jakewharton.rxbinding:rxbinding-design:0.3.0'
compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.16'
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
app/libs/gson-2.3.1.jar Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -38,6 +38,8 @@
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<!-- 小米推送需要的权限 -->
<uses-permission android:name="com.gh.gamecenter.permission.MIPUSH_RECEIVE" />
<!-- 获取网路状态 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<permission
android:name="com.gh.gamecenter.permission.MIPUSH_RECEIVE"
@ -52,6 +54,7 @@
<application
android:name="com.gh.base.AppController"
android:allowBackup="true"
android:icon="@drawable/logo"
android:label="@string/app_name"
android:theme="@style/AppThemeNormal" >
@ -61,7 +64,8 @@
android:value="81DB144D555386A38A70B833537EC256" />
<meta-data
android:name="TD_CHANNEL_ID"
android:value="${CHANNEL_VALUE}"/>
android:value="GH_TEST"
/>
<!--android:value="${CHANNEL_VALUE}"-->
<!-- MTA -->
@ -70,7 +74,7 @@
android:value="APV567FTBS7J"/>
<meta-data
android:name="InstallChannel"
android:value="${CHANNEL_VALUE}"/>
android:value="GH_TEST"/>
<!--android:value="${CHANNEL_VALUE}"-->
<activity
@ -85,74 +89,6 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.gh.gamecenter.MainActivity"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustResize"/>
<activity
android:name="com.gh.gamecenter.DownloadManagerActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.ViewImageActivity"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" />
<activity
android:name="com.gh.gamecenter.SearchActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible" />
<activity
android:name="com.gh.gamecenter.GameDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.NewsDetailActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.SettingActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.SuggestionActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible" />
<activity
android:name="com.gh.gamecenter.ConcernActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.SubjectActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.PluginActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.NewsSearchActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.GameNewsActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.CropImageActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.WebActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.ShareCardPicActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.ShareCardActivity"
android:screenOrientation="portrait"/>
<activity
android:name="com.gh.gamecenter.MessageDetailActivity"
android:screenOrientation="portrait"/>
<activity android:name="com.gh.gamecenter.SkipActivity"
android:theme="@android:style/Theme.Translucent">
<intent-filter>
<data android:scheme="ghzhushou"/>
<category android:name="android.intent.category.DEFAULT"/>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.BROWSABLE"/>
</intent-filter>
</activity>
<activity
android:name="com.mob.tools.MobUIShell"
android:configChanges="keyboardHidden|orientation|screenSize"
@ -169,54 +105,50 @@
</intent-filter>
</activity>
<activity
android:name="com.gh.gamecenter.wxapi.WXEntryActivity"
android:name=".WXEntryActivity"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:configChanges="keyboardHidden|orientation|screenSize"
android:exported="true"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.MainActivity"
android:launchMode="singleTop"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="sdksample"/>
</intent-filter>
</activity>
<!-- QQ 分享 -->
android:screenOrientation="portrait" />
<activity
android:name="com.tencent.tauth.AuthActivity"
android:launchMode="singleTask"
android:noHistory="true" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="tencent1104659243" />
</intent-filter>
</activity>
android:name="com.gh.gamecenter.DownloadManagerActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.tencent.connect.common.AssistActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="behind"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
<!--微博分享-->
android:name="com.gh.gamecenter.ViewImageActivity"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" />
<activity
android:name="com.sina.weibo.sdk.component.WeiboSdkBrowser"
android:configChanges="keyboardHidden|orientation"
android:windowSoftInputMode="adjustResize"
android:exported="false" >
</activity>
<activity
android:name="com.gh.gamecenter.WeiBoShareActivity"
android:configChanges="keyboardHidden|orientation"
android:name="com.gh.gamecenter.SearchActivity"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:exported="true"
android:launchMode="singleTop">
<intent-filter>
<action android:name="com.sina.weibo.sdk.action.ACTION_SDK_REQ_ACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
android:windowSoftInputMode="stateVisible" />
<activity
android:name="com.gh.gamecenter.GameDetailsActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.NewsActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.GameActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.SettingActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.SuggestionActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible" />
<activity
android:name="com.gh.gamecenter.ConcernActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.SubjectActivity"
android:screenOrientation="portrait" />
<activity
android:name="com.gh.gamecenter.PluginActivity"
android:screenOrientation="portrait"/>
<receiver android:name="com.gh.gamecenter.receiver.InstallAndUninstallReceiver" >
<intent-filter>
@ -235,17 +167,10 @@
</intent-filter>
</receiver>
<receiver
android:name="com.gh.gamecenter.receiver.DownloadReceiver"
android:name="com.gh.gamecenter.receiver.UninstallReceiver"
android:exported="false" >
<intent-filter>
<action android:name="com.gh.gamecenter.DOWNLOAD" />
</intent-filter>
</receiver>
<receiver
android:name="com.gh.gamecenter.receiver.InstallReceiver"
android:exported="false" >
<intent-filter>
<action android:name="com.gh.gamecenter.INSTALL" />
<action android:name="com.gh.gamecenter.UNINSTALL" />
</intent-filter>
</receiver>
<receiver android:name="com.gh.gamecenter.receiver.NetworkStateReceiver" >
@ -284,15 +209,15 @@
</intent-filter>
</receiver>
<receiver
android:name="com.gh.gamecenter.receiver.ActivitySkipReceiver"
android:exported="true" >
android:name="com.xiaomi.push.service.receivers.PingReceiver"
android:exported="false"
android:process=":pushservice" >
<intent-filter>
<action android:name="com.gh.gamecenter.ACTIVITYSKIP" />
<action android:name="com.xiaomi.push.PING_TIMER" />
</intent-filter>
</receiver>
<service
android:name="com.gh.download.DownloadService" />
<service android:name="com.gh.download.DownloadService" />
<service
android:name="com.xiaomi.push.service.XMPushService"
android:enabled="true"

View File

@ -0,0 +1,129 @@
<?xml version="1.0" encoding="utf-8"?>
<DevInfor>
<!--
说明:
1、表格中的第一项
<ShareSDK
AppKey="api20" />
是必须的其中的AppKey是您在ShareSDK上注册的开发者帐号的AppKey
2、所有集成到您项目的平台都应该为其在表格中填写相对应的开发者信息以新浪微博为例
<SinaWeibo
Id="1"
SortId="1"
AppKey="568898243"
AppSecret="38a4f8204cc784f81f9f0daaf31e02e3"
RedirectUrl="http://www.mob.com"
Enable="true" />
其中的SortId是此平台在分享列表中的位置由开发者自行定义可以是任何整型数字数值越大
越靠后AppKey、AppSecret和RedirectUrl是您在新浪微博上注册开发者信息和应用后得到的信息
Id是一个保留的识别符整型ShareSDK不使用此字段供您在自己的项目中当作平台的识别符。
Enable字段表示此平台是否有效布尔值默认为true如果Enable为false即便平台的jar包
已经添加到应用中,平台实例依然不可获取。
各个平台注册应用信息的地址如下:
新浪微博 http://open.weibo.com
腾讯微博 http://dev.t.qq.com
QQ空间 http://connect.qq.com/intro/login/
微信好友 http://open.weixin.qq.com
Facebook https://developers.facebook.com
Twitter https://dev.twitter.com
人人网 http://dev.renren.com
开心网 http://open.kaixin001.com
搜狐微博 http://open.t.sohu.com
网易微博 http://open.t.163.com
豆瓣 http://developers.douban.com
有道云笔记 http://note.youdao.com/open/developguide.html#app
印象笔记 https://dev.evernote.com/
Linkedin https://developer.linkedin.com
FourSquare https://developer.foursquare.com/
搜狐随身看 https://open.sohu.com/
Flickr http://www.flickr.com/services/
Pinterest http://developers.pinterest.com/
Tumblr http://www.tumblr.com/developers
Dropbox https://www.dropbox.com/developers
Instagram http://instagram.com/developer#
VKontakte http://vk.com/dev
易信好友 http://open.yixin.im/
明道 http://open.mingdao.com/
Line http://media.line.me/zh-hant/
Pocket http://getpocket.com/developer/apps/new
-->
<ShareSDK
AppKey = "6f286c8a261a"/> <!-- 修改成你在sharesdk后台注册的应用的appkey"-->
<!-- ShareByAppClient标识是否使用微博客户端分享默认是false -->
<SinaWeibo
Id="1"
SortId="1"
AppKey="568898243"
AppSecret="38a4f8204cc784f81f9f0daaf31e02e3"
RedirectUrl="http://www.sharesdk.cn"
ShareByAppClient="false"
Enable="true" />
<TencentWeibo
Id="2"
SortId="2"
AppKey="801307650"
AppSecret="ae36f4ee3946e1cbb98d6965b0b2ff5c"
RedirectUri="http://sharesdk.cn"
Enable="true" />
<!-- ShareByAppClient标识是否使用微博客户端分享默认是false -->
<QZone
Id="3"
SortId="3"
AppId="1104659243"
AppKey="OfjHS7bWyxPiH0t8"
ShareByAppClient="true"
Enable="true" />
<!--
Wechat微信和WechatMoments微信朋友圈的appid是一样的
注意开发者不能用我们这两个平台的appid,否则分享不了
微信测试的时候微信测试需要先签名打包出apk,
sample测试微信要先签名打包keystore在sample项目中密码123456
BypassApproval是绕过审核的标记设置为true后AppId将被忽略故不经过
审核的应用也可以执行分享,但是仅限于分享文字和图片,不能分享其他类型,
默认值为false。此外微信收藏不支持此字段。
-->
<Wechat
Id="4"
SortId="4"
AppId="wx4868b35061f87885"
AppSecret="64020361b8ec4c99936c0e3999a9f249"
BypassApproval="true"
Enable="true" />
<WechatMoments
Id="5"
SortId="5"
AppId="wx4868b35061f87885"
AppSecret="64020361b8ec4c99936c0e3999a9f249"
BypassApproval="true"
Enable="true" />
<WechatFavorite
Id="6"
SortId="6"
AppId="wx4868b35061f87885"
AppSecret="64020361b8ec4c99936c0e3999a9f249"
Enable="true" />
<!-- ShareByAppClient标识是否使用微博客户端分享默认是false -->
<QQ
Id="7"
SortId="7"
AppId="1104659243"
AppKey="OfjHS7bWyxPiH0t8"
ShareByAppClient="true"
Enable="true" />
</DevInfor>

Binary file not shown.

View File

@ -429,9 +429,7 @@ class AdapterHelper implements OpReorderer.Callback {
if (DEBUG) {
Log.d(TAG, "postponing " + op);
}
// Utils.log("add UpdateOp to PostponedList");
mPostponedList.add(op);
// Utils.log("op" + op.positionStart + "=" + op.itemCount);
switch (op.cmd) {
case UpdateOp.ADD:
mCallback.offsetPositionsForAdd(op.positionStart, op.itemCount);

View File

@ -3296,16 +3296,10 @@ public class RecyclerView extends ViewGroup {
}
if (holder == null) {
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
// final int offsetPosition = position;
// Utils.log("offsetPosition position = " + position);
// Utils.log("offsetPosition = " + offsetPosition);
// Utils.log("offsetPosition count = " + mAdapter.getItemCount());
// Utils.log("offsetPosition count = " + mState.getItemCount());
if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item "
+ "position " + position + "(offset:" + offsetPosition + ")."
+ "state:" + mState.getItemCount()
+ "adpter:" + mAdapter.getClass().getName());
+ "state:" + mState.getItemCount());
}
final int type = mAdapter.getItemViewType(offsetPosition);

View File

@ -106,7 +106,7 @@ public class BasicNetwork implements Network {
responseHeaders = convertHeaders(httpResponse.getAllHeaders());
// Handle cache validation.
if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
if (request.getUrl().startsWith(Config.HOST + "support/upgrade")) {
if (request.getUrl().startsWith(Config.HOST + "v2/version")) {
if (request.getCacheEntry() != null) {
return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED,
request.getCacheEntry().data, responseHeaders, true);

View File

@ -176,8 +176,9 @@ public class DiskBasedCache implements Cache {
public synchronized void modify(String key, byte[] data) {
File file = getFileForKey(key);
CountingInputStream cis = null;
try {
CountingInputStream cis = new CountingInputStream(new FileInputStream(file));
cis = new CountingInputStream(new FileInputStream(file));
CacheHeader e = CacheHeader.readHeader(cis); // eat header
Entry entry = e.toCacheEntry(data);
cis.close();

View File

@ -5,6 +5,7 @@ import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Process;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
@ -13,86 +14,43 @@ import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.gh.base.GHPushMessageReceiver.PushHandler;
import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.HttpsUtils;
import com.gh.common.util.DexUtils;
import com.gh.common.util.HotFix;
import com.gh.common.util.Utils;
import com.xiaomi.channel.commonutils.logger.LoggerInterface;
import com.xiaomi.mipush.sdk.Logger;
import com.xiaomi.mipush.sdk.MiPushClient;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class AppController extends Application {
//import com.facebook.drawee.backends.pipeline.Fresco;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
// xiaomi push appid
public static final String APP_ID = "2882303761517352993";
// xiaomi push appkey
public static final String APP_KEY = "5451735292993";
private static AppController mInstance;
private static ArrayMap<String, Object> objectMap = new ArrayMap<>();
private static PushHandler handler = null;
private RequestQueue mRequestQueue;
private ArrayList<Activity> list = new ArrayList<>();
private boolean isFinish = false;
@Override
public void onCreate() {
super.onCreate();
//初始化Fresco
Fresco.initialize(this);
DataUtils.init(this);
HttpsUtils.initHttpsUrlConnection(this);
AppUncaHandler uncaHandler = new AppUncaHandler(this);
Thread.setDefaultUncaughtExceptionHandler(uncaHandler);
mInstance = this;
// 注册push服务注册成功后会向GHPushMessageReceiver发送广播
// 可以从GHPushMessageReceiver的onCommandResult方法中MiPushCommandMessage对象参数中获取注册信息
if (shouldInit()) {
MiPushClient.registerPush(this, APP_ID, APP_KEY);
}
LoggerInterface newLogger = new LoggerInterface() {
@Override
public void setTag(String tag) {
// ignore
}
@Override
public void log(String content, Throwable t) {
Log.d(TAG, content, t);
}
@Override
public void log(String content) {
Log.d(TAG, content);
}
};
Logger.setLogger(this, newLogger);
}
private static ArrayMap<String, Object> objectMap = new ArrayMap<String, Object>();
public static void put(String key, Object object) {
if (objectMap == null) {
objectMap = new ArrayMap<>();
}
objectMap.put(key, object);
}
public static Object get(String key, boolean isRemove) {
if (objectMap == null) {
return null;
}
if (isRemove) {
return objectMap.remove(key);
} else {
@ -101,12 +59,13 @@ public class AppController extends Application {
}
public static void remove(String key) {
if (objectMap == null) {
return;
}
objectMap.remove(key);
}
private ArrayList<Activity> list = new ArrayList<Activity>();
private boolean isFinish = false;
/**
* Activity关闭时删除Activity列表中的Activity对象
*/
@ -141,6 +100,67 @@ public class AppController extends Application {
Process.killProcess(Process.myPid());
}
@Override
public void onCreate() {
super.onCreate();
// Fresco.initialize(getApplicationContext());
File dexPath = new File(getDir("dex", Context.MODE_PRIVATE), "hackdex_dex.jar");
DexUtils.prepareAssetsDex(this, dexPath, "hackdex_dex.jar");
HotFix.patch(this, dexPath.getAbsolutePath(), "dodola.hackdex.AntilazyLoad");
SharedPreferences sp = this.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
File directory = new File(this.getFilesDir().getAbsolutePath() + File.separator + "hotfix");
if (directory.exists()) {
File[] files = directory.listFiles();
for (File file : files) {
Utils.log("dex file = " + file.getName());
String clazz = sp.getString(file.getName(), null);
if (clazz != null) {
dexPath = new File(getDir("dex", Context.MODE_PRIVATE), file.getName());
DexUtils.prepareDex(this, dexPath, file);
HotFix.patch(this, dexPath.getAbsolutePath(), clazz);
Utils.log(file.getName() + " patch success");
}
}
}
DataUtils.init(this);
AppUncaHandler uncaHandler = new AppUncaHandler(this);
Thread.setDefaultUncaughtExceptionHandler(uncaHandler);
mInstance = this;
// 注册push服务注册成功后会向GHPushMessageReceiver发送广播
// 可以从GHPushMessageReceiver的onCommandResult方法中MiPushCommandMessage对象参数中获取注册信息
if (shouldInit()) {
MiPushClient.registerPush(this, APP_ID, APP_KEY);
}
LoggerInterface newLogger = new LoggerInterface() {
@Override
public void setTag(String tag) {
// ignore
}
@Override
public void log(String content, Throwable t) {
Log.d(TAG, content, t);
}
@Override
public void log(String content) {
Log.d(TAG, content);
}
};
Logger.setLogger(this, newLogger);
if (handler == null) {
handler = new PushHandler(this);
}
}
public static String getProcessName(Context cxt, int pid) {
ActivityManager am = (ActivityManager) cxt
.getSystemService(Context.ACTIVITY_SERVICE);
@ -160,18 +180,6 @@ public class AppController extends Application {
return mInstance;
}
public static <T> void addToRequestQueue(Request<T> request) {
request.setTag(TAG);
getInstance().addRequest(request);
}
public static void canclePendingRequests(String tag) {
if (TextUtils.isEmpty(tag)) {
tag = TAG;
}
getInstance().cancleRequest(tag);
}
public <T> void addRequest(Request<T> request) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
@ -184,6 +192,50 @@ public class AppController extends Application {
mRequestQueue.cancelAll(tag);
}
}
public static <T> void addToRequestQueue(Request<T> request) {
request.setTag(TAG);
getInstance().addRequest(request);
}
public static <T> void addToRequestQueue(Request<T> request, String tag) {
request.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getInstance().addRequest(request);
}
public static <T> void addToRequestQueue(Request<T> request, Object obj) {
String tag = null;
if (obj != null) {
tag = obj.getClass().getSimpleName();
}
addToRequestQueue(request, tag);
}
public static <T> void addToRequestQueue(Request<T> request, Class<?> clazz) {
String tag = null;
if (clazz != null) {
tag = clazz.getSimpleName();
}
addToRequestQueue(request, tag);
}
public static void canclePendingRequests(String tag) {
if (tag != null) {
getInstance().cancleRequest(tag);
}
}
public static void canclePendingRequests(Object obj) {
if (obj != null) {
getInstance().cancleRequest(obj.getClass().getSimpleName());
}
}
public static void canclePendingRequests(Class<?> clazz) {
if (clazz != null) {
getInstance().cancleRequest(clazz.getSimpleName());
}
}
private boolean shouldInit() {
ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
@ -199,4 +251,8 @@ public class AppController extends Application {
return false;
}
public static PushHandler getHandler() {
return handler;
}
}

View File

@ -4,14 +4,11 @@ import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import com.gh.common.constant.Config;
import com.gh.common.util.FileUtils;
import com.gh.common.util.NetworkUtils;
import com.gh.gamecenter.SplashScreenActivity;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.tencent.stat.StatService;
@ -58,25 +55,18 @@ public class AppUncaHandler implements UncaughtExceptionHandler {
e.printStackTrace();
}
// 防止重复奔溃导致助手一直重启20秒内不做处理
SharedPreferences sp = appController.getApplicationContext().getSharedPreferences(
Config.PREFERENCE, Context.MODE_PRIVATE);
long time = sp.getLong("last_restart_time", 0);
if (System.currentTimeMillis() - time > 20 * 1000) {
sp.edit().putLong("last_restart_time", System.currentTimeMillis()).apply();
Intent intent = new Intent(appController.getApplicationContext(),
SplashScreenActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent restartIntent = PendingIntent.getActivity(
appController.getApplicationContext(), 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// 退出程序并重启
AlarmManager mgr = (AlarmManager) appController
.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
restartIntent); // 1秒钟后重启应用
}
Intent intent = new Intent(appController.getApplicationContext(),
SplashScreenActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent restartIntent = PendingIntent.getActivity(
appController.getApplicationContext(), 0, intent,
Intent.FLAG_ACTIVITY_NEW_TASK);
// 退出程序并重启
AlarmManager mgr = (AlarmManager) appController
.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
restartIntent); // 1秒钟后重启应用
appController.finishActivity();
}
}
@ -88,17 +78,19 @@ public class AppUncaHandler implements UncaughtExceptionHandler {
// MTA主动上传错误
StatService.reportError(appController.getApplicationContext(), errorMsg);
// WIFI实时上传错误数据
Map<String, Object> map = new HashMap<>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("content", errorMsg);
map.put("createdOn", System.currentTimeMillis() / 1000);
map.put("type", android.os.Build.MODEL);
map.put("system", android.os.Build.VERSION.SDK_INT + "=" + android.os.Build.VERSION.RELEASE);
DataCollectionManager.onEvent(appController.getApplicationContext(), "error", map,
NetworkUtils.isWifiConnected(appController.getApplicationContext()));
map.put("system", android.os.Build.VERSION.SDK_INT + "="
+ android.os.Build.VERSION.RELEASE);
DataCollectionManager.onEvent(appController.getApplicationContext(),
"error", map, false);
// 保存到本地
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.getDefault());
File file = new File(FileUtils.getLogPath(appController.getApplicationContext(),
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss",
Locale.getDefault());
File file = new File(FileUtils.getLogPath(
appController.getApplicationContext(),
format.format(new Date()) + "_gh_assist" + ".log"));
FileWriter writer = null;
try {
@ -117,7 +109,6 @@ public class AppUncaHandler implements UncaughtExceptionHandler {
}
}
}
}
/**

View File

@ -5,6 +5,7 @@ import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
@ -19,32 +20,34 @@ import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.FileUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.RunningUtils;
import com.gh.common.util.ShareUtils;
import com.gh.common.util.Utils;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.MainActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.eventbus.EBShowDialog;
import com.gh.gamecenter.listener.OnCallBackListener;
import com.gh.gamecenter.manager.SystemBarTintManager;
import com.gh.gamecenter.manager.SystemBarTintManager.SystemBarConfig;
import java.lang.reflect.Field;
import java.util.ArrayList;
import cn.sharesdk.framework.ShareSDK;
import de.greenrobot.event.EventBus;
import onekeyshare.OnekeyShare;
import onekeyshare.themes.classic.PlatformPage;
public class BaseActivity extends Activity implements OnCallBackListener {
private SystemBarTintManager tintManager;
public class BaseActivity extends Activity {
private String LOG = this.getClass().getName();
private boolean LOG_ON = true;
private boolean isPause;
private SystemBarTintManager tintManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppLog("onCreate");
Utils.log(this.getClass().getSimpleName());
AppController.getInstance().addActivity(this);
EventBus.getDefault().register(this);
@ -62,7 +65,7 @@ public class BaseActivity extends Activity implements OnCallBackListener {
setTranslucentStatus(true);
tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.theme);
tintManager.setStatusBarTintResource(R.color.theme_colors);
SystemBarConfig config = tintManager.getConfig();
contentView.setPadding(0, config.getPixelInsetTop(false), 0,
config.getPixelInsetBottom());
@ -117,6 +120,12 @@ public class BaseActivity extends Activity implements OnCallBackListener {
AppController.getInstance().removeActivity(this);
}
public void AppLog(String str) {
if (LOG_ON) {
Log.i(LOG, str);
}
}
public void toast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
@ -138,44 +147,77 @@ public class BaseActivity extends Activity implements OnCallBackListener {
window.setAttributes(winParams);
}
//如果是游戏分享newsTitle默认为空
public void showShare(String url, String gameName, String icon, String newsTitle, ArrayList<String> tag, String entrance, String type) {
public void showShare(String url, String title, String icon, String entrance, String type) {
//判断是否是官方版
boolean isPlugin = false;
if (tag != null){
for (String s : tag) {
if (!"官方版".equals(s)){
isPlugin = true;
}
if (isShowShare){
return;
}
ShareSDK.initSDK(this);
OnekeyShare oks = new OnekeyShare();
// 关闭sso授权
oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
// oks.setNotification(R.drawable.ic_launcher,
// getString(R.string.app_name));
// title标题印象笔记、邮箱、信息、微信、人人网和QQ空间使用
oks.setTitle(title);
// titleUrl是标题的网络链接仅在人人网和QQ空间使用
oks.setTitleUrl(url);
// text是分享文本所有平台都需要这个字段
oks.setText(title + " " + url);
// imagePath是图片的本地路径Linked-In以外的平台都支持此参数
// oks.setImagePath(icon);//确保SDcard下面存在此张图片
oks.setImageUrl(icon);
// url仅在微信包括好友和朋友圈中使用
oks.setUrl(url);
// comment是我对这条分享的评论仅在人人网和QQ空间使用
oks.setComment("精彩尽在" + url);
// site是分享此内容的网站名称仅在QQ空间使用
oks.setSite(this.getString(R.string.app_name));
// siteUrl是分享此内容的网站地址仅在QQ空间使用
oks.setSiteUrl(url);
oks.setOnFinishListener(new PlatformPage.OnFinishListener() {
@Override
public void onFinish() {
Utils.log("onFinish");
isShowShare = false;
}
}
});
ShareUtils.getInstance(this).showShareWindows(new View(this), url, gameName, icon, newsTitle, isPlugin);
if (newsTitle == null){
DataUtils.onEvent(this, "内容分享", gameName);
}else {
DataUtils.onEvent(this, "内容分享", newsTitle);
}
// 启动分享GUI
oks.show(this);
DataUtils.onEvent(this, "内容分享", title);
isShowShare = true;
}
private boolean isShowShare = false;
public void onEventMainThread(final EBShowDialog showDialog) {
if (!isPause && this.getClass().getName().equals(RunningUtils.getTopActivity(this))) {
if ("hijack".equals(showDialog.getType())) {
DialogUtils.showQqSessionDialog(this, null);// 建议用户联系客服
} else if ("plugin".equals(showDialog.getType())) {
DialogUtils.showPluginDialog(this, new DialogUtils.ConfiremListener(){
DialogUtils.showHijackDialog(this);
} else if ("delete".equals(showDialog.getType())) {
DialogUtils.showUninstallDialog(this, new DialogUtils.ConfiremListener() {
@Override
public void onConfirem() {
if (FileUtils.isEmptyFile(showDialog.getPath())) {
Toast.makeText(BaseActivity.this, "解析包出错(可能被误删了),请重新下载", Toast.LENGTH_SHORT).show();
} else {
startActivity(PackageUtils.getUninstallIntent(BaseActivity.this, showDialog.getPath()));
}
MainActivity.uninstallMap.put(
PackageUtils.getPackageNameByPath(BaseActivity.this, showDialog.getPath()), showDialog.getPath());
startActivity(PackageUtils.getUninstallIntent(BaseActivity.this, showDialog.getPath()));
}
});
} else if ("plugin".equals(showDialog.getType())) {
DialogUtils.showPluginDialog(this, new DialogUtils.ConfiremListener(){
@Override
public void onConfirem() {
MainActivity.uninstallMap.put(
PackageUtils.getPackageNameByPath(BaseActivity.this, showDialog.getPath()), showDialog.getPath());
startActivity(PackageUtils.getUninstallIntent(BaseActivity.this, showDialog.getPath()));
}
}, null);
}
}
}
@ -189,35 +231,35 @@ public class BaseActivity extends Activity implements OnCallBackListener {
@Override
protected void onPause() {
super.onPause();
AppLog("onPause");
DataUtils.onPause(this);
isPause = true;
}
@Override
protected void onRestart() {
super.onRestart();
AppLog("onRestart");
}
@Override
protected void onResume() {
super.onResume();
AppLog("onResume");
DataUtils.onResume(this);
isPause = false;
DownloadManager.getInstance(this).initGameMap();
}
@Override
public void loadDone() {
protected void onStart() {
super.onStart();
AppLog("onStart");
}
@Override
public void loadDone(Object obj) {
protected void onStop() {
super.onStop();
AppLog("onStop");
}
@Override
public void loadError() {
}
@Override
public void loadEmpty() {
}
}

View File

@ -1,421 +0,0 @@
package com.gh.base;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.FileUtils;
import com.gh.common.util.GameUtils;
import com.gh.common.util.NetworkUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.PlatformUtils;
import com.gh.common.util.ShareUtils;
import com.gh.common.view.DownloadDialog;
import com.gh.download.DataWatcher;
import com.gh.download.DownloadEntity;
import com.gh.download.DownloadManager;
import com.gh.download.DownloadStatus;
import com.gh.gamecenter.DownloadManagerActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.eventbus.EBDownloadStatus;
import com.gh.gamecenter.eventbus.EBPackage;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.PackageManager;
import com.tencent.tauth.Tencent;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Administrator on 2016/9/19.
* 游戏详情、新闻详情基类(控制底部下载栏)
*/
public abstract class BaseDetailActivity extends BaseActivity implements View.OnClickListener {
protected TextView actionbar_tv_title;
protected RecyclerView detail_rv_show;
protected LinearLayout detail_ll_bottom;
protected TextView detail_tv_download;
protected ProgressBar detail_pb_progressbar;
protected TextView detail_tv_per;
protected LinearLayout reuse_ll_loading;
protected LinearLayout reuse_no_connection;
protected ImageView iv_share;
protected GameEntity gameEntity;
protected DownloadEntity mDownloadEntity;
protected String entrance;
protected String name;
protected String title;
protected String downloadAddWord;
protected String downloadOffText;
protected Handler handler = new Handler();
private DataWatcher dataWatcher = new DataWatcher() {
@Override
public void onDataChanged(DownloadEntity downloadEntity) {
if (gameEntity != null && gameEntity.getApk().size() == 1) {
String url = gameEntity.getApk().get(0).getUrl();
if (url.equals(downloadEntity.getUrl())) {
if (!"pause".equals(DownloadManager.getInstance(BaseDetailActivity.this).
getStatus(downloadEntity.getUrl()))) {
mDownloadEntity = downloadEntity;
invalidate();
}
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
entrance = getIntent().getStringExtra("entrance");
View contentView = View.inflate(this, R.layout.activity_detail, null);
// 添加分享图标
iv_share = new ImageView(this);
iv_share.setImageResource(R.drawable.share_icon);
iv_share.setOnClickListener(this);
iv_share.setVisibility(View.GONE);
iv_share.setPadding(DisplayUtils.dip2px(this, 13),DisplayUtils.dip2px(this, 11)
,DisplayUtils.dip2px(this, 11),DisplayUtils.dip2px(this, 13));
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
DisplayUtils.dip2px(this, 48), DisplayUtils.dip2px(this, 48));
params.addRule( RelativeLayout.CENTER_VERTICAL);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT );
RelativeLayout reuse_actionbar = (RelativeLayout) contentView.findViewById(
R.id.reuse_actionbar);
reuse_actionbar.addView(iv_share, params);
init(contentView);
actionbar_tv_title = (TextView) findViewById(R.id.actionbar_tv_title);
detail_rv_show = (RecyclerView) findViewById(R.id.detail_rv_show);
detail_ll_bottom = (LinearLayout) findViewById(R.id.detail_ll_bottom);
detail_tv_download = (TextView) findViewById(R.id.detail_tv_download);
detail_pb_progressbar = (ProgressBar) findViewById(R.id.detail_pb_progressbar);
detail_tv_per = (TextView) findViewById(R.id.detail_tv_per);
reuse_ll_loading = (LinearLayout) findViewById(R.id.reuse_ll_loading);
reuse_no_connection = (LinearLayout) findViewById(R.id.reuse_no_connection);
detail_ll_bottom.setOnClickListener(this);
detail_tv_download.setOnClickListener(this);
detail_pb_progressbar.setOnClickListener(this);
detail_tv_per.setOnClickListener(this);
reuse_no_connection.setOnClickListener(this);
}
//接收QQ或者QQ空间分享回调
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == com.tencent.connect.common.Constants.REQUEST_QQ_SHARE
|| requestCode == com.tencent.connect.common.Constants.REQUEST_QZONE_SHARE) {
Tencent.onActivityResultData(requestCode, resultCode, data, ShareUtils.getInstance(this).QqShareListener);
}
}
@Override
protected void onResume() {
super.onResume();
if (gameEntity != null
&& gameEntity.getApk() != null
&& gameEntity.getApk().size() == 1) {
initDownload(true);
}
DownloadManager.getInstance(this).addObserver(dataWatcher);
}
@Override
protected void onPause() {
super.onPause();
DownloadManager.getInstance(this).removeObserver(dataWatcher);
}
protected void initDownload(boolean isCheck) {
if (Config.isShow(this)) {
detail_ll_bottom.setVisibility(View.VISIBLE);
detail_rv_show.setPadding(0, 0, 0,
DisplayUtils.dip2px(getApplicationContext(), 44));
} else {
detail_ll_bottom.setVisibility(View.GONE);
detail_rv_show.setPadding(0, 0, 0, 0);
}
if (gameEntity != null && "光环助手".equals(gameEntity.getName())) {
detail_ll_bottom.setVisibility(View.GONE);
detail_rv_show.setPadding(0, 0, 0, 0);
} else if (gameEntity == null || gameEntity.getApk().isEmpty()) {
detail_tv_download.setVisibility(View.VISIBLE);
detail_pb_progressbar.setVisibility(View.GONE);
detail_tv_per.setVisibility(View.GONE);
if (TextUtils.isEmpty(downloadOffText)) {
detail_tv_download.setText("暂无下载");
} else {
detail_tv_download.setText(downloadOffText);
}
detail_tv_download.setBackgroundResource(R.drawable.game_item_btn_pause_style);
detail_tv_download.setTextColor(0xFF999999);
detail_tv_download.setClickable(false);
} else {
detail_tv_download.setVisibility(View.VISIBLE);
detail_pb_progressbar.setVisibility(View.GONE);
detail_tv_per.setVisibility(View.GONE);
boolean isInstalled = false;
if (gameEntity.getApk() != null && gameEntity.getApk().size() == 1
&& PackageManager.isInstalled(gameEntity.getApk().get(0).getPackageName())) {
isInstalled = true;
}
if (isInstalled) {
if (PackageManager.isCanUpdate(gameEntity.getId(), gameEntity.getApk().get(0).getPackageName())) {
if (TextUtils.isEmpty(downloadAddWord)) {
detail_tv_download.setBackgroundResource(
R.drawable.game_item_btn_download_style);
detail_tv_download.setText(String.format("更新《%s》",
gameEntity.getName()));
} else {
detail_tv_download.setBackgroundResource(
R.drawable.game_item_btn_download_style);
detail_tv_download.setText(String.format("更新《%s》%s",
gameEntity.getName(), downloadAddWord));
}
} else {
if (gameEntity.getTag() != null && gameEntity.getTag().size() != 0
&& !TextUtils.isEmpty(gameEntity.getApk().get(0).getGhVersion())
&& !PackageUtils.isSignature(this, gameEntity.getApk().get(0).getPackageName())) {
if (TextUtils.isEmpty(downloadAddWord)) {
detail_tv_download.setBackgroundResource(
R.drawable.game_item_btn_plugin_style);
detail_tv_download.setText(String.format("插件化《%s》",
gameEntity.getName()));
} else {
detail_tv_download.setBackgroundResource(
R.drawable.game_item_btn_plugin_style);
detail_tv_download.setText(String.format("插件化《%s》%s",
gameEntity.getName(), downloadAddWord));
}
} else {
if (TextUtils.isEmpty(downloadAddWord)) {
detail_tv_download.setBackgroundResource(
R.drawable.game_item_btn_launch_style);
detail_tv_download.setText(String.format("启动《%s》",
gameEntity.getName()));
} else {
detail_tv_download.setBackgroundResource(
R.drawable.game_item_btn_launch_style);
detail_tv_download.setText(String.format("启动《%s》%s",
gameEntity.getName(), downloadAddWord));
}
}
}
} else {
String status = GameUtils.getDownloadBtnText(this, gameEntity);
if ("插件化".equals(status)) {
detail_tv_download.setBackgroundResource(R.drawable.game_item_btn_plugin_style);
} else if ("打开".equals(status)) {
detail_tv_download.setBackgroundResource(R.drawable.game_item_btn_launch_style);
} else {
detail_tv_download.setBackgroundResource(R.drawable.game_item_btn_download_style);
}
if (TextUtils.isEmpty(downloadAddWord)) {
detail_tv_download.setText(String.format(status + "《%s》",
gameEntity.getName()));
} else {
detail_tv_download.setText(String.format(status + "《%s》%s",
gameEntity.getName(), downloadAddWord));
}
}
}
if (isCheck && gameEntity != null
&& gameEntity.getApk() != null
&& gameEntity.getApk().size() == 1) {
String url = gameEntity.getApk().get(0).getUrl();
DownloadEntity downloadEntity = DownloadManager.getInstance(getApplicationContext()).get(url);
if (downloadEntity != null) {
mDownloadEntity = downloadEntity;
detail_tv_download.setVisibility(View.GONE);
detail_pb_progressbar.setVisibility(View.VISIBLE);
detail_tv_per.setVisibility(View.VISIBLE);
invalidate();
}
}
}
private void invalidate() {
detail_pb_progressbar.setProgress((int) (mDownloadEntity.getPercent() * 10));
detail_tv_per.setTextColor(0xFFFFFFFF);
switch (mDownloadEntity.getStatus()) {
case downloading:
case pause:
case timeout:
case neterror:
case waiting:
detail_tv_per.setText("下载中");
break;
case done:
detail_tv_per.setText("安装");
if (mDownloadEntity.isPluggable()
&& PackageManager.isInstalled(mDownloadEntity.getPackageName())) {
detail_pb_progressbar.setProgressDrawable(getResources().getDrawable(R.drawable.progressbar_plugin_radius_style));
} else {
detail_pb_progressbar.setProgressDrawable(getResources().getDrawable(R.drawable.progressbar_normal_radius_style));
}
break;
case cancel:
case hijack:
case notfound:
initDownload(false);
break;
default:
break;
}
}
// 接收下载被删除消息
public void onEvent(EBDownloadStatus status) {
if ("delete".equals(status.getStatus())
&& gameEntity != null
&& gameEntity.getApk() != null
&& gameEntity.getApk().size() == 1) {
String url = gameEntity.getApk().get(0).getUrl();
if (url.equals(status.getUrl())) {
initDownload(false);
}
}
}
// 接受安装、卸载消息
public void onEventMainThread(EBPackage busFour) {
if (gameEntity != null
&& gameEntity.getApk() != null
&& gameEntity.getApk().size() == 1) {
String packageName = gameEntity.getApk().get(0).getPackageName();
if (packageName.equals(busFour.getPackageName())) {
initDownload(false);
}
}
}
@Override
public void onClick(View v) {
if (v == detail_tv_download) {
if (gameEntity != null && !gameEntity.getApk().isEmpty()) {
if (gameEntity.getApk().size() == 1) {
if (NetworkUtils.isWifiConnected(this)) {
download();
} else {
DialogUtils.showDownloadDialog(this, new DialogUtils.ConfiremListener() {
@Override
public void onConfirem() {
download();
}
});
}
} else {
DownloadDialog.getInstance(this)
.showPopupWindow(v, gameEntity, entrance, name + ":" + title);
}
} else {
toast("稍等片刻~!游戏正在上传中...");
}
} else if (v == detail_pb_progressbar || v == detail_tv_per) {
String str = detail_tv_per.getText().toString();
if ("下载中".equals(str)) {
Intent intent = new Intent(this, DownloadManagerActivity.class);
intent.putExtra("url", gameEntity.getApk().get(0).getUrl());
startActivity(intent);
} else if ("安装".equals(str)) {
PackageUtils.launchSetup(this, mDownloadEntity.getPath());
}
}
}
private void download() {
String str = detail_tv_download.getText().toString();
if (str.contains("启动")) {
Map<String, Object> kv = new HashMap<>();
kv.put("版本", gameEntity.getApk().get(0).getPlatform());
kv.put("页面", name);
DataUtils.onEvent(BaseDetailActivity.this, "游戏启动", gameEntity.getName(), kv);
PackageUtils.launchApplicationByPackageName(this, gameEntity.getApk().get(0).getPackageName());
} else {
String method;
if (str.contains("更新")) {
method = "更新";
} else if (str.contains("插件化")) {
method = "插件化";
} else {
method = "下载";
}
ApkEntity apkEntity = gameEntity.getApk().get(0);
String msg = FileUtils.isCanDownload(this, apkEntity.getSize());
if (TextUtils.isEmpty(msg)) {
Map<String, Object> kv = new HashMap<>();
kv.put("版本", apkEntity.getPlatform());
kv.put("状态", "下载开始");
DataUtils.onEvent(BaseDetailActivity.this, "游戏下载", gameEntity.getName(), kv);
Map<String, Object> kv2 = new HashMap<>();
kv2.put("版本", apkEntity.getPlatform());
kv2.put("状态", "下载开始");
kv2.put("页面", name);
kv2.put("位置", entrance);
DataUtils.onEvent(BaseDetailActivity.this, "游戏下载位置", gameEntity.getName(), kv2);
Map<String, Object> kv3 = new HashMap<>();
kv3.put(entrance, "下载数");
kv3.put(entrance, "下载开始");
DataUtils.onEvent(BaseDetailActivity.this, "应用数据", gameEntity.getName(), kv3);
Map<String, Object> map = new HashMap<>();
map.put("game", gameEntity.getName());
map.put("game_id", gameEntity.getId());
map.put("method", method.equals("下载") ? "正常" : method);
map.put("platform", PlatformUtils.getInstance(getApplicationContext())
.getPlatformName(gameEntity.getApk().get(0).getPlatform()));
map.put("status", "开始");
map.put("location", name + ":" + title);
map.put("entrance", entrance);
map.put("btn_status", method);
map.put("network", NetworkUtils.getConnectedType(this));
DataCollectionManager.onEvent(this, "download", map);
DownloadManager.createDownload(this, apkEntity, gameEntity, method, entrance, name + ":" + title);
detail_tv_download.setVisibility(View.GONE);
detail_pb_progressbar.setVisibility(View.VISIBLE);
detail_tv_per.setVisibility(View.VISIBLE);
detail_pb_progressbar.setProgress(0);
detail_tv_per.setText("0.0%");
DownloadManager.getInstance(BaseDetailActivity.this).putStatus(apkEntity.getUrl(), "downloading");
} else {
toast(msg);
}
}
}
}

View File

@ -1,127 +0,0 @@
package com.gh.base;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.gh.common.util.Utils;
import com.gh.gamecenter.listener.OnCallBackListener;
import java.lang.reflect.Field;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
/**
* Created by LGT on 2016/9/4.
* Fragment 基类
*/
public class BaseFragment extends Fragment implements OnCallBackListener {
// private Unbinder unbinder;
protected View view;
protected Handler handler = new Handler();
protected boolean isEverpause;
protected void init(int layout, boolean flag) {
view = View.inflate(getActivity(), layout, null);
// unbinder = ButterKnife.bind(this, view);
if (flag) {
//简化findViewById
try {
Class<?> clazz = this.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
int id = Utils.getId(field.getName());
if (id != -1) {
Utils.log("reflect name = " + field.getName());
field.setAccessible(true);
Class<?> fieldType = field.getType();
Object injectedValue = fieldType.cast(view.findViewById(id));
field.set(this, injectedValue);
field.setAccessible(false);
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
ButterKnife.bind(this, view);
}
}
protected void init(int layout) {
init(layout, true);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isEverpause = false;
EventBus.getDefault().register(this);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
if(container != null){
container.removeView(view);
}
return view;
}
public boolean isEverpause() {
return isEverpause;
}
@Override
public void onPause() {
super.onPause();
isEverpause = true;
}
@Override
public void onResume() {
super.onResume();
isEverpause = false;
}
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
// unbinder.unbind();
}
@Override
public void loadDone() {
}
@Override
public void loadDone(Object obj) {
}
@Override
public void loadError() {
}
@Override
public void loadEmpty() {
}
}

View File

@ -5,6 +5,7 @@ import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
@ -19,29 +20,32 @@ import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.FileUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.RunningUtils;
import com.gh.common.util.ShareUtils;
import com.gh.common.util.Utils;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.MainActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.eventbus.EBShowDialog;
import com.gh.gamecenter.manager.SystemBarTintManager;
import com.gh.gamecenter.manager.SystemBarTintManager.SystemBarConfig;
import java.lang.reflect.Field;
import java.util.ArrayList;
import cn.sharesdk.framework.ShareSDK;
import de.greenrobot.event.EventBus;
import onekeyshare.OnekeyShare;
import onekeyshare.themes.classic.PlatformPage;
public class BaseFragmentActivity extends FragmentActivity {
private String LOG = this.getClass().getName();
private boolean LOG_ON = false;
private boolean isPause;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppLog("onCreate");
Utils.log(this.getClass().getSimpleName());
AppController.getInstance().addActivity(this);
EventBus.getDefault().register(this);
@ -59,7 +63,7 @@ public class BaseFragmentActivity extends FragmentActivity {
setTranslucentStatus(true);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.theme);
tintManager.setStatusBarTintResource(R.color.theme_colors);
SystemBarConfig config = tintManager.getConfig();
contentView.setPadding(0, config.getPixelInsetTop(false), 0,
config.getPixelInsetBottom());
@ -109,6 +113,12 @@ public class BaseFragmentActivity extends FragmentActivity {
AppController.getInstance().removeActivity(this);
}
public void AppLog(String str) {
if (LOG_ON) {
Log.i(LOG, str);
}
}
public void toast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
@ -130,43 +140,77 @@ public class BaseFragmentActivity extends FragmentActivity {
window.setAttributes(winParams);
}
//如果是游戏分享newsTitle默认为空
public void showShare(String url, String gameName, String icon, String newsTitle, ArrayList<String> tag, String entrance, String type) {
public void showShare(String url, String title, String icon, String entrance, String type) {
//判断是否是官方版
boolean isPlugin = false;
if (tag != null){
for (String s : tag) {
if (!"官方版".equals(s)){
isPlugin = true;
}
if (isShowShare){
return;
}
ShareSDK.initSDK(this);
OnekeyShare oks = new OnekeyShare();
// 关闭sso授权
oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
// oks.setNotification(R.drawable.ic_launcher,
// getString(R.string.app_name));
// title标题印象笔记、邮箱、信息、微信、人人网和QQ空间使用
oks.setTitle(title);
// titleUrl是标题的网络链接仅在人人网和QQ空间使用
oks.setTitleUrl(url);
// text是分享文本所有平台都需要这个字段
oks.setText(title + " " + url);
// imagePath是图片的本地路径Linked-In以外的平台都支持此参数
// oks.setImagePath(icon);//确保SDcard下面存在此张图片
oks.setImageUrl(icon);
// url仅在微信包括好友和朋友圈中使用
oks.setUrl(url);
// comment是我对这条分享的评论仅在人人网和QQ空间使用
oks.setComment("精彩尽在" + url);
// site是分享此内容的网站名称仅在QQ空间使用
oks.setSite(this.getString(R.string.app_name));
// siteUrl是分享此内容的网站地址仅在QQ空间使用
oks.setSiteUrl(url);
oks.setOnFinishListener(new PlatformPage.OnFinishListener() {
@Override
public void onFinish() {
Utils.log("onFinish");
isShowShare = false;
}
}
});
ShareUtils.getInstance(this).showShareWindows(new View(this), url, gameName, icon, newsTitle, isPlugin);
if (newsTitle == null){
DataUtils.onEvent(this, "内容分享", gameName);
}else {
DataUtils.onEvent(this, "内容分享", newsTitle);
}
// 启动分享GUI
oks.show(this);
DataUtils.onEvent(this, "内容分享", title);
isShowShare = true;
}
private boolean isShowShare = false;
public void onEventMainThread(final EBShowDialog showDialog) {
if (!isPause && this.getClass().getName().equals(RunningUtils.getTopActivity(this))) {
if ("hijack".equals(showDialog.getType())) {
DialogUtils.showQqSessionDialog(this, null);// 建议用户联系客服
} else if ("plugin".equals(showDialog.getType())) {
DialogUtils.showPluginDialog(this, new DialogUtils.ConfiremListener(){
DialogUtils.showHijackDialog(this);
} else if ("delete".equals(showDialog.getType())) {
DialogUtils.showUninstallDialog(this, new DialogUtils.ConfiremListener() {
@Override
public void onConfirem() {
if (FileUtils.isEmptyFile(showDialog.getPath())) {
Toast.makeText(BaseFragmentActivity.this, "解析包出错(可能被误删了),请重新下载", Toast.LENGTH_SHORT).show();
} else {
startActivity(PackageUtils.getUninstallIntent(BaseFragmentActivity.this, showDialog.getPath()));
}
MainActivity.uninstallMap.put(
PackageUtils.getPackageNameByPath(BaseFragmentActivity.this, showDialog.getPath()), showDialog.getPath());
startActivity(PackageUtils.getUninstallIntent(BaseFragmentActivity.this, showDialog.getPath()));
}
});
} else if ("plugin".equals(showDialog.getType())) {
DialogUtils.showPluginDialog(this, new DialogUtils.ConfiremListener(){
@Override
public void onConfirem() {
MainActivity.uninstallMap.put(
PackageUtils.getPackageNameByPath(BaseFragmentActivity.this, showDialog.getPath()), showDialog.getPath());
startActivity(PackageUtils.getUninstallIntent(BaseFragmentActivity.this, showDialog.getPath()));
}
}, null);
}
}
}
@ -180,16 +224,34 @@ public class BaseFragmentActivity extends FragmentActivity {
@Override
protected void onPause() {
super.onPause();
AppLog("onPause");
DataUtils.onPause(this);
isPause = true;
}
@Override
protected void onResume() {
super.onResume();
DataUtils.onResume(this);
isPause = false;
DownloadManager.getInstance(this).initGameMap();
protected void onRestart() {
super.onRestart();
AppLog("onRestart");
}
@Override
protected void onResume() {
super.onResume();
AppLog("onResume");
DataUtils.onResume(this);
isPause = false;
}
@Override
protected void onStart() {
super.onStart();
AppLog("onStart");
}
@Override
protected void onStop() {
super.onStop();
AppLog("onStop");
}
}

View File

@ -1,5 +1,6 @@
package com.gh.base;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
@ -9,8 +10,11 @@ import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
@ -18,6 +22,8 @@ import com.gh.common.util.FileUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.Utils;
import com.gh.gamecenter.R;
import com.xiaomi.mipush.sdk.ErrorCode;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.xiaomi.mipush.sdk.MiPushCommandMessage;
import com.xiaomi.mipush.sdk.MiPushMessage;
import com.xiaomi.mipush.sdk.PushMessageReceiver;
@ -57,6 +63,17 @@ import java.util.Locale;
*/
public class GHPushMessageReceiver extends PushMessageReceiver {
private String mRegId;
private long mResultCode = -1;
private String mReason;
private String mCommand;
private String mMessage;
private String mTopic;
private String mAlias;
private String mAccount;
private String mStartTime;
private String mEndTime;
@Override
public void onReceivePassThroughMessage(Context context,
MiPushMessage message) {
@ -69,12 +86,15 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
Utils.log("channel = " + channel);
// 1判断渠道号是否一致或是否为ALL
String TD_CHANNEL_ID = (String) PackageUtils.getMetaData(context, context.getPackageName(), "TD_CHANNEL_ID");
if ("ALL".equals(channel) || channel.equalsIgnoreCase(TD_CHANNEL_ID)) {
if ("ALL".equals(channel)
|| TD_CHANNEL_ID
.equalsIgnoreCase(channel)) {
String type = jsonObject.getString("type");
Utils.log("type = " + type);
if ("NEWS".equals(type)) {
// 新闻推送
JSONArray jsonArray = jsonObject.getJSONArray("package");
JSONArray jsonArray = jsonObject
.getJSONArray("package");
ArrayMap<String, Boolean> map = getInstalledMapFromLocal(context);
for (int i = 0; i < jsonArray.length(); i++) {
Boolean b = map.get(jsonArray.getString(i));
@ -99,11 +119,14 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
if (gh_version != null) {
gh_version = gh_version.substring(2);
// 判断gh_version是否相同
if (gh_version.equals(apk.getString("gh_version"))) {
if (gh_version.equals(apk
.getString("gh_version"))) {
// 判断version是否相同
String version = PackageUtils.getVersionByPackage(
context, packageName);
if (apk.getString("version").equals(version)) {
String version = PackageUtils
.getVersionByPackage(context,
packageName);
if (version.equals(apk
.getString("version"))) {
// 版本相同,无需显示插件更新,继续查看是否有可更新的游戏包
continue;
}
@ -124,10 +147,24 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
e.printStackTrace();
}
Log.v(AppController.TAG, "onReceivePassThroughMessage is called. " + message.toString());
Log.v(AppController.TAG, "onReceivePassThroughMessage is called. "
+ message.toString());
String log = context.getString(R.string.recv_passthrough_message,
message.getContent());
if (!TextUtils.isEmpty(message.getTopic())) {
mTopic = message.getTopic();
} else if (!TextUtils.isEmpty(message.getAlias())) {
mAlias = message.getAlias();
}
Message msg = Message.obtain();
msg.obj = log;
AppController.getHandler().sendMessage(msg);
}
private void showNotification(Context context, JSONObject jsonObject, int id) throws JSONException {
private void showNotification(Context context, JSONObject jsonObject, int id)
throws JSONException {
Intent intent = new Intent();
intent.setAction("com.gh.gamecenter.NOTIFICATION");
intent.putExtra("notifyId", id);
@ -148,8 +185,7 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
RemoteViews remoteViews = null;
if (Build.MANUFACTURER.equals("Meizu")
&& (Build.MODEL.startsWith("m")
|| Build.MODEL.startsWith("MX"))) {
&& (Build.MODEL.startsWith("m") || Build.MODEL.startsWith("MX"))) {
remoteViews = new RemoteViews(context.getPackageName(),
R.layout.notification_meizu);
SimpleDateFormat format = new SimpleDateFormat("HH:mm",
@ -157,8 +193,8 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
remoteViews.setTextViewText(R.id.time, format.format(new Date()));
} else if (Build.MANUFACTURER.equals("Xiaomi")
&& (Build.MODEL.startsWith("MI")
|| Build.MODEL.startsWith("HM")
|| Build.MODEL.startsWith("Redmi"))) {
|| Build.MODEL.startsWith("HM") || Build.MODEL
.startsWith("Redmi"))) {
// 小米系统
remoteViews = new RemoteViews(context.getPackageName(),
R.layout.notification_xiaomi);
@ -175,39 +211,27 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
String path = context.getCacheDir() + File.separator
+ url.substring(url.lastIndexOf("/") + 1);
try {
int result = FileUtils.downloadFile(url, path);
if (result == -1) {
// 下载出错使用光环logo
path = null;
}
FileUtils.downloadFile(url, path);
} catch (IOException e) {
// 下载出错使用光环logo
path = null;
e.printStackTrace();
}
if (remoteViews != null) {
if (path == null) {
remoteViews.setImageViewBitmap(R.id.icon, BitmapFactory.decodeResource(context.getResources(), R.drawable.logo));
} else {
remoteViews.setImageViewBitmap(R.id.icon, BitmapFactory.decodeFile(path));
}
remoteViews.setTextViewText(R.id.title, jsonObject.getString("pushTitle"));
remoteViews.setTextViewText(R.id.intro, jsonObject.getString("pushDesc"));
remoteViews.setImageViewBitmap(R.id.icon,
BitmapFactory.decodeFile(path));
// remoteViews.setImageViewResource(R.id.icon, R.drawable.me_icon);
remoteViews.setTextViewText(R.id.title,
jsonObject.getString("pushTitle"));
remoteViews.setTextViewText(R.id.intro,
jsonObject.getString("pushDesc"));
notification.contentView = remoteViews;
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo_black)
.setTicker(jsonObject.getString("pushTitle"))
.setContentTitle(jsonObject.getString("pushTitle"))
.setContentText(jsonObject.getString("pushDesc"))
.setContentIntent(pendingIntent);
if (path == null) {
builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.logo));
} else {
builder.setLargeIcon(BitmapFactory.decodeFile(path));
}
notification = builder.build();
.setContentIntent(pendingIntent)
.setLargeIcon(BitmapFactory.decodeFile(path)).build();
}
notification.defaults = Notification.DEFAULT_SOUND;// 添加系统默认声音
@ -216,7 +240,7 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
}
private ArrayMap<String, Boolean> getInstalledMapFromLocal(Context context) {
ArrayMap<String, Boolean> map = new ArrayMap<>();
ArrayMap<String, Boolean> map = new ArrayMap<String, Boolean>();
ArrayList<String> list = getAllPackageName(context);
for (String str : list) {
map.put(str, true);
@ -225,7 +249,7 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
}
private ArrayList<String> getAllPackageName(Context context) {
ArrayList<String> list = new ArrayList<>();
ArrayList<String> list = new ArrayList<String>();
List<PackageInfo> packageInfos = context.getPackageManager()
.getInstalledPackages(0);
for (int i = 0, size = packageInfos.size(); i < size; i++) {
@ -242,6 +266,21 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
MiPushMessage message) {
Log.v(AppController.TAG, "onNotificationMessageClicked is called. "
+ message.toString());
String log = context.getString(R.string.click_notification_message,
message.getContent());
if (!TextUtils.isEmpty(message.getTopic())) {
mTopic = message.getTopic();
} else if (!TextUtils.isEmpty(message.getAlias())) {
mAlias = message.getAlias();
}
Message msg = Message.obtain();
if (message.isNotified()) {
msg.obj = log;
}
AppController.getHandler().sendMessage(msg);
}
@Override
@ -249,12 +288,105 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
MiPushMessage message) {
Log.v(AppController.TAG, "onNotificationMessageArrived is called. "
+ message.toString());
String log = context.getString(R.string.arrive_notification_message,
message.getContent());
if (!TextUtils.isEmpty(message.getTopic())) {
mTopic = message.getTopic();
} else if (!TextUtils.isEmpty(message.getAlias())) {
mAlias = message.getAlias();
}
Message msg = Message.obtain();
msg.obj = log;
AppController.getHandler().sendMessage(msg);
}
@Override
public void onCommandResult(Context context, MiPushCommandMessage message) {
Log.v(AppController.TAG, "onCommandResult is called. "
+ message.toString());
Log.v(AppController.TAG,
"onCommandResult is called. " + message.toString());
String command = message.getCommand();
List<String> arguments = message.getCommandArguments();
String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments
.get(0) : null);
String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments
.get(1) : null);
String log = "";
if (MiPushClient.COMMAND_REGISTER.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mRegId = cmdArg1;
log = context.getString(R.string.register_success);
} else {
log = context.getString(R.string.register_fail);
}
} else if (MiPushClient.COMMAND_SET_ALIAS.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mAlias = cmdArg1;
log = context.getString(R.string.set_alias_success, mAlias);
} else {
log = context.getString(R.string.set_alias_fail,
message.getReason());
}
} else if (MiPushClient.COMMAND_UNSET_ALIAS.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mAlias = cmdArg1;
log = context.getString(R.string.unset_alias_success, mAlias);
} else {
log = context.getString(R.string.unset_alias_fail,
message.getReason());
}
} else if (MiPushClient.COMMAND_SET_ACCOUNT.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mAccount = cmdArg1;
log = context.getString(R.string.set_account_success, mAccount);
} else {
log = context.getString(R.string.set_account_fail,
message.getReason());
}
} else if (MiPushClient.COMMAND_UNSET_ACCOUNT.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mAccount = cmdArg1;
log = context.getString(R.string.unset_account_success,
mAccount);
} else {
log = context.getString(R.string.unset_account_fail,
message.getReason());
}
} else if (MiPushClient.COMMAND_SUBSCRIBE_TOPIC.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mTopic = cmdArg1;
log = context.getString(R.string.subscribe_topic_success,
mTopic);
} else {
log = context.getString(R.string.subscribe_topic_fail,
message.getReason());
}
} else if (MiPushClient.COMMAND_UNSUBSCRIBE_TOPIC.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
log = context.getString(R.string.unsubscribe_topic_success,
mTopic);
} else {
log = context.getString(R.string.unsubscribe_topic_fail,
message.getReason());
}
} else if (MiPushClient.COMMAND_SET_ACCEPT_TIME.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mStartTime = cmdArg1;
mEndTime = cmdArg2;
log = context.getString(R.string.set_accept_time_success,
mStartTime, mEndTime);
} else {
log = context.getString(R.string.set_accept_time_fail,
message.getReason());
}
} else {
log = message.getReason();
}
Message msg = Message.obtain();
msg.obj = log;
AppController.getHandler().sendMessage(msg);
}
@Override
@ -262,6 +394,47 @@ public class GHPushMessageReceiver extends PushMessageReceiver {
MiPushCommandMessage message) {
Log.v(AppController.TAG, "onReceiveRegisterResult is called. "
+ message.toString());
String command = message.getCommand();
List<String> arguments = message.getCommandArguments();
String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments
.get(0) : null);
String log;
if (MiPushClient.COMMAND_REGISTER.equals(command)) {
if (message.getResultCode() == ErrorCode.SUCCESS) {
mRegId = cmdArg1;
log = context.getString(R.string.register_success);
} else {
log = context.getString(R.string.register_fail);
}
} else {
log = message.getReason();
}
Message msg = Message.obtain();
msg.obj = log;
AppController.getHandler().sendMessage(msg);
}
@SuppressLint("SimpleDateFormat")
public static String getSimpleDate() {
return new SimpleDateFormat("MM-dd hh:mm:ss").format(new Date());
}
public static class PushHandler extends Handler {
private Context context;
public PushHandler(Context context) {
this.context = context;
}
@Override
public void handleMessage(Message msg) {
String s = (String) msg.obj;
if (!TextUtils.isEmpty(s)) {
// Toast.makeText(context, s, Toast.LENGTH_LONG).show();
}
}
}
}

View File

@ -1,247 +0,0 @@
package com.gh.base;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.ConcernActivity;
import com.gh.gamecenter.DownloadManagerActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.SearchActivity;
import com.gh.gamecenter.eventbus.EBDownloadStatus;
import com.gh.gamecenter.eventbus.EBReuse;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.PackageManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.greenrobot.event.EventBus;
/**
* Created by LGT on 2016/9/9.
* 工具栏 搜索控制
*/
public class HomeFragment extends Fragment implements View.OnClickListener {
protected View view;
protected LinearLayout home_ll_top;
protected View home_slide_line;
protected ViewPager home_vp_content;
protected LinearLayout.LayoutParams lparams;
protected Handler handler = new Handler();
private TextView downloadHint;
private TextView searchHint;
private String hint;
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (!TextUtils.isEmpty(hint)) {
outState.putString("hint", hint);
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
hint = savedInstanceState.getString("hint");
}
view = View.inflate(getActivity(), R.layout.fragment_home, null);
SharedPreferences sp = getActivity().getSharedPreferences(
Config.PREFERENCE, Context.MODE_PRIVATE);
LinearLayout home_actionbar = (LinearLayout) view.findViewById(R.id.home_actionbar);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, sp.getInt("actionbar_height",
DisplayUtils.dip2px(getActivity(), 48)));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
int top = DisplayUtils.getInternalDimensionSize(getResources(), "status_bar_height");
home_actionbar.setPadding(0, top, 0, 0);
lparams.height += top;
}
home_actionbar.setLayoutParams(lparams);
initActionBar();
home_ll_top = (LinearLayout) view.findViewById(R.id.home_ll_top);
home_slide_line = view.findViewById(R.id.home_slide_line);
home_vp_content = (ViewPager) view.findViewById(R.id.home_vp_content);
EventBus.getDefault().register(this);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
if (container != null) {
container.removeView(view);
}
return view;
}
private void initActionBar() {
view.findViewById(R.id.actionbar_rl_download).setOnClickListener(this);
view.findViewById(R.id.actionbar_iv_search).setOnClickListener(this);
view.findViewById(R.id.actionbar_notification).setOnClickListener(this);
if (Config.isShow(getActivity())) {
view.findViewById(R.id.actionbar_rl_download).setVisibility(View.VISIBLE);
} else {
view.findViewById(R.id.actionbar_rl_download).setVisibility(View.GONE);
}
downloadHint = (TextView) view.findViewById(R.id.action_tip);
int updateSize = PackageManager.getUpdateListSize();
int downloadSize = DownloadManager.getInstance(getActivity()).getAll().size();
if (downloadSize != 0) {
downloadHint.setVisibility(View.VISIBLE);
downloadHint.setText(String.valueOf(downloadSize));
} else if (updateSize != 0) {
downloadHint.setVisibility(View.VISIBLE);
downloadHint.setText(String.valueOf(updateSize));
} else {
downloadHint.setVisibility(View.GONE);
}
searchHint = (TextView) view.findViewById(R.id.actionbar_search_input);
searchHint.setOnClickListener(this);
if (!TextUtils.isEmpty(hint)) {
searchHint.setHint(hint);
}
}
@Override
public void onClick(View v) {
final int id = v.getId();
if (id == R.id.actionbar_notification) {
DataUtils.onEvent(getActivity(), "主页", "关注图标");
Map<String, Object> map = new HashMap<>();
map.put("location", "关注图标");
map.put("page", "主页");
DataCollectionManager.onEvent(getActivity(), "click-item", map);
startActivity(new Intent(getActivity(), ConcernActivity.class));
} else if (id == R.id.actionbar_rl_download) {
DataUtils.onEvent(getActivity(), "主页", "下载图标");
Map<String, Object> map = new HashMap<>();
map.put("location", "下载图标");
map.put("page", "主页");
DataCollectionManager.onEvent(getActivity(), "click-item", map);
startActivity(new Intent(getActivity(), DownloadManagerActivity.class));
} else if (id == R.id.actionbar_search_input) {
DataUtils.onEvent(getActivity(), "主页", "搜索框");
Map<String, Object> map = new HashMap<>();
map.put("location", "搜索框");
map.put("page", "主页");
DataCollectionManager.onEvent(getActivity(), "click-item", map);
Intent goSearch = new Intent(getActivity(), SearchActivity.class);
goSearch.putExtra("clicked", false);
goSearch.putExtra("hint", hint);
startActivity(goSearch);
} else if (id == R.id.actionbar_iv_search) {
DataUtils.onEvent(getActivity(), "主页", "搜索图标");
Map<String, Object> map = new HashMap<>();
map.put("location", "搜索图标");
map.put("page", "主页");
DataCollectionManager.onEvent(getActivity(), "click-item", map);
Intent searchIntent = new Intent(getActivity(), SearchActivity.class);
searchIntent.putExtra("clicked", true);
searchIntent.putExtra("hint", hint);
startActivity(searchIntent);
}
}
// 打开下载按钮事件
public void onEventMainThread(EBReuse reuse) {
if ("Refresh".equals(reuse.getType())) {
if (Config.isShow(getActivity())) {
view.findViewById(R.id.actionbar_rl_download).setVisibility(View.VISIBLE);
} else {
view.findViewById(R.id.actionbar_rl_download).setVisibility(View.GONE);
}
}
}
public void setHint(String hint) {
if (!TextUtils.isEmpty(hint)) {
this.hint = hint;
if (searchHint != null) {
searchHint.setHint(hint);
}
}
}
public void onEventMainThread(EBDownloadStatus status) {
int updateSize = PackageManager.getUpdateListSize();
int downloadSize = DownloadManager.getInstance(getActivity()).getAll().size();
if (downloadSize != 0) {
downloadHint.setVisibility(View.VISIBLE);
downloadHint.setText(String.valueOf(downloadSize));
} else if (updateSize != 0) {
downloadHint.setVisibility(View.VISIBLE);
downloadHint.setText(String.valueOf(updateSize));
} else {
downloadHint.setVisibility(View.GONE);
}
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
List<Fragment> list = getChildFragmentManager().getFragments();
if (list != null) {
if (hidden) {
for (Fragment fragment : getChildFragmentManager().getFragments()) {
transaction.hide(fragment);
}
} else {
for (Fragment fragment : getChildFragmentManager().getFragments()) {
transaction.show(fragment);
}
}
}
transaction.commit();
}
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}

View File

@ -1,20 +1,16 @@
package com.gh.common.constant;
import com.gh.gamecenter.SplashScreenActivity;
import android.content.Context;
import android.content.SharedPreferences;
public class Config {
public final class Config {
// test host dev.ghzhushou.com/api
public static final String HOST = "http://api.ghzhushou.com/";
// public static final String HOST = "http://115.28.145.16:9001/";
public static final String HOST = "http://api.ghzhushou.com/v2d2/";
public static final String USER_HOST = "http://user.ghzhushou.com/v1d0/";
public static final String COMMENT_HOST = "http://comment.ghzhushou.com/v1d0/";
public static final String DATA_HOST = "http://data.ghzhushou.com/";
public static final String PREFERENCE = "ghzhushou";
public static boolean isShow(Context context) {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
return sp.getBoolean("isShow", true);
}
// public static final boolean isShow = true;
public static final boolean isShow = SplashScreenActivity.isShow;
}

View File

@ -38,5 +38,4 @@ public class Constants {
public static final int SEARCH_CD = 5 * 60 * 1000;
//评论 cd间隔
public static final int COMMENT_CD = 60 * 1000;
}

View File

@ -1,24 +0,0 @@
package com.gh.common.constant;
/**
* Created by LGT on 2016/10/16.
*/
public class ItemViewType {
public static final int COLUMN_HEADER = 0; // 专题头部布局
public static final int GAME_SLIDE = 1; // 滚动图布局
public static final int GAME_NORMAL = 2; // 正常游戏布局
public static final int GAME_TEST = 3; // 测试游戏布局
public static final int GAME_IMAGE = 4; // 游戏大图布局
public static final int NEWS_HEADER = 5; // 新闻头部布局
public static final int NEWS_TEXT = 6; // 新闻文本布局
public static final int NEWS_IMAGE = 7; // 新闻带图布局
public static final int NEWS_IMAGE1 = 8; // 新闻带一张小图布局
public static final int NEWS_IMAGE2 = 9; // 新闻带三张小图布局
public static final int NEWS_IMAGE3 = 10; // 新闻带一张大图布局
public static final int NEWS_DIGEST = 11; // 新闻摘要布局
public static final int SEARCH_NORMAL = 12; // 搜索正常布局
public static final int SEARCH_DELETE = 13; // 清空历史记录布局
public static final int LOADING = 14; // 加载布局
}

View File

@ -1,77 +0,0 @@
package com.gh.common.util;
import android.content.Context;
import android.content.SharedPreferences;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
/**
* Created by khy on 2016/11/24.
* 该类定义了微博授权时所需要的参数。
*/
public class AccessTokenKeeper {
private static final String PREFERENCES_NAME = "com_weibo_sdk_android";
private static final String KEY_UID = "uid";
private static final String KEY_ACCESS_TOKEN = "access_token";
private static final String KEY_EXPIRES_IN = "expires_in";
private static final String KEY_REFRESH_TOKEN = "refresh_token";
/**
* 保存 Token 对象到 SharedPreferences。
*
* @param context 应用程序上下文环境
* @param token Token 对象
*/
public static void writeAccessToken(Context context, Oauth2AccessToken token) {
if (null == context || null == token) {
return;
}
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
SharedPreferences.Editor editor = pref.edit();
editor.putString(KEY_UID, token.getUid());
editor.putString(KEY_ACCESS_TOKEN, token.getToken());
editor.putString(KEY_REFRESH_TOKEN, token.getRefreshToken());
editor.putLong(KEY_EXPIRES_IN, token.getExpiresTime());
editor.commit();
}
/**
* 从 SharedPreferences 读取 Token 信息。
*
* @param context 应用程序上下文环境
*
* @return 返回 Token 对象
*/
public static Oauth2AccessToken readAccessToken(Context context) {
if (null == context) {
return null;
}
Oauth2AccessToken token = new Oauth2AccessToken();
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
token.setUid(pref.getString(KEY_UID, ""));
token.setToken(pref.getString(KEY_ACCESS_TOKEN, ""));
token.setRefreshToken(pref.getString(KEY_REFRESH_TOKEN, ""));
token.setExpiresTime(pref.getLong(KEY_EXPIRES_IN, 0));
return token;
}
/**
* 清空 SharedPreferences 中 Token信息。
*
* @param context 应用程序上下文环境
*/
public static void clear(Context context) {
if (null == context) {
return;
}
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.commit();
}
}

View File

@ -1,87 +0,0 @@
package com.gh.common.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import java.io.IOException;
/**
* Created by LGT on 2016/10/21.
*/
public class BitmapUtils {
/**
* 根据文件路径返回bitmap
* @param filepath 文件路径
* @param w 宽
* @param h 高
* @return bitmap
*/
public static Bitmap getBitmapByFile(String filepath, int w, int h) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
// 设置为ture只获取图片大小
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.RGB_565;
// 返回为空
BitmapFactory.decodeFile(filepath, options);
int width = options.outWidth;
int height = options.outHeight;
float scaleWidth = 0.f, scaleHeight = 0.f;
if (width > w || height > h) {
// 缩放
scaleWidth = ((float) width) / w;
scaleHeight = ((float) height) / h;
}
options.inJustDecodeBounds = false;
int scale = (int) Math.ceil(Math.max(scaleWidth, scaleHeight));
if (scale % 2 == 1) {
scale += 1;
}
options.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filepath, options);
bitmap = rotatePicture(filepath, bitmap);
if (bitmap != null) {
return bitmap;
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Bitmap rotatePicture(String path, Bitmap bitmap) {
int rotate = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
if (rotate != 0) {
Matrix matrix = new Matrix();
matrix.setRotate(rotate);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
} else {
return bitmap;
}
}
}

View File

@ -1,98 +0,0 @@
package com.gh.common.util;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.LinearLayout;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gh.gamecenter.ViewImageActivity;
import java.util.ArrayList;
import java.util.List;
/**
* Created by khy on 2016/11/8.
*
* 初始化资讯关注-内容图片
*
**/
public class ConcernContentUtils {
public static void addContentPic(int width, LinearLayout linearLayout, List<String> list, Context context) {
int count = list.size();
LinearLayout ll;
int index = 0;
for (int i = 0, size = (int) Math.ceil(list.size() / 3.0f); i < size; i++) {
switch (count % 3) {
case 0:
ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.HORIZONTAL);
for (int j = 0; j < 3; j++) {
ll.addView(getImageView(list, index, width, 0, context));
index += 1;
}
linearLayout.addView(ll);
count -= 3;
break;
case 1:
linearLayout.addView(getImageView(list, index, width, 1, context));
count -= 1;
index += 1;
break;
case 2:
ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.HORIZONTAL);
for (int j = 0; j < 2; j++) {
ll.addView(getImageView(list, index, width, 2, context));
index += 1;
}
linearLayout.addView(ll);
count -= 2;
break;
}
}
}
private static SimpleDraweeView getImageView(final List<String> list, final int position, int width, int type, final Context context) {
SimpleDraweeView imageView;
if (type == 0) {
imageView = new SimpleDraweeView(context);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
0, width / 3 - DisplayUtils.dip2px(context, 4));
lparams.setMargins(DisplayUtils.dip2px(context, 2), 0,
DisplayUtils.dip2px(context, 2), DisplayUtils.dip2px(context, 4));
lparams.weight = 1;
imageView.setLayoutParams(lparams);
ImageUtils.getInstance().display(context.getResources(), imageView, ScalingUtils.ScaleType.CENTER_CROP, list.get(position));
} else if (type == 1) {
imageView = new SimpleDraweeView(context);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(width, width / 2);
lparams.setMargins(DisplayUtils.dip2px(context, 2), 0,
DisplayUtils.dip2px(context, 2), DisplayUtils.dip2px(context, 4));
imageView.setLayoutParams(lparams);
ImageUtils.getInstance().display(context.getResources(), imageView, ScalingUtils.ScaleType.CENTER_CROP, list.get(position));
} else {
imageView = new SimpleDraweeView(context);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
0, width / 2 - DisplayUtils.dip2px(context, 4));
lparams.setMargins(DisplayUtils.dip2px(context, 2), 0,
DisplayUtils.dip2px(context, 2), DisplayUtils.dip2px(context, 4));
lparams.weight = 1;
imageView.setLayoutParams(lparams);
ImageUtils.getInstance().display(context.getResources(), imageView, ScalingUtils.ScaleType.CENTER_CROP, list.get(position));
}
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent checkIntent = new Intent(context, ViewImageActivity.class);
checkIntent.putExtra("urls", (ArrayList<String>) list);
checkIntent.putExtra("current", position);
checkIntent.putExtra("ScaleType", "FIT_CENTER");
context.startActivity(checkIntent);
}
});
return imageView;
}
}

View File

@ -1,154 +0,0 @@
package com.gh.common.util;
import android.content.Context;
import android.telephony.TelephonyManager;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest;
import com.gh.gamecenter.volley.extended.StringExtendedRequest;
import org.json.JSONArray;
import java.util.UUID;
/**
* Created by khy on 2016/8/24.
*/
public class ConcernUtils {
public static void loadConcernData(final String url, final DownJsonListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
if (listener != null){
listener.downSucced(response.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (listener != null){
listener.downFailed();
}
}
});
request.setShouldCache(false);
AppController.addToRequestQueue(request);
}
}).start();
}
public static void postConcernGameId(final String gameId, final String postUrl, final DownJsonListener listener){
new Thread(new Runnable() {
@Override
public void run() {
JSONArray data = new JSONArray();
data.put(gameId);
StringExtendedRequest request = new StringExtendedRequest(
Request.Method.POST, postUrl, data.toString(),
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (listener != null) {
listener.downSucced("关注成功");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (listener != null) {
listener.downFailed();
}
}
});
request.setShouldCache(false);
AppController.addToRequestQueue(request);
}
}).start();
}
public static void deleteConcernData(final String url, final DownJsonListener listener){
new Thread(new Runnable() {
@Override
public void run() {
StringExtendedRequest request = new StringExtendedRequest(
Request.Method.DELETE, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (listener != null) {
listener.downSucced("删除成功");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (listener != null) {
listener.downFailed();
}
}
});
request.setShouldCache(false);
AppController.addToRequestQueue(request);
}
}).start();
}
public static void updateConcernData(final String url, final JSONArray data, final DownJsonListener listener){
new Thread(new Runnable() {
@Override
public void run() {
StringExtendedRequest request = new StringExtendedRequest(
Request.Method.PUT, url, data.toString(),
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (listener != null) {
listener.downSucced("更新设备关注成功");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (listener != null) {
listener.downFailed();
}
}
});
request.setShouldCache(false);
AppController.addToRequestQueue(request);
}
}).start();
}
public interface DownJsonListener {
void downSucced(String str);
void downFailed();
}
// 获取设备号ID
public static String uuid(Context context){
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final String tmDevice, tmSerial, androidId;
tmDevice = "" + tm.getDeviceId();
tmSerial = "" + tm.getSimSerialNumber();
androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
return deviceUuid.toString();
}
}

View File

@ -21,14 +21,14 @@ public class DataUtils {
public static void init(Application application) {
//TalkingData
//dubug true release false
TCAgent.LOG_ON = true;
TCAgent.LOG_ON = false;
TCAgent.init(application);
TCAgent.setReportUncaughtExceptions(true);
//MTA
// 打开debug开关可查看mta上报日志或错误
// dubug true release false
StatConfig.setDebugEnable(true);
StatConfig.setDebugEnable(false);
// 收集未处理的异常
StatConfig.setAutoExceptionCaught(true);
// 设置数据上报策略

View File

@ -15,16 +15,14 @@ public class DeviceUtils {
StringBuffer buffer = new StringBuffer();
String imei = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
if (!TextUtils.isEmpty(imei)) {
buffer.append("imei=");
buffer.append(imei);
buffer.append("imei=" + imei);
}
String android_id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
if (!TextUtils.isEmpty(android_id)) {
if (buffer.length() != 0) {
buffer.append(",");
}
buffer.append("android_id=");
buffer.append(android_id);
buffer.append("android_id=" + android_id);
}
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String mac = wm.getConnectionInfo().getMacAddress();
@ -32,8 +30,7 @@ public class DeviceUtils {
if (buffer.length() != 0) {
buffer.append(",");
}
buffer.append("mac=");
buffer.append(mac);
buffer.append("mac=" + mac);
}
return buffer.toString();
}

View File

@ -17,7 +17,6 @@ import java.io.OutputStream;
* Created by sunpengfei on 15/11/4.
*/
public class DexUtils {
private static final int BUF_SIZE = 2048;
public static boolean prepareAssetsDex(Context context, File dexInternalStoragePath, String dex_file) {
@ -54,7 +53,7 @@ public class DexUtils {
}
}
public static boolean prepareDex(File dexInternalStoragePath, File dex_file) {
public static boolean prepareDex(Context context, File dexInternalStoragePath, File dex_file) {
BufferedInputStream bis = null;
OutputStream dexWriter = null;
@ -87,5 +86,4 @@ public class DexUtils {
return false;
}
}
}

View File

@ -1,14 +1,13 @@
package com.gh.common.util;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;
@ -28,147 +27,265 @@ public class DialogUtils {
return dialog;
}
private static boolean isShow = false;
private static boolean isShowHijackDialog = false;
public static void showWarningDialog(Context context, String title, CharSequence msg, String cancel, String confirm,
final ConfiremListener cmListener, final CancelListener clListener) {
if (isShow) {
public static void showHijackDialog(final Context context) {
if (isShowHijackDialog) {
return;
}
isShow = true;
isShowHijackDialog = true;
final Dialog dialog = new Dialog(context);
View view = View.inflate(context,
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);
View view = View.inflate(context, R.layout.common_alertdialog, null);
content.setText("您当前网络环境异常,下载地址已被替换(网络劫持),请更换网络环境进行下载。");
// 标题
TextView alertdialog_title = (TextView) view.findViewById(R.id.alertdialog_title);
alertdialog_title.setText(title);
// 内容
TextView alertdialog_content = (TextView) view.findViewById(R.id.alertdialog_content);
alertdialog_content.setText(msg);
// 取消按钮
TextView alertdialog_cannel = (TextView) view.findViewById(R.id.alertdialog_cannel);
alertdialog_cannel.setText(cancel);
alertdialog_cannel.setOnClickListener(new View.OnClickListener() {
TextView cancel = (TextView) view
.findViewById(R.id.delete_dialog_cancel);
cancel.setText("取消");
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
if (clListener != null) {
clListener.onCancel();
}
}
});
// 确定按钮
TextView alertdialog_confirm = (TextView) view.findViewById(R.id.alertdialog_confirm);
alertdialog_confirm.setText(confirm);
alertdialog_confirm.setOnClickListener(new View.OnClickListener() {
TextView confirem = (TextView) view
.findViewById(R.id.delete_dialog_confirm);
confirem.setText("确定");
confirem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 跳转wifi管理界面
Intent intent = new Intent("android.settings.WIFI_SETTINGS");
context.startActivity(intent);
dialog.dismiss();
if (cmListener != null) {
cmListener.onConfirem();
}
}
});
dialog.setOnDismissListener(new Dialog.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
isShow = false;
isShowHijackDialog = false;
}
});
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
}
private static boolean isShowDeleteDialog = false;
public static void showUninstallDialog(final Context context, final ConfiremListener listener) {
if (isShowDeleteDialog) {
return;
}
isShowDeleteDialog = true;
final Dialog dialog = new Dialog(context);
View view = View.inflate(context,
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);
content.setText("您已安装了官方原版,该版本与插件版本冲突,是否卸载官方原版?");
TextView cancel = (TextView) view
.findViewById(R.id.delete_dialog_cancel);
cancel.setText("忽略");
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView confirem = (TextView) view
.findViewById(R.id.delete_dialog_confirm);
confirem.setText("卸载");
confirem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
if (listener != null) {
listener.onConfirem();
}
}
});
dialog.setOnDismissListener(new Dialog.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
isShowDeleteDialog = false;
}
});
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
}
public static void showWarningDialog(Context context, final ConfiremListener listener) {
final Dialog dialog = new Dialog(context);
View view = View.inflate(context, 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);
content.setText("您当前的网络为2G/3G/4G下载将会消耗移动流量是否继续下载");
TextView cancel = (TextView) view
.findViewById(R.id.delete_dialog_cancel);
cancel.setText("取消");
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView confirem = (TextView) view
.findViewById(R.id.delete_dialog_confirm);
confirem.setText("继续");
confirem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
if (listener != null) {
listener.onConfirem();
}
}
});
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
}
public static void showSuccessDialog(Context context) {
final Dialog dialog = new Dialog(context);
View view = View.inflate(context, R.layout.gamedetails_attention_dialog, null);
TextView title = (TextView) view.findViewById(R.id.dialog_title);
title.setText("关注成功");
TextView confirm = (TextView) view.findViewById(R.id.dialog_confirm);
confirm.setText("我知道了");
confirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView message = (TextView) view.findViewById(R.id.dialog_message);
message.setText("游戏的最新动态消息会优先提醒您,包括攻略、资讯、开服信息、开测信息以及最新的插件。");
view.findViewById(R.id.dialog_rl_cancel).setVisibility(View.GONE);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
}
public static void showCancelDialog(Context context, final ConfiremListener listener) {
final Dialog dialog = new Dialog(context);
View view = View.inflate(context, R.layout.gamedetails_attention_dialog, null);
TextView title = (TextView) view.findViewById(R.id.dialog_title);
title.setText("取消关注");
TextView cancel = (TextView) view.findViewById(R.id.dialog_cancel);
cancel.setText("取消");
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView message = (TextView) view.findViewById(R.id.dialog_message);
Spanned content = Html
.fromHtml("取消关注游戏后,您将无法及时收到游戏的<font color='#ff0000'>攻略</font>、<font color='#ff0000'>资讯</font>等最新动态提醒,您确定取消吗?");
message.setText(content);
view.findViewById(R.id.dialog_rl_confirm).setVisibility(View.VISIBLE);
view.findViewById(R.id.dialog_confirm).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
if (listener != null) {
listener.onConfirem();
}
}
});
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
}
public static void showPluginDialog(Context context, final ConfiremListener cListener,
final DismissListener dListener) {
final Dialog dialog = new Dialog(context);
View view = View.inflate(context, 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 spanned = Html.fromHtml("您将进行插件化安装以实现插件功能,此过程将"
+ "<font color=\"#ff0000\">卸载</font>" + "当前使用的版本并"
+ "<font color=\"#ff0000\">安装插件版本</font>" + "");
content.setText(spanned);
TextView cancel = (TextView) view
.findViewById(R.id.delete_dialog_cancel);
cancel.setText("取消");
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView confirm = (TextView) view
.findViewById(R.id.delete_dialog_confirm);
confirm.setText("确定");
confirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
if (cListener != null) {
cListener.onConfirem();
}
}
});
if (dListener != null) {
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
dListener.onDismiss();
}
});
}
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
}
public static void showHijackDialog(final Context context) {
showWarningDialog(context, "警告", "您当前网络环境异常,下载地址已被替换(网络劫持),请更换网络环境进行下载。",
new ConfiremListener() {
@Override
public void onConfirem() {
// 跳转wifi管理界面
Intent intent = new Intent("android.settings.WIFI_SETTINGS");
context.startActivity(intent);
}
});
}
// 网络劫持时 打开QQ客户端创建临时会话
public static void showQqSessionDialog(final Context context, String qq) {
if (qq == null) {
qq = "2586716223";// 默认客服QQ
}
final String finalQq = qq;
showWarningDialog(context, "警告", "您当前网络环境异常,下载地址可能被运营商恶意替换(网络劫持)" +
"如多次下载失败请联系客服获取正确的下载地址客服QQ" + qq + ""
, "取消", "前往QQ", new ConfiremListener() {
@Override
public void onConfirem() {
if (ShareUtils.isQQClientAvailable(context)) {
//安装了QQ会直接调用QQ打开手机QQ进行会话 QQ号2586716223
String str = "mqqwpa://im/chat?chat_type=wpa&uin=" + finalQq + "&version=1&src_type=web&web_src=oicqzone.com";
Uri uri = Uri.parse(str);
Intent it = new Intent(Intent.ACTION_VIEW, uri);
context.startActivity(it);
} else {
//没有安装QQ 复制账号
ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setText(finalQq);
Utils.toast(context,"已复制" + finalQq);
}
}
}, null);
}
public static void showWarningDialog(Context context, String title, CharSequence msg, final ConfiremListener listener) {
showWarningDialog(context, title, msg, "取消", "确定", listener, null);
}
public static void showDownloadDialog(Context context, ConfiremListener listener) {
showWarningDialog(context, "下载提示", "您当前使用的网络为2G/3G/4G开始下载将会消耗移动流量确定下载", listener);
}
public static void showCancelDialog(Context context, final ConfiremListener listener) {
Spanned content = Html.fromHtml("取消关注游戏后,您将无法及时收到游戏" +
"<font color='#ff0000'>攻略</font>、" +
"<font color='#ff0000'>资讯</font>等最新动态提醒。");
showWarningDialog(context, "取消关注", content, "暂不取消", "确定取消", listener, null);
}
public static void showPluginDialog(Context context, final ConfiremListener listener) {
Spanned spanned = Html.fromHtml("您将进行插件化安装以实现插件功能,此过程将"
+ "<font color=\"#ff0000\">卸载</font>" + "当前使用的版本并"
+ "<font color=\"#ff0000\">安装插件版本</font>");
showWarningDialog(context, "插件化安装", spanned, listener);
}
public static void showDisclaimerDialog(Context context, String content) {
final Dialog disclaimerDialog = new Dialog(context);
View view = View.inflate(context, R.layout.dialog_disclaimer, null);
// TextView title = (TextView) view.findViewById(R.id.disclaimer_title);
// title.setText("免责声明");
TextView message = (TextView) view.findViewById(R.id.disclaimer_message);
View view = View.inflate(context, 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_confirm).setOnClickListener(
new View.OnClickListener() {
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();
@ -178,8 +295,8 @@ public class DialogUtils {
void onConfirem();
}
public interface CancelListener{
void onCancel();
public interface DismissListener{
void onDismiss();
}
}

View File

@ -25,7 +25,7 @@ public class DisplayUtils {
* 将px值转换为sp值保证文字大小不变
*
* @param pxValue
* @param pxValue
* @param fontScale
* DisplayMetrics类中属性scaledDensity
* @return
*/
@ -38,7 +38,7 @@ public class DisplayUtils {
* 将sp值转换为px值保证文字大小不变
*
* @param spValue
* @param spValue
* @param fontScale
* DisplayMetrics类中属性scaledDensity
* @return
*/

File diff suppressed because it is too large Load Diff

View File

@ -5,10 +5,9 @@ import android.os.Environment;
import android.os.StatFs;
import android.os.StrictMode;
import org.apache.http.HttpStatus;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
@ -39,14 +38,10 @@ public class FileUtils {
File file = new File(dir + File.separator + TEST_FILE_NAME);
if (!file.exists()) {
try {
if (!file.createNewFile()) {
// cannot create file
Utils.log("cannot create file");
dir = null;
}
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
// cannot create file
//cannot create file
Utils.log("cannot create file");
dir = null;
}
@ -55,11 +50,6 @@ public class FileUtils {
if (dir == null) {
String baseDir = context.getFilesDir().getAbsolutePath();
dir = checkDir(baseDir + File.separator + "gh-download");
try {
Runtime.getRuntime().exec("chmod 755 " + dir);
} catch (IOException e) {
e.printStackTrace();
}
}
return dir;
}
@ -86,10 +76,7 @@ public class FileUtils {
private static String checkDir(String dir) {
File directory = new File(dir);
if (directory.exists() && !directory.isDirectory()) {
directory.delete();
}
if (!directory.exists()) {
if (!directory.exists() || !directory.isDirectory()) {
directory.mkdirs();
}
return dir;
@ -109,6 +96,21 @@ public class FileUtils {
}
return true;
}
public static void checkDirExists(String dirName) {
File file = Environment.getExternalStorageDirectory();
if (file.isDirectory()) {
File[] fs = file.listFiles();
for (int i = 0; i < fs.length; i++) {
if (fs[i].isDirectory()
&& fs[i].getName().equalsIgnoreCase(dirName)
&& !fs[i].getName().equals(dirName)) {
fs[i].delete();
break;
}
}
}
}
public static boolean isMounted() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
@ -132,13 +134,15 @@ public class FileUtils {
@SuppressWarnings("deprecation")
public static float getFreeSpaceByPath(String path) {
StatFs statfs = new StatFs(path);
long blockSize = statfs.getBlockSize();
long availableBlocks = statfs.getAvailableBlocks();
return availableBlocks * blockSize / 1024f / 1024f;
}
public static String isCanDownload(Context context, String size) {
public static String isCanDownload(String size) {
String msg = null;
String packageSizeStr = "";
for (int i = 0; i < size.length(); i++) {
@ -150,7 +154,8 @@ public class FileUtils {
if (packageSizeStr.length() != 0) {
packageSize = Float.valueOf(packageSizeStr);
}
float freeSpace = getFreeSpaceByPath(getDownloadDir(context));
float freeSpace = getFreeSpaceByPath(Environment
.getExternalStorageDirectory().getAbsolutePath());
if (freeSpace < packageSize) {
msg = "手机存储空间不足,无法进行下载!";
}
@ -163,7 +168,8 @@ public class FileUtils {
DataInputStream dis = null;
FileOutputStream fos = null;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
HttpURLConnection connection = (HttpURLConnection) new URL(url)
.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5 * 1000);
connection.setReadTimeout(5 * 1000);
@ -187,7 +193,7 @@ public class FileUtils {
dis.close();
}
return code;
} catch (IOException e) {
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
@ -201,7 +207,7 @@ public class FileUtils {
}
// 上传文件
public static JSONObject uploadFile(String url, String filePath, String token) {
public static String uploadFile(String url, String filePath, String token) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = UUID.randomUUID().toString().replaceAll("-", "")
@ -214,23 +220,21 @@ public class FileUtils {
* post method must write something to the connection
*/
connection.setDoOutput(true);
// Read from the connection. Default is true.
/* Read from the connection. Default is true. */
connection.setDoInput(true);
// Post cannot use caches
/* Post cannot use caches */
connection.setUseCaches(false);
// Set the post method. Default is GET
/* Set the post method. Default is GET */
connection.setRequestMethod("POST");
connection.setConnectTimeout(5 * 1000);
connection.setReadTimeout(5 * 1000);
// 设置请求属性
/* 设置请求属性 */
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
if (token != null) {
connection.setRequestProperty("TOKEN", token);
connection.setRequestProperty("Auth", token);
}
// 设置StrictMode 否则HTTPURLConnection连接失败因为这是在主进程中进行网络连接
/* 设置StrictMode 否则HTTPURLConnection连接失败因为这是在主进程中进行网络连接 */
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
@ -239,144 +243,60 @@ public class FileUtils {
Utils.log("name = " + file.getName());
Utils.log("length = " + file.length());
}
// 设置DataOutputStreamgetOutputStream中默认调用connect()
/* 设置DataOutputStreamgetOutputStream中默认调用connect() */
DataOutputStream dos = new DataOutputStream(
connection.getOutputStream()); // output
// to the connection
// to
// the
// connection
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; "
+ "name=\"Filedata\";filename=\"" + file.getName() + "\""
+ end);
dos.writeBytes(end);
// 取得文件的FileInputStream
/* 取得文件的FileInputStream */
FileInputStream fStream = new FileInputStream(file);
// 设置每次写入8192bytes
/* 设置每次写入8192bytes */
int bufferSize = 8192;
byte[] buffer = new byte[bufferSize]; // 8k
int length;
// 从文件读取数据至缓冲区
int length = -1;
/* 从文件读取数据至缓冲区 */
while ((length = fStream.read(buffer)) != -1) {
// 将资料写入DataOutputStream中
/* 将资料写入DataOutputStream中 */
dos.write(buffer, 0, length);
}
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
// 关闭流写入的东西自动生成Http正文
/* 关闭流写入的东西自动生成Http正文 */
fStream.close();
// 关闭DataOutputStream
dos.flush();
/* 关闭DataOutputStream */
dos.close();
InputStream inputStream;
try {
inputStream = connection.getInputStream();
} catch (IOException ioe) {
inputStream = connection.getErrorStream();
}
/* 从返回的输入流读取响应信息 */
InputStream is = connection.getInputStream(); // input from the
// connection
// 正式建立HTTP连接
Utils.log("con.getResponseCode() = " + connection.getResponseCode());
int ch;
StringBuffer b = new StringBuffer();
while ((ch = inputStream.read()) != -1) {
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
// 显示网页响应内容
/* 显示网页响应内容 */
Utils.log("content = " + b.toString().trim());
int statusCode = connection.getResponseCode();
Utils.log("statusCode = " + statusCode);
if (statusCode == 200) {
// {"icon":"http:\/\/gh-test-1.oss-cn-qingdao.aliyuncs.com\/pic\/57e4f4d58a3200042d29492f.jpg"}
// {"status":"success","url":"http:\/\/api.ghzhushou.com\/temp\/5688e548d7859e6f278b4567.jpg"}
if (connection.getResponseCode() == HttpStatus.SC_OK) {
JSONObject response = new JSONObject(b.toString().trim());
response.put("statusCode", 200);
return response;
} else if (statusCode == 403) {
JSONObject response = new JSONObject(b.toString().trim());
response.put("statusCode", 403);
return response;
} else if (statusCode == 401) {
JSONObject response = new JSONObject();
response.put("statusCode", 401);
return response;
if ("success".equals(response.getString("status"))) {
return response.getString("url");
}
}
} catch (Exception e) {
// 显示异常信息
e.printStackTrace();
/* 显示异常信息 */
Utils.log("Fail:" + e);
}
return null;
}
// 读取文件返回byte[]
public static byte[] readFile(File file) {
if (file == null) {
return null;
}
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = new FileInputStream(file);
bos = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int len;
while ((len = fis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.flush();
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
// 根据byte[],保存文件
public static void saveFile(File file, byte[] data) {
if (file == null || data == null) {
return;
}
ByteArrayInputStream bis = null;
FileOutputStream fos = null;
try {
bis = new ByteArrayInputStream(data);
fos = new FileOutputStream(file);
byte[] buffer = new byte[2048];
int len;
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

View File

@ -1,108 +0,0 @@
package com.gh.common.util;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.TextView;
import com.gh.base.AppController;
import com.gh.download.DownloadEntity;
import com.gh.download.DownloadManager;
import com.gh.download.DownloadStatus;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.manager.PackageManager;
/**
* Created by LGT on 2016/9/29.
*/
public class GameUtils {
/**
* 启动游戏详情页面
*/
public static void startGameDetailActivity(Context context, GameEntity gameEntity, String entrance) {
AppController.put("GameEntity", gameEntity);
Intent intent = new Intent(context, GameDetailActivity.class);
intent.putExtra("entrance", entrance);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* 启动游戏详情页面
*/
public static void startGameDetailActivity(Context context, String gameId, String entrance) {
Intent intent = new Intent(context, GameDetailActivity.class);
intent.putExtra("gameId", gameId);
intent.putExtra("entrance", entrance);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* 设置下载按钮状态
*/
public static void setDownloadBtnStatus(Context context, GameEntity gameEntity, TextView downloadBtn) {
String status = getDownloadBtnText(context, gameEntity);
downloadBtn.setTextColor(Color.WHITE);
downloadBtn.setText(status);
if ("插件化".equals(status)) {
downloadBtn.setBackgroundResource(R.drawable.game_item_btn_plugin_style);
} else if ("打开".equals(status)) {
downloadBtn.setBackgroundResource(R.drawable.game_item_btn_launch_style);
} else {
downloadBtn.setBackgroundResource(R.drawable.game_item_btn_download_style);
}
}
/**
* 获取下载按钮文案
*/
public static String getDownloadBtnText(Context context, GameEntity gameEntity) {
int doneCount = 0; // 下载完成数量
int pluginCount = 0; // 可插件化数量
int updateCount = 0; // 可更新数量
int installCount = 0; // 已安装数量
DownloadEntity downloadEntity;
Object gh_id;
for (ApkEntity apkEntity : gameEntity.getApk()) {
downloadEntity = DownloadManager.getInstance(context).get(apkEntity.getUrl());
if (downloadEntity != null) {
if (downloadEntity.getStatus().equals(DownloadStatus.done)) {
doneCount++;
} else if (downloadEntity.isPluggable()) {
pluginCount++;
} else if (downloadEntity.isUpdate()) {
updateCount++;
}
}
if (PackageManager.isCanUpdate(gameEntity.getId(), apkEntity.getPackageName())) {
updateCount++;
}
if (PackageManager.isInstalled(apkEntity.getPackageName())) {
gh_id = PackageUtils.getMetaData(context, apkEntity.getPackageName(), "gh_id");
if (!PackageUtils.isSignature(context, apkEntity.getPackageName())) {
pluginCount++;
} else if (gh_id == null || gh_id.equals(gameEntity.getId())) {
installCount++;
}
}
}
if (doneCount != 0) {
return "安装";
} else if (pluginCount != 0) {
return "插件化";
} else if (updateCount != 0) {
return "更新";
} else if (installCount != 0) {
return "打开";
} else {
return "下载";
}
}
}

View File

@ -26,50 +26,66 @@ import java.util.TimeZone;
*/
public class GameViewUtils {
public static void setLabelList(Context context, LinearLayout labelLayout, List<String> tag) {
public static void setLabelList(Context context, LinearLayout labelLayout,
List<String> tag) {
labelLayout.removeAllViews();
if (tag == null || tag.isEmpty()) {
labelLayout.addView(getGameTagView(context, "官方版", 0));
labelLayout.addView(getGameTagView(context, "官方版"));
} else {
for (int i = 0, size = tag.size() > 3 ? 3 : tag.size(); i < size; i++) {
if (i == size - 1) {
labelLayout.addView(getGameTagView(context, tag.get(i), 0));
} else {
labelLayout.addView(getGameTagView(context, tag.get(i), DisplayUtils.dip2px(context, 5)));
}
labelLayout.addView(getGameTagView(context, tag.get(i)));
}
}
}
public static TextView getGameTagView(Context context, String tagStr, int rightMargin) {
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
// 获取游戏标签列表视图
public static void setLabelList(Context context, LinearLayout labelLayout,
String tag) {
labelLayout.removeAllViews();
// 添加tag标签
if (tag != null && !tag.isEmpty()) {
String[] tags = tag.split(",");
for (int i = 0; i < tags.length; i++) {
labelLayout.addView(getGameTagView(context, tags[i]));
}
}
}
public static TextView getGameTagView(Context context, String tagStr) {
LayoutParams lp = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lparams.rightMargin = rightMargin;
lp.setMargins(0, 0, DisplayUtils.dip2px(context, 5), 0);
TextView tag = new TextView(context);
tag.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
tag.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
tag.setSingleLine(true);
tag.setText(tagStr);
if ("官方版".equals(tagStr) || "已关注".equals(tagStr)) {
tag.setBackgroundResource(R.drawable.border_green_bg);
tag.setTextColor(context.getResources().getColor(R.color.tag_green));
} else {
tag.setBackgroundResource(R.drawable.border_red_bg);
tag.setTextColor(0xffbc2132);
} else if ("已安装".equals(tagStr)) {
tag.setBackgroundResource(R.drawable.border_blue_bg);
tag.setTextColor(context.getResources().getColor(R.color.theme));
tag.setTextColor(0xff1BA4FC);
} else {
tag.setBackgroundResource(R.drawable.border_green_bg);
tag.setTextColor(0xff2ec991);
}
tag.setLayoutParams(lparams);
tag.setPadding(DisplayUtils.dip2px(context, 3),
0,
DisplayUtils.dip2px(context, 3),
DisplayUtils.dip2px(context, 1));
tag.setLayoutParams(lp);
tag.setPadding(DisplayUtils.dip2px(context, 4),
DisplayUtils.dip2px(context, 2),
DisplayUtils.dip2px(context, 4),
DisplayUtils.dip2px(context, 2));
return tag;
}
public static String getGameTestDate(long testTime) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd",
Locale.CHINA);
format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
String testDate;
try {
long today = format.parse(format.format(new Date())).getTime();
long day = Long.parseLong(testTime + "000");

View File

@ -15,7 +15,8 @@ public class GzipUtils {
/*
* 数据压缩
*/
public static void compress(InputStream is, OutputStream os) throws IOException {
public static void compress(InputStream is, OutputStream os)
throws IOException {
GZIPOutputStream gos = null;
try {
gos = new GZIPOutputStream(os);
@ -37,7 +38,8 @@ public class GzipUtils {
/*
* 数据解压缩
*/
public static void decompress(InputStream is, OutputStream os) throws IOException {
public static void decompress(InputStream is, OutputStream os)
throws IOException {
GZIPInputStream gis = null;
try {
gis = new GZIPInputStream(is);
@ -110,5 +112,4 @@ public class GzipUtils {
}
}
}
}

View File

@ -16,7 +16,6 @@ import dalvik.system.PathClassLoader;
/* compiled from: ProGuard */
public final class HotFix {
public static void patch(Context context, String patchDexFile, String patchClassName) {
if (patchDexFile != null && new File(patchDexFile).exists()) {
try {
@ -154,5 +153,4 @@ public final class HotFix {
}
return newInstance;
}
}

View File

@ -0,0 +1,35 @@
package com.gh.common.util;
import android.content.Context;
import com.alibaba.sdk.android.httpdns.HttpDns;
import com.alibaba.sdk.android.httpdns.HttpDnsService;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by khy on 2016/7/11.
*/
public class HttpdnsUtils {
private static HttpDnsService httpdns;
private static String accountID = "180813";
public static String getUrls(Context context,String url){
httpdns = HttpDns.getService(context,accountID);
try {
URL oldUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) oldUrl.openConnection();
String ip = httpdns.getIpByHost(oldUrl.getHost());
if (ip!= null){
String newUrl = url.replaceFirst(oldUrl.getHost(), ip);
return newUrl;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -1,137 +0,0 @@
package com.gh.common.util;
import android.content.Context;
import com.gh.gamecenter.R;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.internal.tls.OkHostnameVerifier;
/**
* Created by khy on 2016/10/8.
*
*/
public class HttpsUtils {
private static final TrustManager[] TRUST_MANAGERS = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
};
private static final HostnameVerifier HOSTNAME_VERIFIER = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
private static SSLSocketFactory mSSLSocketFactory;
private static HostnameVerifier mHostnameVerifier;
public static void initHttpsUrlConnection(Context context) {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
KeyStore keyStore = getHttpsKeyStore(context);
if (keyStore != null) {
String algorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
tmf.init(keyStore);
sslContext.init(null, tmf.getTrustManagers(), null);
mHostnameVerifier = OkHostnameVerifier.INSTANCE;
} else {
sslContext.init(null, TRUST_MANAGERS, null);
mHostnameVerifier = HOSTNAME_VERIFIER;
}
mSSLSocketFactory = sslContext.getSocketFactory();
// HttpsURLConnection.setDefaultSSLSocketFactory(mSSLSocketFactory);
// HttpsURLConnection.setDefaultHostnameVerifier(mHostnameVerifier);
} catch (Exception e) {
e.printStackTrace();
}
}
private static KeyStore getHttpsKeyStore(Context context) {
InputStream is = null;
try {
is = context.getResources().openRawResource(R.raw.download);
//读取证书
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificateFactory.generateCertificate(is);
Certificate certificate = certificateFactory.generateCertificate(is);
//创建一个证书库,并将证书导入证书库
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("trust", certificate);
return keyStore;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static HttpsURLConnection getHttpsURLConnection(URL url) throws Exception {
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
if ("apk2.ghzhushou.com".equals(url.getHost())
|| "download.ghzhushou.com".equals(url.getHost())) {
if (mSSLSocketFactory == null || mHostnameVerifier == null) {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, TRUST_MANAGERS, null);
mSSLSocketFactory = sslContext.getSocketFactory();
mHostnameVerifier = HOSTNAME_VERIFIER;
}
httpsURLConnection.setSSLSocketFactory(mSSLSocketFactory);
httpsURLConnection.setHostnameVerifier(mHostnameVerifier);
} else {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, TRUST_MANAGERS, null);
httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
httpsURLConnection.setHostnameVerifier(HOSTNAME_VERIFIER);
}
return httpsURLConnection;
}
}

View File

@ -1,105 +1,279 @@
package com.gh.common.util;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.support.v4.util.ArrayMap;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import com.facebook.common.executors.CallerThreadExecutor;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.gh.common.view.CircleImageView;
import com.gh.gamecenter.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.lang.ref.WeakReference;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ImageUtils {
private static ImageUtils singleton;
private static ImageLoader imageLoader;
private static DisplayImageOptions options;
private ArrayMap<String, WeakReference<Bitmap>> imageCache = new ArrayMap<String, WeakReference<Bitmap>>();
public static ImageUtils getInstance() {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
public static ImageUtils getInstance(Context context) {
if (singleton == null) {
synchronized (ImageUtils.class) {
if (singleton == null) {
singleton = new ImageUtils();
singleton = new ImageUtils(context.getApplicationContext(),
(int) Runtime.getRuntime().maxMemory() / 10);
return singleton;
}
}
}
return singleton;
}
// 自适应图片宽高
public void display(final SimpleDraweeView simpleDraweeView, String url, final int width) {
ControllerListener<ImageInfo> listener = new BaseControllerListener<ImageInfo>(){
@Override
public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
if (imageInfo == null){
return;
}
ViewGroup.LayoutParams layoutParams = simpleDraweeView.getLayoutParams();
float scale = (float) imageInfo.getHeight() / (float) imageInfo.getWidth();
layoutParams.height = (int)(width * scale);
simpleDraweeView.setLayoutParams(layoutParams);
}
};
simpleDraweeView.setController(Fresco.newDraweeControllerBuilder()
.setUri(url)
.setControllerListener(listener)
.build());
}
private ImageUtils(Context context, int size) {
// 设置缩放类型,设置按压状态下的叠加图
public void display(Resources resources, SimpleDraweeView simpleDraweeView,
ScalingUtils.ScaleType scaleType, String url) {
simpleDraweeView.setHierarchy(new GenericDraweeHierarchyBuilder(resources)
.setFadeDuration(500)
.setPressedStateOverlay(new ColorDrawable(resources.getColor(R.color.pressed_bg)))
.setPlaceholderImage(R.drawable.ocupy2, ScalingUtils.ScaleType.CENTER)
.setBackground(new ColorDrawable(resources.getColor(R.color.placeholder_bg)))
.setActualImageScaleType(scaleType)
.build());
simpleDraweeView.setImageURI(url);
}
// 设置占位符
public void display(Resources resources, SimpleDraweeView simpleDraweeView, String url, int placeholderImage) {
simpleDraweeView.setHierarchy(new GenericDraweeHierarchyBuilder(resources)
.setFadeDuration(500)
.setPressedStateOverlay(new ColorDrawable(resources.getColor(R.color.pressed_bg)))
.setBackground(new ColorDrawable(resources.getColor(R.color.placeholder_bg)))
.setPlaceholderImage(placeholderImage)
.build());
simpleDraweeView.setImageURI(url);
}
// 图片下载监听和设置低高分辨率图片
public void display(SimpleDraweeView simpleDraweeView, String url, String lowUrl,
ControllerListener<? super ImageInfo> listener) {
simpleDraweeView.setController(Fresco.newDraweeControllerBuilder()
.setImageRequest(ImageRequest.fromUri(url))
.setControllerListener(listener)
.setLowResImageRequest(ImageRequest.fromUri(lowUrl)) // 低分辨率图片
.build());
}
// 获取bitmap
public void display(Context context, String url, BaseBitmapDataSubscriber dataSubscriber) {
ImageRequest imageRequest = ImageRequestBuilder
.newBuilderWithSource(Uri.parse(url))
.setProgressiveRenderingEnabled(true)
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true).considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
// .showImageOnLoading(R.drawable.ocupy)
// .showImageForEmptyUri(R.drawable.ocupy)
// .showImageOnFail(R.drawable.ocupy)
.build();
Fresco.getImagePipeline()
.fetchDecodedImage(imageRequest, context)
.subscribe(dataSubscriber, CallerThreadExecutor.getInstance());
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
context).writeDebugLogs()
.memoryCacheExtraOptions(480, 800)
.build();
ImageLoader.getInstance().init(config);
imageLoader = ImageLoader.getInstance();
}
public void displayFile(String url, ImageView imageView) {
imageLoader.displayImage(url, imageView, options,
new ImageLoadingListener() {
@Override
public void onLoadingCancelled(String arg0, View arg1) {
}
@Override
public void onLoadingComplete(String arg0, View view,
Bitmap arg2) {
AlphaAnimation animation = new AlphaAnimation(0f, 1f);
animation.setDuration(500);
view.startAnimation(animation);
}
@Override
public void onLoadingFailed(String arg0, View arg1,
FailReason arg2) {
}
@Override
public void onLoadingStarted(String arg0, View arg1) {
}
});
}
//增加一个上下文环境,图片宽度设最大,高度自适应
public void display(String url, ImageView imageView, int drawable,Context context) {
display(url, imageView, drawable, ScaleType.FIT_XY, null,context);
}
public void display(String url, ImageView imageView, int drawable) {
display(url, imageView, drawable, ScaleType.FIT_XY, null);
}
public void display(final String url, final ImageView imageView,
final int drawable, final ScaleType scaleType,
final OnLoadingCompleteListener listener) {
imageLoader.displayImage(url, imageView, options,
new ImageLoadingListener() {
@Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
if (imageView instanceof CircleImageView) {
imageView.setScaleType(ScaleType.CENTER_CROP);
} else {
imageView.setScaleType(scaleType);
}
if (listener != null) {
listener.onLoadingComplete();
}
}
@Override
public void onLoadingStarted(String imageUri, View view) {
imageView.setScaleType(ScaleType.CENTER);
if (drawable != -1) {
imageView.setImageResource(drawable);
}
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
}
@Override
public void onLoadingFailed(String imageUri, View view,
FailReason reason) {
}
});
}
public void display(final String url, final ImageView imageView,
final int drawable, final ScaleType scaleType,
final OnLoadingCompleteListener listener,final Context context) {
imageLoader.displayImage(url, imageView, options,
new ImageLoadingListener() {
@Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
int width = loadedImage.getWidth();
int height = loadedImage.getHeight();
int widthPixels = context.getResources().getDisplayMetrics().widthPixels;
float index = (float) height/(float) width;
int newHeight = (int)(index*widthPixels);
ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
layoutParams.height = newHeight;
layoutParams.width = widthPixels;
imageView.setLayoutParams(layoutParams);
if (imageView instanceof CircleImageView) {
imageView.setScaleType(ScaleType.CENTER_CROP);
} else {
imageView.setScaleType(scaleType);
}
if (listener != null) {
listener.onLoadingComplete();
}
}
@Override
public void onLoadingStarted(String imageUri, View view) {
imageView.setScaleType(ScaleType.CENTER);
if (drawable != -1) {
imageView.setImageResource(drawable);
}
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
}
@Override
public void onLoadingFailed(String imageUri, View view,
FailReason reason) {
}
});
}
public void display(final String url, final ImageView imageView,
final int drawable, final ScaleType scaleType,
final OnLoadingCompleteListener listener, final int i) {
imageLoader.displayImage(url, imageView, options,
new ImageLoadingListener() {
@Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
WeakReference<Bitmap> bitmapWeakReference = imageCache.get(imageUri);
try {
if (bitmapWeakReference!=null){
Bitmap bitmap = bitmapWeakReference.get();
imageView.setImageBitmap(bitmap);
}else {
Matrix m = new Matrix();
m.setRotate(i, (float) loadedImage.getWidth() / 2, (float) loadedImage.getHeight() / 2);
Bitmap bm1 = Bitmap.createBitmap(loadedImage, 0, 0, loadedImage.getWidth(), loadedImage.getHeight(), m, true);
imageView.setImageBitmap(bm1);
WeakReference<Bitmap> weakBM = new WeakReference<Bitmap>(bm1);
imageCache.put(imageUri, weakBM);
}
} catch (OutOfMemoryError ex) {
Utils.log("Bitmap:::内存溢出");
} catch (Exception e) {
e.printStackTrace();
}
if (imageView instanceof CircleImageView) {
imageView.setScaleType(ScaleType.CENTER_CROP);
} else {
imageView.setScaleType(scaleType);
}
if (listener != null) {
listener.onLoadingComplete();
}
}
@Override
public void onLoadingStarted(String imageUri, View view) {
imageView.setScaleType(ScaleType.CENTER);
if (drawable != -1) {
imageView.setImageResource(drawable);
}
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
}
@Override
public void onLoadingFailed(String imageUri, View view,
FailReason reason) {
}
});
}
public void display(String url, ImageView imageView, ScaleType scaleType) {
display(url, imageView, R.drawable.ocupy, scaleType, null);
}
public void display(String url, ImageView imageView) {
display(url, imageView, R.drawable.ocupy, ScaleType.FIT_XY, null);
}
//旋转图片 i表示角度
public void display(String url, ImageView imageView, int i, boolean isHorizontal) {
display(url, imageView, R.drawable.ocupy, ScaleType.FIT_XY, null, i);
}
public void display(String url, ImageView imageView, ScaleType scaleType, OnLoadingCompleteListener listener) {
display(url, imageView, R.drawable.ocupy, scaleType, listener);
}
public void display(String url, ImageView imageView, OnLoadingCompleteListener listener) {
display(url, imageView, R.drawable.ocupy, ScaleType.FIT_XY, listener);
}
public interface OnLoadingCompleteListener {
void onLoadingComplete();
}
}

View File

@ -9,10 +9,8 @@ import java.io.RandomAccessFile;
import java.util.UUID;
public class Installation {
private static final String INSTALLATION = "INSTALLATION";
private static String sID = null;
private static final String INSTALLATION = "INSTALLATION";
public synchronized static String getUUID(Context context) {
if (sID == null) {
@ -44,5 +42,4 @@ public class Installation {
out.write(id.getBytes());
out.close();
}
}

View File

@ -74,5 +74,4 @@ public class MD5Utils {
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
}
}

View File

@ -1,63 +0,0 @@
package com.gh.common.util;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by khy on 2016/8/22.
* RecyclerView 自适应高度
*/
public class MeasureHeightLayoutManager extends LinearLayoutManager {
public MeasureHeightLayoutManager(Context context) {
super(context);
}
private int[] mMeasuredDimension = new int[1];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
height = height + mMeasuredDimension[0];
}
if (height > heightSize){
super.onMeasure(recycler, state, widthSpec, heightSpec);
}else {
setMeasuredDimension(View.MeasureSpec.getSize(widthSpec), height);
}
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
if (view.getVisibility() == View.GONE) {
measuredDimension[0] = 0;
return;
}
super.measureChildWithMargins(view, 0, 0);
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childHeightSpec = ViewGroup.getChildMeasureSpec(
heightSpec,
getPaddingTop() + getPaddingBottom() + getDecoratedTop(view) + getDecoratedBottom(view),
p.height);
view.measure(0, childHeightSpec);
measuredDimension[0] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}

View File

@ -1,441 +0,0 @@
package com.gh.common.util;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gh.gamecenter.R;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXImageObject;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.platformtools.Util;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
* Created by khy on 2016/11/8.
*/
public class MessageShareUtils {
private static MessageShareUtils instance;
private Bitmap shareBm; //分享截图
private String picName;
private boolean isPlugin = false;
private static IWXAPI api;
private static Tencent mTencent;
private Handler handler;
private int[] arrLogo = {R.drawable.share_wechat_logo, R.drawable.share_wechatmoments_logo, R.drawable.share_qq_logo
, R.drawable.share_qzone_logo, R.drawable.share_save};
private String[] arrLabel = {"微信好友", "朋友圈", "QQ好友", "QQ空间", "保存"};
private PopupWindow popupWindow;
private Context context;
private Activity activity; // 用来关闭分享页面
public static MessageShareUtils getInstance(Context context) {
if (instance == null) {
instance = new MessageShareUtils();
mTencent = Tencent.createInstance("1104659243", context); //初始化QQ分享
api = WXAPIFactory.createWXAPI(context, "wx3ffd0785fad18396"); //初始化微信分享
}
instance.context = context;
return instance;
}
public void showShareWindows(View view, Bitmap bitmap, String picName, boolean ispopupWindow){
this.shareBm = bitmap;
this.picName = picName;
this.activity= (Activity) context;
RelativeLayout contentView = new RelativeLayout(context);
contentView.setBackgroundColor(0x8c000000);
contentView.setFocusable(true);
contentView.setFocusableInTouchMode(true);
RecyclerView shareRecyclerView = new RecyclerView(context);
shareRecyclerView.setPadding(DisplayUtils.dip2px(context, 10), DisplayUtils.dip2px(context, 10), DisplayUtils.dip2px(context, 10), 0);
shareRecyclerView.setBackgroundColor(Color.WHITE);
//RecyclerView禁止滑动
GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 5){
@Override
public boolean canScrollVertically() {
return false;
}
};
shareRecyclerView.setLayoutManager(gridLayoutManager);
shareRecyclerView.setAdapter(new ShareRecyclerViewAdapter());
if (!ispopupWindow) {
LinearLayout llBottom = (LinearLayout) view;
ViewGroup.LayoutParams layoutParams = llBottom.getLayoutParams();
layoutParams.height = DisplayUtils.dip2px(context, 100);
llBottom.addView(shareRecyclerView);
return;
}
RelativeLayout.LayoutParams rlParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
, DisplayUtils.dip2px(context, 106));
rlParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
contentView.addView(shareRecyclerView,rlParams);
popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT
, LinearLayout.LayoutParams.MATCH_PARENT, true);
popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
contentView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0 && popupWindow != null
&& popupWindow.isShowing()) {
popupWindow.dismiss();
}
return false;
}
});
}
public class ShareRecyclerViewAdapter extends RecyclerView.Adapter<ShareRecyclerViewAdapter.ViewHolder>{
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DisplayUtils.dip2px(context, 90)));
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
linearLayout.setBackgroundResource(R.drawable.cardview_item_style);
ImageView shareLogo = new ImageView(context);
LinearLayout.LayoutParams logoParams = new LinearLayout.LayoutParams(DisplayUtils.dip2px(context, 43), DisplayUtils.dip2px(context, 43));
logoParams.setMargins(0, DisplayUtils.dip2px(context, 10), 0, 0);
shareLogo.setLayoutParams(logoParams);
TextView shareLabel = new TextView(context);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, DisplayUtils.dip2px(context,10), 0, 0);
shareLabel.setLayoutParams(layoutParams);
shareLabel.setGravity(Gravity.CENTER);
shareLabel.setTextColor(Color.parseColor("#3a3a3a"));
shareLabel.setTextSize(13);
linearLayout.addView(shareLogo);
linearLayout.addView(shareLabel);
return new ViewHolder(linearLayout);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.shareLogo.setImageResource(arrLogo[position]);
holder.shareLabel.setText(arrLabel[position]);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (holder.getPosition()){
case 0:
wechatSahre();
activity.finish();
break;
case 1:
wechatMomentsSahre();
activity.finish();
break;
case 2:
qqSahre();
break;
case 3:
qZoneSahre();
break;
case 4:
String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/ghzhushou/";
writeBitmap(savePath, "gh-" + new Date().getTime() + ".jpg", shareBm, true);
if (popupWindow == null) return;
popupWindow.dismiss();
activity.finish();
break;
}
}
});
}
@Override
public int getItemCount() {
return arrLogo.length;
}
public class ViewHolder extends RecyclerView.ViewHolder{
LinearLayout linearLayout;
TextView shareLabel;
ImageView shareLogo;
public ViewHolder(View itemView) {
super(itemView);
linearLayout = (LinearLayout) itemView;
shareLogo = (ImageView) linearLayout.getChildAt(0);
shareLabel = (TextView) linearLayout.getChildAt(1);
}
}
}
//QQ分享
private void qqSahre(){
Utils.toast(context,"分享跳转中...");
Bundle params = new Bundle();
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
QQShare.SHARE_TO_QQ_TYPE_IMAGE);
params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, context.getExternalCacheDir().getPath() + "/ShareImg/" + picName);
params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "光环助手");
params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,
QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
mTencent.shareToQQ(
(Activity) context, params,QqShareListener);
if (popupWindow == null) return;
popupWindow.dismiss();
}
//QQ空间分享
private void qZoneSahre(){
Utils.toast(context,"分享跳转中...");
Bundle params = new Bundle();
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
QQShare.SHARE_TO_QQ_TYPE_IMAGE);
params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, context.getExternalCacheDir().getPath() + "/ShareImg/" + picName);
params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "光环助手");
params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,
QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
mTencent.shareToQQ(
(Activity) context, params,QqShareListener);
if (popupWindow == null) return;
popupWindow.dismiss();
}
//微信好友分享
private void wechatSahre(){
Utils.toast(context,"分享跳转中...");
//官方分享
// WXImageObject imgObj = new WXImageObject();
// imgObj.setImagePath(context.getExternalCacheDir().getPath() + "/ShareImg/" + picName);
// WXMediaMessage msg = new WXMediaMessage();
// msg.mediaObject = imgObj;
//
// SendMessageToWX.Req req = new SendMessageToWX.Req();
// req.transaction = buildTransaction("img");
// req.message = msg;
// req.scene = SendMessageToWX.Req.WXSceneSession;
//
// Bitmap compressBp = compressBitmap(shareBm);
// msg.thumbData = Util.bmpToByteArray(compressBp, true);
// api.sendReq(req);
//调用手机系统分享
try {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + context.getExternalCacheDir().getPath() + "/ShareImg/" + picName));
intent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI"));
context.startActivity(intent);
} catch (Exception e) {
Utils.toast(context,"分享失败!请检查是否已安装微信");
e.printStackTrace();
}
if (popupWindow == null) return;
popupWindow.dismiss();
}
//微信朋友圈分享
private void wechatMomentsSahre(){
Utils.toast(context,"分享跳转中...");
WXImageObject imgObj = new WXImageObject();
imgObj.setImagePath(context.getExternalCacheDir().getPath() + "/ShareImg/" + picName);
WXMediaMessage msg = new WXMediaMessage();
msg.mediaObject = imgObj;
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("img");
req.message = msg;
req.scene = SendMessageToWX.Req.WXSceneTimeline;
Bitmap compressBp = compressBitmap(shareBm);
msg.thumbData = Util.bmpToByteArray(compressBp, true);
api.sendReq(req);
if (popupWindow == null) return;
popupWindow.dismiss();
}
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
//压缩图片
private Bitmap compressBitmap(Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bos);
float zoom = (float) Math.sqrt(10 * 1024 / (float) bos.toByteArray().length);
Matrix matrix = new Matrix();
matrix.setScale(zoom, zoom);
Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bos.reset();
result.compress(Bitmap.CompressFormat.JPEG, 85, bos);
while(bos.toByteArray().length > 10 * 1024){
System.out.println(bos.toByteArray().length);
matrix.setScale(0.9f, 0.9f);
result = Bitmap.createBitmap(result, 0, 0, result.getWidth(), result.getHeight(), matrix, true);
bos.reset();
result.compress(Bitmap.CompressFormat.JPEG, 85, bos);
}
return result;
}
//QQ或者QQ空间分享回调处理
public IUiListener QqShareListener = new IUiListener() {
@Override
public void onComplete(Object o) {
activity.finish();
activity.overridePendingTransition(0, 0);//禁止退出Activity 动画
Utils.toast(context, "分享成功");
}
@Override
public void onError(UiError uiError) {
Utils.toast(context, "分享失败");
}
@Override
public void onCancel() {
activity.finish();
activity.overridePendingTransition(0, 0);//禁止退出Activity 动画
Utils.toast(context, "分享已取消");
}
};
//检查是否安装手机QQ
public static boolean isQQClientAvailable(Context context){
final PackageManager packageManager = context.getPackageManager();
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
if (pinfo != null) {
for (int i = 0; i < pinfo.size(); i++) {
String pn = pinfo.get(i).packageName; if (pn.equals("com.tencent.mobileqq")) {
return true;
}
}
}
return false;
}
//写到存储卡中
public void writeBitmap(String path, String name, Bitmap bitmap, boolean isToast) {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
File _file = new File(path , name);
if (_file.exists()) {
_file.delete();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(_file);
if (name != null && !"".equals(name)) {
int index = name.lastIndexOf(".");
if (index != -1 && (index + 1) < name.length()) {
String extension = name.substring(index + 1).toLowerCase();
if ("png".equals(extension)) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} else if ("jpg".equals(extension)
|| "jpeg".equals(extension)) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
}
if (isToast) {
Utils.toast(context,"成功保存到相册");
//刷新手机图片库
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(_file);
intent.setData(uri);
context.sendBroadcast(intent);
Utils.log("保存分享图片路径:" + _file.getAbsolutePath());
}
}
}
} catch (FileNotFoundException e) {
Utils.log("消息分享异常" + e.toString());
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

View File

@ -9,7 +9,8 @@ public class NetworkUtils {
/**
* 判断是否有网络连接
*
* @param context 上下文
* @param context
* 上下文
* @return true 有网络连接 false 无网络连接
*/
public static boolean isNetworkConnected(Context context) {
@ -28,7 +29,8 @@ public class NetworkUtils {
/**
* 判断WIFI网络是否可用
*
* @param context 上下文
* @param context
* 上下文
* @return true wifi可用 false wifi不可用
*/
public static boolean isWifiConnected(Context context) {
@ -47,7 +49,8 @@ public class NetworkUtils {
/**
* 判断MOBILE网络是否可用
*
* @param context 上下文
* @param context
* 上下文
* @return true mobile可用 false mobile不可用
*/
public static boolean isMobileConnected(Context context) {
@ -103,5 +106,4 @@ public class NetworkUtils {
}
return "NONE";
}
}

View File

@ -2,29 +2,26 @@ package com.gh.common.util;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.gh.gamecenter.MessageDetailActivity;
import com.gh.gamecenter.NewsDetailActivity;
import com.gh.gamecenter.NewsActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.entity.ConcernEntity;
import com.gh.gamecenter.entity.NewsDetailsEntity;
import com.gh.gamecenter.entity.NewsEntity;
import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.json.JSONObject;
public class NewsUtils {
/**
* 根据新闻类型获取标签背景资源
*
* @param type
* @return
*/
public static int getDrawableIdByType(String type) {
if ("活动".equals(type) || "高阶".equals(type)) {
@ -40,23 +37,21 @@ public class NewsUtils {
/**
* 启动新闻详情页面
*
* @param context
* @param newsEntity
* @param entrance
* @return
*/
public static void startNewsActivity(Context context, NewsEntity newsEntity, String entrance) {
Intent intent = new Intent(context, NewsDetailActivity.class);
intent.putExtra("id", newsEntity.getId());
intent.putExtra("title", newsEntity.getTitle());
intent.putExtra("type", newsEntity.getType());
intent.putExtra("entrance", entrance);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* 启动消息详情页面
*/
public static void startMessageActivity(Context context, ConcernEntity concernEntity, String entrance) {
AppController.put("ConcernEntity", concernEntity);
Intent intent = new Intent(context, MessageDetailActivity.class);
public static void startNewsActivity(Context context,
NewsEntity newsEntity, String entrance) {
Intent intent = new Intent(context, NewsActivity.class);
NewsDetailsEntity entity = new NewsDetailsEntity();
entity.setId(newsEntity.getId());
entity.setTitle(newsEntity.getTitle());
entity.setType(newsEntity.getType());
entity.setTime(newsEntity.getPublishOn());
intent.putExtra("entity", entity);
intent.putExtra("entrance", entrance);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
@ -64,81 +59,25 @@ public class NewsUtils {
/**
* 统计阅读量
* @param news_id
*/
public static void statNewsViews(String news_id) {
String url = Config.DATA_HOST + "news/stat?news_id=" + news_id;
String url = "http://data.ghzhushou.com/news/stat?news_id=" + news_id;
JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
Request.Method.POST, url, null, null);
Request.Method.POST, url,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
request.setShouldCache(false);
AppController.addToRequestQueue(request);
}
/**
* 去除与重复sourceList相同的数据
*/
public static List<NewsEntity> removeDuplicateData(List<NewsEntity> sourceList, List<NewsEntity> rawList) {
if (sourceList == null || sourceList.isEmpty()
|| rawList == null || rawList.isEmpty()) {
return rawList;
}
String id;
for (int i = 0; i < rawList.size(); i++) {
id = rawList.get(i).getId();
for (NewsEntity newsEntity : sourceList) {
if (id.equals(newsEntity.getId())) {
rawList.remove(i);
i--;
break;
}
}
}
return rawList;
}
/**
* 设置新闻类型
*/
public static void setNewsType(TextView textView, String type) {
textView.setText(type);
textView.setTextColor(Color.WHITE);
if ("活动".equals(type)) {
textView.setBackgroundResource(R.drawable.textview_orange_style);
} else if ("公告".equals(type)) {
textView.setBackgroundResource(R.drawable.textview_red_style);
} else if ("评测".equals(type)) {
textView.setBackgroundResource(R.drawable.textview_red_style);
} else if ("杂谈".equals(type)) {
textView.setBackgroundResource(R.drawable.textview_orange_style);
} else if ("专题".equals(type)) {
textView.setBackgroundResource(R.drawable.textview_blue_style);
} else {
textView.setBackgroundResource(R.drawable.textview_blue_style);
}
}
/**
* 设置新闻发布时间
*/
public static void setNewsPublishOn(TextView textView, long time) {
time = time * 1000;
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
try {
long today = format.parse(format.format(new Date())).getTime();
if (time >= today && time < today + 86400 * 1000) {
format.applyPattern("HH:mm");
textView.setText(String.format("今天 %s", format.format(time)));
} else if (time >= today - 86400 * 1000 && time < today) {
format.applyPattern("HH:mm");
textView.setText(String.format("昨天 %s", format.format(time)));
} else {
format.applyPattern("yyyy年MM月dd日 HH:mm");
textView.setText(format.format(time));
}
} catch (ParseException e) {
e.printStackTrace();
format.applyPattern("yyyy年MM月dd日 HH:mm");
textView.setText(format.format(time));
}
AppController.addToRequestQueue(request, NewsUtils.class);
}
}

View File

@ -1,85 +0,0 @@
package com.gh.common.util;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.gh.download.DownloadEntity;
import com.gh.download.DownloadManager;
import com.gh.download.DownloadStatus;
import com.gh.gamecenter.R;
/**
* Created by LGT on 2016/10/10.
*/
public class NotificationUtils {
public static void showDownloadDoneNotification(Context context, DownloadEntity downloadEntity, int flag) {
NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent();
intent.putExtra("path", downloadEntity.getPath());
intent.setAction("com.gh.gamecenter.INSTALL");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, flag,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
String text;
String title;
if (downloadEntity.isPluggable()) {
text = "下载完成,点击继续插件化";
title = downloadEntity.getName() + "-"
+ PlatformUtils.getInstance(context).getPlatformName(downloadEntity.getPlatform());
} else {
if (downloadEntity.isPlugin()) {
text = downloadEntity.getName() + "-"
+ PlatformUtils.getInstance(context).getPlatformName(downloadEntity.getPlatform()) + " 下载完成";
} else {
text = downloadEntity.getName() + " 下载完成";
}
title = "点击立即安装";
}
Notification notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo)
.setTicker(text)
.setContentTitle(title)
.setContentText(text)
.setContentIntent(pendingIntent).build();
// notification.defaults = Notification.DEFAULT_SOUND;// 添加系统默认声音
notification.flags |= Notification.FLAG_AUTO_CANCEL; // // FLAG_AUTO_CANCEL表明当通知被用户点击时通知将被清除。
nManager.notify(flag, notification);
}
public static void showDownloadingNotification(Context context) {
int downloadingSize = 0;
for (DownloadEntity entity : DownloadManager.getInstance(context).getAll()) {
if (entity.getStatus().equals(DownloadStatus.downloading)
|| entity.getStatus().equals(DownloadStatus.waiting)
|| entity.getStatus().equals(DownloadStatus.pause)
|| entity.getStatus().equals(DownloadStatus.timeout)
|| entity.getStatus().equals(DownloadStatus.neterror)) {
downloadingSize++;
}
}
if (downloadingSize == 0) {
NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.cancel(0x123);
} else {
NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent();
intent.setAction("com.gh.gamecenter.DOWNLOAD");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0x123,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo)
.setTicker("你有" + downloadingSize + "个游戏正在下载中")
.setContentTitle("点击查看详情")
.setContentText("你有" + downloadingSize + "个游戏正在下载中")
.setContentIntent(pendingIntent).build();
// notification.defaults = Notification.DEFAULT_SOUND;// 添加系统默认声音
notification.flags |= Notification.FLAG_NO_CLEAR; // 通知无法手动清除
nManager.notify(0x123, notification);
}
}
}

View File

@ -9,14 +9,18 @@ import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.widget.Toast;
import com.gh.gamecenter.entity.GameUpdateEntity;
import com.gh.gamecenter.manager.FilterManager;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
@ -27,6 +31,65 @@ public class PackageUtils {
public static final String publicKey = "OpenSSLRSAPublicKey{modulus=a8c4bb5748fec8d5c35db1a7a182d41ba4721a91131a417330af79ef4ddb43f9fa0ff4907b0a613bfe152de0ed8fc1b2e6f94a908aa98a5f7adc1ce814ba7ec919d75d9910bdfd8649b4789da6a90ffb61f0d23ac4f828a78fcd0d6f6120c1c43c1f87f7498a89eb40ca8e32dfc2f9d5c10d612b95192870223674e241e53305abf320d7eed76ded398778576e4db7b17b3bc6a792f13de5e43a6a5fae4276c73e6990ce97f68dff0ec16fc9594f175c8d49cd0d7877340d9de60942ca0efc737e50b6c295dfe0713e4532b4e810e1ea11b702b4a27753e41559cbceb247e7f044ec4e3ab2e8bccd8b9fd71286e63307550bcde86deee95adb8133076269135b,publicExponent=10001}";
/*
* 根据apk路径获取apk的签名信息,耗时
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String getApkSignatureByPath(Context context, String path) {
String PATH_PackageParser = "android.content.pm.PackageParser";
try {
// apk包的文件路径
// 这是一个Package 解释器, 是隐藏的
// 构造函数的参数只有一个, apk文件的路径
// PackageParser packageParser = new PackageParser(apkPath);
Class pkgParserCls = Class.forName(PATH_PackageParser);
Class[] typeArgs = new Class[1];
typeArgs[0] = String.class;
Constructor pkgParserCt = pkgParserCls.getConstructor(typeArgs);
Object[] valueArgs = new Object[1];
valueArgs[0] = path;
Object pkgParser = pkgParserCt.newInstance(valueArgs);
// 这个是与显示有关的, 里面涉及到一些像素显示等等, 我们使用默认的情况
DisplayMetrics metrics = new DisplayMetrics();
metrics.setToDefaults();
// PackageParser.Package mPkgInfo = packageParser.parsePackage(new
// File(apkPath), apkPath,
// metrics, 0);
typeArgs = new Class[4];
typeArgs[0] = File.class;
typeArgs[1] = String.class;
typeArgs[2] = DisplayMetrics.class;
typeArgs[3] = Integer.TYPE;
Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod(
"parsePackage", typeArgs);
valueArgs = new Object[4];
valueArgs[0] = new File(path);
valueArgs[1] = path;
valueArgs[2] = metrics;
valueArgs[3] = PackageManager.GET_SIGNATURES;
Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser,
valueArgs);
typeArgs = new Class[2];
typeArgs[0] = pkgParserPkg.getClass();
typeArgs[1] = Integer.TYPE;
Method pkgParser_collectCertificatesMtd = pkgParserCls
.getDeclaredMethod("collectCertificates", typeArgs);
valueArgs = new Object[2];
valueArgs[0] = pkgParserPkg;
valueArgs[1] = PackageManager.GET_SIGNATURES;
pkgParser_collectCertificatesMtd.invoke(pkgParser, valueArgs);
// 应用程序信息包, 这个公开的, 不过有些函数, 变量没公开
Field packageInfoFld = pkgParserPkg.getClass().getDeclaredField(
"mSignatures");
Signature[] info = (Signature[]) packageInfoFld.get(pkgParserPkg);
return parseSignature(info[0].toByteArray())[0];
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/*
* 根据路径获取apk的包名
*/
@ -41,9 +104,6 @@ public class PackageUtils {
return null;
}
/*
* 获取meta-data
*/
public static Object getMetaData(Context context, String packageName, String name) {
try {
Bundle metaDate = context.getPackageManager().getApplicationInfo(
@ -60,7 +120,8 @@ public class PackageUtils {
/*
* 根据包名获取apk的签名信息
*/
public static String getApkSignatureByPackageName(Context context, String packageName) {
public static String getApkSignatureByPackageName(Context context,
String packageName) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
@ -72,83 +133,6 @@ public class PackageUtils {
return null;
}
/*
* 判断是否可以更新只判断gh_version的大小
*/
public static boolean isCanUpdate(Context context, GameUpdateEntity gameUpdateEntity) {
// 判断是否gh_version是否存在
String gh_version = (String) PackageUtils.getMetaData(
context, gameUpdateEntity.getPackageName(), "gh_version");
if (gh_version != null) {
gh_version = gh_version.substring(2);
// 判断gh_version的大小
return Long.parseLong(gh_version) < Long.parseLong(gameUpdateEntity.getGhVersion());
} else {
return false;
}
}
/*
* 判断是否是插件包
*/
public static boolean isSignature(Context context, String packageName) {
String signature = getApkSignatureByPackageName(context, packageName);
return publicKey.equals(signature);
}
/*
* 根据apk路径获取apk包名、签名 根据包名 判断 是否已安装游戏 根据签名 判断 是否一致
*/
public static boolean isCanLaunchSetup(Context context, String path) {
String packageName = getPackageNameByPath(context, path);
if (TextUtils.isEmpty(packageName)) {
return true;
}
boolean isContain = com.gh.gamecenter.manager.PackageManager.isInstalled(packageName);
if (!isContain) {
return true;
}
boolean isInstalled = isInstalled(context, packageName);
if (!isInstalled) {
return true;
}
String signature = getApkSignatureByPackageName(context, packageName);
return publicKey.equals(signature);
}
/*
* 启动安装应用程序
*/
public static void launchSetup(final Context context, final String path) {
if (isCanLaunchSetup(context, path)) {
context.startActivity(PackageUtils.getInstallIntent(path));
} else {
DialogUtils.showPluginDialog(context, new DialogUtils.ConfiremListener() {
@Override
public void onConfirem() {
context.startActivity(PackageUtils.getUninstallIntent(context, path));
}
});
}
}
/*
* 获取应用第一次安装的时间
*/
public static long getInstalledTime(Context context, String packageName) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(packageName, 0);
return packageInfo.firstInstallTime;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return 0;
}
/*
* 解析签名
*/
@ -181,9 +165,6 @@ public class PackageUtils {
return null;
}
/*
* 获取apk的版本
*/
public static String getVersionByPackage(Context context, String packageName) {
try {
return context.getPackageManager().getPackageInfo(packageName,
@ -194,13 +175,11 @@ public class PackageUtils {
return null;
}
/*
* 获取所有已安装的软件的包名、版本(非系统应用)
*/
public static ArrayList<String> getAllPackageName(Context context) {
FilterManager filterManager = new FilterManager(context);
ArrayList<String> list = new ArrayList<>();
List<PackageInfo> packageInfos = context.getPackageManager().getInstalledPackages(0);
ArrayList<String> list = new ArrayList<String>();
List<PackageInfo> packageInfos = context.getPackageManager()
.getInstalledPackages(0);
for (int i = 0, size = packageInfos.size(); i < size; i++) {
PackageInfo packageInfo = packageInfos.get(i);
if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
@ -214,9 +193,6 @@ public class PackageUtils {
return list;
}
/*
* 启动应用
*/
public static void launchApplicationByPackageName(Context context,
String packageName) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(
@ -248,8 +224,33 @@ public class PackageUtils {
* 根据包名,判断是否已安装该游戏
*/
public static boolean isInstalled(Context context, String packageName) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
return intent != null;
Intent intent = context.getPackageManager().getLaunchIntentForPackage(
packageName);
if (intent == null) {
return false;
}
return true;
}
private static ArrayMap<String, Boolean> map;
public static boolean isContain(Context context, String packageName) {
if (TextUtils.isEmpty(packageName)) {
return false;
}
if (map == null) {
map = new ArrayMap<String, Boolean>();
List<PackageInfo> infos = context.getPackageManager()
.getInstalledPackages(0);
for (PackageInfo info : infos) {
map.put(info.packageName, true);
}
}
Boolean b = map.get(packageName);
if (b != null) {
return true;
}
return false;
}
/*
@ -276,4 +277,13 @@ public class PackageUtils {
return installIntent;
}
public static String getInstalledApkPath(Context context, String packageName) {
try {
return context.getPackageManager().getApplicationInfo(packageName,
0).sourceDir;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -11,17 +11,19 @@ import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import com.gh.gamecenter.R;
import com.gh.gamecenter.eventbus.EBReuse;
import com.gh.gamecenter.SplashScreenActivity;
import com.gh.gamecenter.eventbus.EBPlatformChanged;
import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Properties;
@ -31,15 +33,15 @@ import de.greenrobot.event.EventBus;
public class PlatformUtils {
private static PlatformUtils mInstance;
private Context context;
private ArrayMap<String, String> platformMap;
private ArrayMap<String, Integer> platformPicMap;
private ArrayMap<String, String> platformPicUrlMap;
private ArrayMap<String, String> platformColorMap;
private static PlatformUtils mInstance;
private Context context;
private PlatformUtils(Context con) {
this.context = con.getApplicationContext();
initMap();
@ -53,7 +55,7 @@ public class PlatformUtils {
}
private void initMap() {
ArrayMap<String, Integer> platformPicMap = new ArrayMap<>();
ArrayMap<String, Integer> platformPicMap = new ArrayMap<String, Integer>();
platformPicMap.put("360", R.drawable.platform_360);
platformPicMap.put("37wan", R.drawable.platform_37);
platformPicMap.put("91", R.drawable.platform_91);
@ -72,7 +74,7 @@ public class PlatformUtils {
platformPicMap.put("vivo", R.drawable.platform_vivo);
platformPicMap.put("wdj", R.drawable.platform_wdj);
ArrayMap<String, String> platformColorMap = new ArrayMap<>();
ArrayMap<String, String> platformColorMap = new ArrayMap<String, String>();
platformColorMap.put("360", "#218FA4");
platformColorMap.put("37wan", "#F5BD20");
platformColorMap.put("91", "#6A63CB");
@ -91,8 +93,8 @@ public class PlatformUtils {
platformColorMap.put("vivo", "#3FA5E3");
platformColorMap.put("wdj", "#5ABA3F");
ArrayMap<String, String> platformMap = new ArrayMap<>();
ArrayMap<String, String> platformPicUrlMap = new ArrayMap<>();
ArrayMap<String, String> platformMap = new ArrayMap<String, String>();
ArrayMap<String, String> platformPicUrlMap = new ArrayMap<String, String>();
SharedPreferences sharedPreferences = context.getSharedPreferences(
"gh_platform", Context.MODE_PRIVATE);
@ -102,7 +104,7 @@ public class PlatformUtils {
try {
properties
.load(context.getAssets().open("platform.properties"));
Set<String> pset = new HashSet<>();
Set<String> pset = new HashSet<String>();
for (Object object : properties.keySet()) {
platformMap.put(object.toString(),
(String) properties.get(object));
@ -116,7 +118,7 @@ public class PlatformUtils {
e.printStackTrace();
}
} else {
ArrayList<String> urls = new ArrayList<>();
ArrayList<String> urls = new ArrayList<String>();
for (String str : set) {
String[] platform = str.split("=");
platformMap.put(platform[0], platform[1]);
@ -175,7 +177,7 @@ public class PlatformUtils {
+ url.substring(url.lastIndexOf("/") + 1);
try {
int code = FileUtils.downloadFile(url, savePath);
if (code == HttpURLConnection.HTTP_OK) {
if (code == HttpStatus.SC_OK) {
success++;
}
} catch (IOException e) {
@ -187,7 +189,7 @@ public class PlatformUtils {
handler.post(new Runnable() {
@Override
public void run() {
EventBus.getDefault().post(new EBReuse("PlatformChanged"));
EventBus.getDefault().post(new EBPlatformChanged());
}
});
}
@ -199,24 +201,30 @@ public class PlatformUtils {
}
}
public ArrayMap<String, String> getPlatformMap() {
return platformMap;
}
public String getPlatformColor(String platform) {
if ("".equals(platform) || "官方版".equals(platform)) {
if ("".equals(platform) || "官方版".equals(platform)
|| "local_plugin".equals(platform)) {
return "#BB3D42";
}
String color = platformColorMap.get(platform);
if (color != null) {
return color;
}
return "#00B7FA";
return "#1BA4FC";
}
public int getPlatformPic(String platform) {
if ("".equals(platform) || "官方版".equals(platform)) {
if ("".equals(platform) || "官方版".equals(platform)
|| "local_plugin".equals(platform)) {
return R.drawable.platform_gf;
}
Integer id = platformPicMap.get(platform);
if (id != null) {
return id;
return id.intValue();
}
return 0;
}
@ -236,7 +244,7 @@ public class PlatformUtils {
}
}
if (path == null && !isCheck) {
ArrayList<String> urls = new ArrayList<>();
ArrayList<String> urls = new ArrayList<String>();
for (String value : platformPicUrlMap.values()) {
urls.add(value);
}
@ -247,14 +255,11 @@ public class PlatformUtils {
}
public String getPlatformName(String platform) {
if ("".equals(platform) || "官方版".equals(platform)) {
if ("".equals(platform) || "官方版".equals(platform)
|| "local_plugin".equals(platform)) {
return "官方版";
}
String platformName = platformMap.get(platform);
if (TextUtils.isEmpty(platformName)) {
getPlatform();
}
return platformName;
return platformMap.get(platform);
}
boolean isUpdate = false;
@ -265,25 +270,32 @@ public class PlatformUtils {
}
isUpdate = true;
JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
Config.HOST + "support/setting/platform",
TimestampUtils.addTimestamp(Config.HOST
+ "v1d45/support/setting/platform",
Constants.PLATFORM_CD),
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
Set<String> platformSet = new HashSet<>();
Set<String> pset = new HashSet<String>();
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
JSONObject jsonObject = response
.getJSONObject(i);
String code = jsonObject.getString("code");
String name = jsonObject.getString("name");
String pic = jsonObject.getString("pic");
String color = jsonObject.getString("color");
platformSet.add(code + "=" + name + "=" + pic + "=" + color);
pset.add(code + "=" + name + "=" + pic + "="
+ color);
}
SharedPreferences sp = context.getSharedPreferences(
"gh_platform", Context.MODE_PRIVATE);
sp.edit().putStringSet("platform", platformSet).apply();
SharedPreferences sharedPreferences = context
.getSharedPreferences("gh_platform",
Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putStringSet("platform", pset);
editor.apply();
initMap();
EventBus.getDefault().post(new EBReuse("PlatformChanged"));
EventBus.getDefault().post(new EBPlatformChanged());
} catch (JSONException e) {
e.printStackTrace();
}
@ -295,7 +307,6 @@ public class PlatformUtils {
isUpdate = false;
}
});
AppController.addToRequestQueue(request);
AppController.addToRequestQueue(request, SplashScreenActivity.class);
}
}

View File

@ -1,97 +0,0 @@
package com.gh.common.util;
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest;
import com.gh.gamecenter.volley.extended.StringExtendedRequest;
import org.json.JSONObject;
/**
* Created by khy on 2016/11/9.
*
*/
public class PostCommentUtils {
public static void addCommentData(Context context, String url, String content, PostCommentListener listener) {
addCommentData(context, url, content, true, listener);
}
public static void addCommentData(final Context context, final String url, final String content,
final boolean isCheck, final PostCommentListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
Request.Method.POST, url, content,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (listener != null){
listener.postSucced(response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null && error.networkResponse.statusCode == 401) {
addCommentData(context, url, content, false, listener);
return;
}
if (listener != null){
listener.postFailed(error);
}
}
});
request.setShouldCache(false);
request.addHeader("TOKEN", TokenUtils.getToken(context, isCheck));
AppController.addToRequestQueue(request);
}
}).start();
}
public static void addCommentVoto(final Context context, final String newsId, final PostCommentListener listener) {
addCommentVoto(context, newsId, true, listener);
}
public static void addCommentVoto(final Context context, final String newsId, final boolean isCheck
, final PostCommentListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
StringExtendedRequest request = new StringExtendedRequest(
Request.Method.POST, Config.COMMENT_HOST + "comment/" + newsId + "/vote",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
listener.postSucced(null);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null && error.networkResponse.statusCode == 401) {
addCommentVoto(context, newsId, false,listener);
} else {
listener.postFailed(error);
}
}
});
request.setShouldCache(false);
request.addHeader("TOKEN", TokenUtils.getToken(context, isCheck));
AppController.addToRequestQueue(request);
}
}).start();
}
public interface PostCommentListener {
void postSucced(JSONObject response);
void postFailed(VolleyError error);
}
}

View File

@ -43,6 +43,7 @@ public class RSEUtils {
* 使用公钥加密
*
* @param content
* @param key
* @return
*/
public static String encryptByPublic(String content) {
@ -67,7 +68,10 @@ public class RSEUtils {
/**
* 使用公钥解密
*
* @param content 密文
* @param content
* 密文
* @param key
* 商户私钥
* @return 解密后的字符串
*/
public static String decryptByPublic(String content) {

View File

@ -17,7 +17,7 @@ public class RandomUtils {
if (i == 0) {
index[i] = random.nextInt(size);
} else {
index[i] = random(random, index, i, size);
random(random, index, i, size);
}
}
return index;

View File

@ -13,7 +13,7 @@ public class RunningUtils {
/**
* 判断当前应用程序处于前台还是后台
*/
public static boolean isApplicationBroughtToBackground(Context context) {
public static boolean isApplicationBroughtToBackground(final Context context) {
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
@ -85,8 +85,8 @@ public class RunningUtils {
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> infos = activityManager.getRunningTasks(100);
for (RunningTaskInfo info : infos) {
if (info.topActivity.getPackageName().equals(context.getPackageName())
&& info.baseActivity.getPackageName().equals(context.getPackageName())) {
if (info.topActivity.getPackageName().equals(
context.getPackageName())) {
return true;
}
}

View File

@ -1,494 +0,0 @@
package com.gh.common.util;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.gh.gamecenter.R;
import com.gh.gamecenter.WeiBoShareActivity;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tencent.mm.sdk.platformtools.Util;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created by khy on 2016/9/4.
*/
public class ShareUtils {
private static ShareUtils instance;
private String shareUrl;
private String shareGameName;
private String shareIcon;
private String shareNewsTitle; // shareNewsTitle不为空就是新闻分享否则是游戏分享
private boolean isPlugin = false;
private static IWXAPI api;
private static Tencent mTencent;
private Handler handler;
private int[] arrLogo = {R.drawable.share_wechat_logo, R.drawable.share_wechatmoments_logo, R.drawable.share_qq_logo
, R.drawable.share_qzone_logo, R.drawable.share_sinaweibo_logo, R.drawable.share_shortmessage_logo
, R.drawable.share_copyfont_logo, R.drawable.share_cancel_logo};
private String[] arrLabel = {"微信好友", "朋友圈", "QQ好友", "QQ空间", "新浪微博", "短信", "复制链接", "取消"};
private PopupWindow popupWindow;
private Context context;
public static ShareUtils getInstance(Context context) {
if (instance == null) {
instance = new ShareUtils();
mTencent = Tencent.createInstance("1104659243", context); //初始化QQ分享
api = WXAPIFactory.createWXAPI(context, "wx3ffd0785fad18396"); //初始化微信分享
}
instance.context = context;
return instance;
}
public void showShareWindows(View view, String url, String gameName, String icon ,String newsTitle, boolean isPlugin){
this.shareIcon = icon;
this.shareGameName = gameName;
this.shareUrl = url;
this.shareNewsTitle = newsTitle;
this.isPlugin = isPlugin;
RelativeLayout contentView = new RelativeLayout(context);
contentView.setBackgroundColor(0x8c000000);
contentView.setFocusable(true);
contentView.setFocusableInTouchMode(true);
RecyclerView shareRecyclerView = new RecyclerView(context);
shareRecyclerView.setPadding(DisplayUtils.dip2px(context, 20), DisplayUtils.dip2px(context, 10), DisplayUtils.dip2px(context, 20), 0);
shareRecyclerView.setBackgroundColor(Color.WHITE);
//RecyclerView禁止滑动
GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 4){
@Override
public boolean canScrollVertically() {
return false;
}
};
shareRecyclerView.setLayoutManager(gridLayoutManager);
shareRecyclerView.setAdapter(new ShareRecyclerViewAdapter());
RelativeLayout.LayoutParams rlParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
, DisplayUtils.dip2px(context, 200));
rlParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
contentView.addView(shareRecyclerView,rlParams);
popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT
, LinearLayout.LayoutParams.MATCH_PARENT, true);
popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
contentView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0 && popupWindow != null
&& popupWindow.isShowing()) {
popupWindow.dismiss();
}
return false;
}
});
}
private class ShareRecyclerViewAdapter extends RecyclerView.Adapter<ShareRecyclerViewAdapter.ViewHolder>{
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DisplayUtils.dip2px(context, 90)));
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
linearLayout.setBackgroundResource(R.drawable.cardview_item_style);
ImageView shareLogo = new ImageView(context);
LinearLayout.LayoutParams logoParams = new LinearLayout.LayoutParams(DisplayUtils.dip2px(context, 45), DisplayUtils.dip2px(context, 45));
logoParams.setMargins(0, DisplayUtils.dip2px(context, 10), 0, 0);
shareLogo.setLayoutParams(logoParams);
TextView shareLabel = new TextView(context);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, DisplayUtils.dip2px(context,10), 0, 0);
shareLabel.setLayoutParams(layoutParams);
shareLabel.setGravity(Gravity.CENTER);
shareLabel.setTextColor(Color.parseColor("#3a3a3a"));
shareLabel.setTextSize(13);
linearLayout.addView(shareLogo);
linearLayout.addView(shareLabel);
return new ViewHolder(linearLayout);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.shareLogo.setImageResource(arrLogo[position]);
holder.shareLabel.setText(arrLabel[position]);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (holder.getPosition()){
case 0:
wechatSahre();
break;
case 1:
wechatMomentsSahre();
break;
case 2:
qqSahre();
break;
case 3:
qZoneSahre();
break;
case 4:
sinaWeiboSahre();
break;
case 5:
shortMessageSahre();
break;
case 6:
copyLink(shareUrl);
break;
case 7:
popupWindow.dismiss();
break;
}
}
});
}
@Override
public int getItemCount() {
return 8;
}
public class ViewHolder extends RecyclerView.ViewHolder{
LinearLayout linearLayout;
TextView shareLabel;
ImageView shareLogo;
public ViewHolder(View itemView) {
super(itemView);
linearLayout = (LinearLayout) itemView;
shareLogo = (ImageView) linearLayout.getChildAt(0);
shareLabel = (TextView) linearLayout.getChildAt(1);
}
}
}
//QQ分享
private void qqSahre(){
Utils.toast(context,"分享跳转中...");
Bundle params = new Bundle();
if (shareNewsTitle != null){
params.putString(QQShare.SHARE_TO_QQ_TITLE, shareNewsTitle);
params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "来自光环助手(最强卡牌神器)");
}else {
params.putString(QQShare.SHARE_TO_QQ_TITLE, "向你推荐:");
if (isPlugin){
params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareGameName + "(光环加速版)");
}else {
params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareGameName);
}
}
params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareUrl);
params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, shareIcon);
params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "光环助手");
mTencent.shareToQQ(
(Activity) context, params,QqShareListener);
popupWindow.dismiss();
}
//微信好友分享
private void wechatSahre(){
Utils.toast(context,"分享跳转中...");
WXWebpageObject webpage = new WXWebpageObject();
WXMediaMessage msg = new WXMediaMessage(webpage);
webpage.webpageUrl = shareUrl;
if (shareNewsTitle != null){
msg.title = shareNewsTitle;
msg.description = "来自光环助手(最强卡牌神器)";
}else {
if (isPlugin){
msg.title = "向你推荐";
msg.description = shareGameName + "(光环加速版)";
}else {
msg.title = "向你推荐";
msg.description = shareGameName;
}
}
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("webpage");
req.message = msg;
req.scene = SendMessageToWX.Req.WXSceneSession;
loadBitMap(shareIcon, msg, req);
popupWindow.dismiss();
}
//QQ空间分享
private void qZoneSahre(){
Utils.toast(context,"分享跳转中...");
Bundle params = new Bundle();
if (shareNewsTitle != null){
params.putString(QzoneShare.SHARE_TO_QQ_TITLE, shareNewsTitle);
}else {
params.putString(QzoneShare.SHARE_TO_QQ_TITLE, "向你推荐:");
if (isPlugin){
params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, shareGameName + "(光环加速版)");
}else {
params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, shareGameName);
}
}
ArrayList<String> imageUrls = new ArrayList<String>();
imageUrls.add(shareIcon);
params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_NO_TYPE);
params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, shareUrl);
params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, "光环助手");
mTencent.shareToQzone(
(Activity) context, params,QqShareListener);
popupWindow.dismiss();
}
//微信朋友圈分享
private void wechatMomentsSahre(){
Utils.toast(context,"分享跳转中...");
WXWebpageObject webpage = new WXWebpageObject();
WXMediaMessage msg = new WXMediaMessage(webpage);
webpage.webpageUrl = shareUrl;
if (shareNewsTitle != null){
msg.title = shareNewsTitle;
}else {
if (isPlugin){
msg.title = "向你推荐:" + shareGameName + "(光环加速版)";
}else {
msg.title = "向你推荐:" + shareGameName;
}
}
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("webpage");
req.message = msg;
req.scene = SendMessageToWX.Req.WXSceneTimeline;
loadBitMap(shareIcon, msg, req);
popupWindow.dismiss();
}
//新浪微博分享
private void sinaWeiboSahre(){
Intent intent = new Intent(context, WeiBoShareActivity.class);
Bundle bundle = new Bundle();
bundle.putString("shareNewsTitle", shareNewsTitle);
bundle.putString("shareIcon", shareIcon);
bundle.putString("shareGameName", shareGameName);
bundle.putString("shareUrl", shareUrl);
bundle.putBoolean("isPlugin",isPlugin);
intent.putExtras(bundle);
context.startActivity(intent);
popupWindow.dismiss();
}
//短信分享
private void shortMessageSahre(){
String smsBody;
if (shareNewsTitle != null){
smsBody = shareNewsTitle + shareUrl;
}else {
if (isPlugin){
smsBody = "向你推荐:" + shareGameName + "(光环加速版)" + shareUrl;
}else {
smsBody = "向你推荐:" + shareGameName + shareUrl;
}
}
Intent sendIntent = new Intent(Intent.ACTION_VIEW, Uri.parse( "smsto:" ));
sendIntent.putExtra( "sms_body", smsBody);
sendIntent.setType( "vnd.android-dir/mms-sms" );
try {
context.startActivity(sendIntent);
} catch (Exception e) {
Utils.toast(context, "系统异常,分享失败");
e.printStackTrace();
}
popupWindow.dismiss();
}
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
//复制文字链接
private void copyLink(String copyContent) {
ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setText(copyContent);
popupWindow.dismiss();
Utils.toast(context,"复制成功");
}
private void loadBitMap(final String iconUrl, final WXMediaMessage msg, final SendMessageToWX.Req req){
ImageUtils.getInstance().display(context, iconUrl, new BaseBitmapDataSubscriber() {
@Override
protected void onNewResultImpl(Bitmap bitmap) {
Bitmap compressBp = compressBitmap(bitmap);
Bitmap resultBp = addBackGround(compressBp);
msg.thumbData = Util.bmpToByteArray(resultBp, true);
api.sendReq(req);
}
@Override
protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
Utils.log("分享获取bitmap失败");
}
});
}
//添加背景防止图片格式为PNG的图片分享出现黑框问题
public Bitmap addBackGround(Bitmap result) {
Bitmap bgBitmap;
int[] colors = new int[result.getWidth()*result.getHeight()];
for (int i = 0; i < colors.length; i++) {
colors[i] = Color.WHITE;
}
bgBitmap = Bitmap.createBitmap(colors, result.getWidth(), result.getHeight(), Bitmap.Config.ARGB_8888);
Bitmap newmap = Bitmap
.createBitmap(result.getWidth(), result.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newmap);
canvas.drawBitmap(bgBitmap, 0, 0, null);
canvas.drawBitmap(result, (result.getHeight() - result.getWidth()) / 2,
(result.getHeight() - result.getWidth()) / 2, null);
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
return newmap;
}
//压缩图片
private Bitmap compressBitmap(Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bos);
float zoom = (float) Math.sqrt(10 * 1024 / (float) bos.toByteArray().length);
Matrix matrix = new Matrix();
matrix.setScale(zoom, zoom);
Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bos.reset();
result.compress(Bitmap.CompressFormat.JPEG, 85, bos);
while(bos.toByteArray().length > 10 * 1024){
System.out.println(bos.toByteArray().length);
matrix.setScale(0.9f, 0.9f);
result = Bitmap.createBitmap(result, 0, 0, result.getWidth(), result.getHeight(), matrix, true);
bos.reset();
result.compress(Bitmap.CompressFormat.JPEG, 85, bos);
}
return result;
}
//QQ或者QQ空间分享回调处理
public IUiListener QqShareListener = new IUiListener() {
@Override
public void onComplete(Object o) {
Utils.toast(context, "分享成功");
}
@Override
public void onError(UiError uiError) {
Utils.toast(context, "分享失败");
}
@Override
public void onCancel() {
Utils.toast(context, "分享已取消");
}
};
//检查是否安装手机QQ
public static boolean isQQClientAvailable(Context context){
final PackageManager packageManager = context.getPackageManager();
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
if (pinfo != null) {
for (int i = 0; i < pinfo.size(); i++) {
String pn = pinfo.get(i).packageName; if (pn.equals("com.tencent.mobileqq")) {
return true;
}
}
}
return false;
}
}

View File

@ -5,7 +5,7 @@ public class SpeedUtils {
public static String getSpeed(long kSpeed) {
if (kSpeed >= 1000) {
float mSpeed = kSpeed / 1024f;
String str = String.valueOf(mSpeed);
String str = mSpeed + "";
if (str.length() > 4) {
str = str.substring(0, 4);
}
@ -14,9 +14,10 @@ public class SpeedUtils {
return kSpeed + "K/s";
}
public static String getRemainTime(long totalSize, long currentSize, long speed) {
public static String getRemainTime(long totalSize, long currentSize,
long speed) {
long remainSize = totalSize - currentSize;
long remainTime;
long remainTime = 0;
if (speed != 0) {
remainTime = remainSize / speed;
} else {
@ -34,5 +35,4 @@ public class SpeedUtils {
return second + "";
}
}
}

View File

@ -1,10 +1,8 @@
package com.gh.common.util;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import java.util.regex.Pattern;
@ -13,113 +11,43 @@ public class TimestampUtils {
// 基准时间
private static final long BASE = 1426608000000L;
private static ArrayMap<String, Integer> intervalMap; // 间隔
private static ArrayMap<String, Integer> cdMap; // cd
public static void initMap() {
initIntervalMap();
initCDMap();
}
private static void initIntervalMap() {
intervalMap = new ArrayMap<>();
intervalMap.put("^" + Config.HOST + "index/slides" + "$", 5);
intervalMap.put("^" + Config.HOST + "game/chajian" + "$", 10);
intervalMap.put("^" + Config.HOST + "game/tuijian" + "$", 15);
intervalMap.put("^" + Config.HOST + "game/.+/detail" + "$", 20);
intervalMap.put("^" + Config.HOST + "game/.+/digest" + "$", 25);
intervalMap.put("^" + Config.HOST + "game/remenkapai" + "$", 30);
intervalMap.put("^" + Config.HOST + "game/.+/news_digest" + "$", 35);
intervalMap.put("^" + Config.HOST + "game/column/.+\\?page=.+" + "$", 40);
intervalMap.put("^" + Config.HOST + "support/package/.+/game/digest" + "$", 45);
intervalMap.put("^" + Config.HOST + "game/danjiyouxi\\?limit=20\\&offset=.+" + "$", 50);
intervalMap.put("^" + Config.HOST + "news/.+/digest" + "$", 55);
intervalMap.put("^" + Config.HOST + "news/.+/detail" + "$", 60);
intervalMap.put("^" + Config.HOST + "news/.+/suggestion" + "$", 65);
intervalMap.put("^" + Config.HOST + "game/.+/news\\?limit=3" + "$", 70);
intervalMap.put("^" + Config.HOST + "zixun/zixun\\?limit=20\\&offset=.+" + "$", 75);
intervalMap.put("^" + Config.HOST + "game/.+/news\\?limit=20\\&offset=.+" + "$", 80);
intervalMap.put("^" + Config.HOST + "zixun/yuanchuang\\?limit=20\\&offset=.+" + "$", 85);
intervalMap.put("^" + Config.HOST + "news\\?type_group=.+\\&offset=.+\\&limit=20" + "$", 90);
intervalMap.put("^" + Config.HOST + "zixun/guanzhu\\?key=.+\\&limit=20\\&offset=.+" + "$", 95);
intervalMap.put("^" + Config.HOST + "game/.+/news\\?limit=20\\&offset=.+\\&type=.+" + "$", 100);
intervalMap.put("^" + Config.HOST + "zixun/guanzhu\\?game_id=.+\\&limit=20\\&offset=.+" + "$", 105);
intervalMap.put("^" + Config.HOST + "search/news\\?game_id=.+\\&keyword=.+\\&page=.+\\&limit=20" + "$", 110);
intervalMap.put("^" + Config.HOST + "search/game\\?keyword=.+" + "$", 115);
intervalMap.put("^" + Config.HOST + "support/setting/platform" + "$", 120);
intervalMap.put("^" + Config.HOST + "update/package/.+" + "$", 125);
intervalMap.put("^" + Config.HOST + "update/game/.+/package/.+" + "$", 130);
intervalMap.put("^" + Config.COMMENT_HOST + "article/.+/comment\\?limit=10\\&offset=.+" + "$", 135);
intervalMap.put("^" + Config.COMMENT_HOST + "article/.+/comment\\?order=hot\\&limit=10\\&offset=.+" + "$", 140);
}
private static void initCDMap() {
cdMap = new ArrayMap<>();
cdMap.put("^" + Config.HOST + "index/slides" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/chajian" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/tuijian" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/.+/detail" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/.+/digest" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/remenkapai" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/.+/news_digest" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/column/.+\\?page=.+" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "support/package/.+/game/digest" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "game/danjiyouxi\\?limit=20\\&offset=.+" + "$", Constants.GAME_CD);
cdMap.put("^" + Config.HOST + "news/.+/digest" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "news/.+/detail" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "news/.+/suggestion" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "game/.+/news\\?limit=3" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "zixun/zixun\\?limit=20\\&offset=.+" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "game/.+/news\\?limit=20\\&offset=.+" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "zixun/yuanchuang\\?limit=10\\&offset=.+" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "news\\?type_group=.+\\&offset=.+\\&limit=20" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "zixun/guanzhu\\?key=.+\\&limit=20\\&offset=.+" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "game/.+/news\\?limit=20\\&offset=.+\\&type=.+" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "zixun/guanzhu\\?game_id=.+\\&limit=20\\&offset=.+" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "search/news\\?game_id=.+\\&keyword=.+\\&page=.+\\&limit=20" + "$", Constants.NEWS_CD);
cdMap.put("^" + Config.HOST + "search/game\\?keyword=.+" + "$", Constants.SEARCH_CD);
cdMap.put("^" + Config.HOST + "support/setting/platform" + "$", Constants.PLATFORM_CD);
cdMap.put("^" + Config.HOST + "update/package/.+" + "$", Constants.UPDATE_CD);
cdMap.put("^" + Config.HOST + "update/game/.+/package/.+" + "$", Constants.UPDATE_CD);
cdMap.put("^" + Config.COMMENT_HOST + "article/.+/comment\\?limit=10\\&offset=.+" + "$", Constants.COMMENT_CD);
cdMap.put("^" + Config.COMMENT_HOST + "article/.+/comment\\?order=hot\\&limit=10\\&offset=.+" + "$", Constants.COMMENT_CD);
cdMap.put("^" + Config.HOST + "device/.+/concern" + "$", 0);
cdMap.put("^" + Config.HOST + "device/.+/concern/.+" + "$", 0);
cdMap.put("^" + Config.HOST + "stat/download" + "$", 0);
cdMap.put("^" + Config.HOST + "disclaimer" + "$", 0);
cdMap.put("^" + Config.HOST + "search/game/default" + "$", 0);
cdMap.put("^" + Config.HOST + "support/upgrade\\?version=.+\\&channel=.+" + "$", 0);
cdMap.put("^" + Config.HOST + "support/time/current" + "$", 0);
cdMap.put("^" + Config.HOST + "support/setting/ui" + "$", 0);
cdMap.put("^" + Config.HOST + "support/download_status\\?version=.+\\&channel=.+" + "$", 0);
cdMap.put("^" + Config.HOST + "support/suggestion" + "$", 0);
cdMap.put("^" + Config.HOST + "game/.+/serverInfo" + "$", 0);
cdMap.put("^" + Config.HOST + "support/package/unused\\?skip=.+" + "$", 0);
}
private static ArrayMap<String, Integer> getIntervalMap() {
if (intervalMap == null) {
intervalMap = new ArrayMap<>();
}
return intervalMap;
}
private static ArrayMap<String, Integer> getCdMap() {
if (cdMap == null) {
cdMap = new ArrayMap<>();
}
return cdMap;
}
private static ArrayMap<String, Integer> map;
/*
* 根据CD获取时间戳
*/
public static long getTimestamp(String url, int cd) {
if (map == null){
map = new ArrayMap<String, Integer>();
map.put("^" + Config.HOST + "v1d45/index/kapaitoutiao" + "$", 5);
map.put("^" + Config.HOST + "v1d45/index/remenkapai" + "$", 10);
map.put("^" + Config.HOST + "v1d45/index/xincekapai" + "$", 15);
map.put("^" + Config.HOST + "v1d45/index/yuedujingxuan" + "$", 20);
map.put("^" + Config.HOST + "v1d45/index/zuixinchajian" + "$", 25);
map.put("^" + Config.HOST + "v1d45/search/game\\?keyword=.+" + "$", 30);
map.put("^" + Config.HOST + "v1d45/plugin/slide" + "$", 40);
map.put("^" + Config.HOST + "v1d45/plugin/jingpin\\?limit=20\\&offset=.+" + "$", 35);
map.put("^" + Config.HOST + "v1d45/plugin/zuixin\\?limit=20\\&offset=.+" + "$", 45);
map.put("^" + Config.HOST + "v1d45/plugin/danji\\?limit=20\\&offset=.+" + "$", 50);
map.put("^" + Config.HOST + "v1d45/game/remenkapai" + "$", 60);
map.put("^" + Config.HOST + "v1d45/game/youxituijian" + "$", 85);
map.put("^" + Config.HOST + "v1d45/game/xincekapai\\?limit=10\\&offset=.+" + "$", 90);
map.put("^" + Config.HOST + "v1d45/game/.+/digest" + "$", 55);
map.put("^" + Config.HOST + "v1d45/game/.+/digest" + "$", 65);
map.put("^" + Config.HOST + "v1d45/game/.+/news_digest" + "$", 70);
map.put("^" + Config.HOST + "v1d45/game/.+/news\\?limit=3\\&offset=0\\&type_group=.+" + "$", 75);
map.put("^" + Config.HOST + "v1d45/game/.+/news\\?limit=5\\&offset=0\\&type_group=.+" + "$", 80);
map.put("^" + Config.HOST + "v1d45/news/.+/suggestion" + "$", 95);
map.put("^" + Config.HOST + "v1d45/news\\?type_group=.+\\&offset=.+\\&limit=20" + "$", 100);
map.put("^" + Config.HOST + "v1d45/support/setting/platform" + "$", 105);
map.put("^" + Config.HOST + "v1d45/support/package/.+/game/digest" + "$", 110);
map.put("^" + Config.HOST + "v1d45/support/package/update\\?package=.+" + "$", 115);
}
long base = BASE;
for (String key : getIntervalMap().keySet()){
for (String key : map.keySet()){
if (Pattern.matches(key, url)) {
Utils.log("url add base = " + url);
base += getIntervalMap().get(key);
base += map.get(key);
break;
}
}
@ -131,20 +59,7 @@ public class TimestampUtils {
/*
* 为url添加timestamp
*/
public static String addTimestamp(String url) {
if (TextUtils.isEmpty(url)) {
return url;
}
int cd = 0;
for (String key : getCdMap().keySet()){
if (Pattern.matches(key, url)) {
cd = getCdMap().get(key);
break;
}
}
if (cd == 0) {
return url;
}
public static String addTimestamp(String url, int cd) {
if (url.contains("?")) {
String u = url + "&timestamp=" + getTimestamp(url, cd);
Utils.log("url = " + u);
@ -155,7 +70,7 @@ public class TimestampUtils {
return u;
}
}
/*
* 去除url中的timestamp
*/

View File

@ -3,27 +3,13 @@ package com.gh.common.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.Response;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.gh.gamecenter.volley.extended.StringExtendedRequest;
import com.tencent.stat.StatConfig;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
@ -34,112 +20,57 @@ import java.util.Map;
public class TokenUtils {
// 注册设备
public static synchronized String register(final Context context) {
HashMap<String, String> params = new HashMap<>();
String android_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
if (!TextUtils.isEmpty(android_id)) {
params.put("ANDROID_ID", android_id);
// 获取用户token
public static synchronized String getToken(Context context) {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE,
Context.MODE_PRIVATE);
String token = sp.getString("token", null);
if (token != null) {
long expire = sp.getLong("token_expire", 0) * 1000 - 10 * 1000;
long time = System.currentTimeMillis();
// 判断token是否过期
if (time < expire) {
return token;
}
}
String imei = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
if (!TextUtils.isEmpty(imei)) {
params.put("IMEI", imei);
}
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String mac = wm.getConnectionInfo().getMacAddress();
if (!TextUtils.isEmpty(mac) || !":::::".equals(mac)) {
params.put("MAC", mac);
} else {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
sp.edit().putBoolean("isUploadMac", false).apply();
}
String mid = StatConfig.getMid(context);
if (!TextUtils.isEmpty(mid) || !"0".equals(mid)) {
params.put("MTA_ID", mid);
} else {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
sp.edit().putBoolean("isUploadMid", false).apply();
}
String url = Config.USER_HOST + "device/register";
try {
JSONObject body = new JSONObject(params);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.connect();
OutputStreamWriter outputStream = new OutputStreamWriter(
connection.getOutputStream(), "utf-8");
outputStream.write(body.toString());
outputStream.flush();
outputStream.close();
if (connection.getResponseCode() == 200) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
reader.close();
// Map<String, String> params = DeviceUtils.getDeviceParams(context);
Map<String, String> params = new HashMap<String, String>();
String url = Config.HOST + "v1d45/token/visit";
//判断是否已登录
if (sp.getBoolean("isLogin", false)) {
// 已登录,获取用户名和密码自动登录
String username = sp.getString("username", null);
String password = sp.getString("password", null);
if (username == null || password == null) {
url = Config.HOST + "v2/token/user?time=" + System.currentTimeMillis();
params.put("username", username);
try {
JSONObject response = new JSONObject(builder.toString());
String device_id = response.getString("device_id");
// 保存device_id
saveDeviceId(context, device_id);
Utils.log("device_id = " + device_id);
return device_id;
} catch (JSONException e) {
String s = RSEUtils.encryptByPublic(password + username + System.currentTimeMillis() / 1000);
Utils.log("加密 = " + s);
params.put("password", s);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static synchronized String getToken(Context context) {
return getToken(context, true);
}
// 获取用户token
public static synchronized String getToken(Context context, boolean isCheck) {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
String token = sp.getString("token", null);
if (isCheck) {
if (token != null) {
long expire = sp.getLong("token_expire", 0) * 1000 - 10 * 1000;
long time = Utils.getTime(context);
// 判断token是否过期
if (time < expire) {
// token未过期
return token;
}
} else {
url = Config.HOST + "v2/token/mobile?time=" + System.currentTimeMillis();
String mobile = sp.getString("mobile", null);
params.put("mobile_number", mobile);
}
}
// 重新获取token
String url = Config.USER_HOST + "login";
Map<String, String> params = new HashMap<>();
params.put("device_id", getDeviceId(context));
try {
JSONObject body = new JSONObject(params);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
HttpURLConnection connection = (HttpURLConnection) new URL(url)
.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.addRequestProperty("Device", DeviceUtils.getDeviceHeader(context));
connection.connect();
@ -159,19 +90,12 @@ public class TokenUtils {
}
reader.close();
try {
Editor editor = sp.edit();
JSONObject jsonObject = new JSONObject(builder.toString());
editor.putString("user_name", jsonObject.getString("name"));
editor.putString("user_icon", jsonObject.getString("icon"));
jsonObject = jsonObject.getJSONObject("token");
editor.putString("token", jsonObject.getString("value"));
Editor editor = sp.edit();
editor.putString("token", jsonObject.getString("token"));
editor.putLong("token_expire", jsonObject.getLong("expire"));
editor.apply();
if (token != null && token.equals(jsonObject.getString("value"))) {
// 服务器返回的token和本地已存的token相同更新本地时间
getTime(context);
}
return jsonObject.getString("value");
return jsonObject.getString("token");
} catch (JSONException e) {
e.printStackTrace();
}
@ -179,189 +103,7 @@ public class TokenUtils {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// 获取服务器时间
public static synchronized void getTime(Context context) {
final SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
StringExtendedRequest request = new StringExtendedRequest(
Request.Method.GET, Config.HOST + "support/time/current",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.matches("^[0-9]{10}$")) {
try {
Editor editor = sp.edit();
editor.putLong("server_time", Long.parseLong(response));
editor.putLong("client_time", System.currentTimeMillis() / 1000);
editor.apply();
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
}, null);
request.setShouldCache(false);
AppController.addToRequestQueue(request);
}
public static synchronized void saveDeviceId(Context context, String device_id){
saveSharedPreferences(context, device_id);
saveDataFile(context, device_id);
svaeSDCard(device_id, "/gh-uuid");// SDCard根目录
svaeSDCard(device_id, "/system"); // SDCard system目录
svaeSDCard(device_id, "/data"); // SDCard data目录
}
//将uuid存到sp
private static void saveSharedPreferences(Context context, String device_id) {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putString("uuid", device_id);
edit.apply();
Utils.log("saveDeviceId", "保存成功SP");
}
//将uuid存到data/data/PackageName/files文件夹下
private static void saveDataFile(Context context, String device_id) {
FileOutputStream fops;
try {
fops = context.openFileOutput("uuid", Context.MODE_PRIVATE);
fops.write(device_id.getBytes());
fops.close();
Utils.log("saveDeviceId", "保存成功DataFile");
} catch (Exception e) {
Utils.log("保存uuid到data/data/PackageName/files文件异常" + e.toString());
e.printStackTrace();
}
}
//将uuid存到SD卡
private static void svaeSDCard(String device_id, String saveDir) {
File sdCardDir = Environment.getExternalStorageDirectory();
String path = sdCardDir.getPath() + saveDir;
File file = new File(path);
if (!file.exists()){
file.mkdirs();
}
// 判断文件是否存在,存在则删除
File uuidFile = new File(path +"/uuid");
if (uuidFile.isFile() && uuidFile.exists()){
Utils.log(saveDir + "文件夹里的文件存在,执行删除操作");
uuidFile.delete();
}
File writeFile = new File(file, "uuid");
FileOutputStream fos;
try {
fos = new FileOutputStream(writeFile);
fos.write(device_id.getBytes());
fos.close();
Utils.log("saveDeviceId", "保存成功SDCard"+"目录为:"+saveDir);
} catch (Exception e) {
Utils.log("保存uuid到SDCard异常" + saveDir + e.toString());
e.printStackTrace();
}
}
// 启动助手时检查uuid
public static void checkDeviceID(Context context) {
String uuid = loadSharedPreferences(context, false);
if (uuid == null) {
// 重新获取uuid保存
return;
}
// 检查
if (loadSharedPreferences(context, true) == null){
saveSharedPreferences(context, uuid);
}
if (loadDataFile(context ,true) == null){
saveDataFile(context, uuid);
}
String[] dirName = {"/gh-uuid", "/system", "/data"};
for (int i = 0; i< 3; i++) {
String s = loadSDCard(dirName[i]);
if (s == null) {
svaeSDCard(uuid, dirName[i]);
}
}
}
public static synchronized String getDeviceId(Context context) {
return loadSharedPreferences(context, false);
}
//读取SharedPreferences的uuid
private static String loadSharedPreferences(Context context, boolean isCheck) {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
String uuid = sp.getString("uuid", null);
if (isCheck){
return uuid;
}
if (uuid == null){
return loadDataFile(context, false);
}
Utils.log("getDeviceId", "获取成功SP" + uuid);
return uuid;
}
//读取data/data/PackageName/files的uuid
private static String loadDataFile(Context context, boolean isCheck) {
File file = new File(context.getFilesDir(), "uuid");
if (file.exists()){
try {
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[1024];
int count = -1;
String uuid = null;
while ((count = fis.read(b)) != -1) {
uuid = new String(b, 0, count, "UTF-8");
}
Utils.log("getDeviceId", "获取成功DataFile"+ uuid);
return uuid;
} catch (Exception e) {
e.printStackTrace();
}
}else if (!isCheck){
String[] dirName = {"/gh-uuid", "/system", "/data"};
for (int i = 0; i< 3; i++) {
String s = loadSDCard(dirName[i]);
if (s != null) {
return s;
}
}
}
return null;
}
//读取SD卡的uuid
private static String loadSDCard(String saveDir){
File sdCardDir = Environment.getExternalStorageDirectory();
String path = sdCardDir.getPath() + saveDir;
File file = new File(path, "uuid");
if (file.exists()){
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = new FileInputStream(file);
bos = new ByteArrayOutputStream();
byte[] array = new byte[1024];
int len = -1;
while( (len = fis.read(array)) != -1){
bos.write(array,0,len);
}
bos.close();
fis.close();
Utils.log("getDeviceId", "获取成功SDCard"+"目录为:"+saveDir+"::"+bos.toString());
return bos.toString();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

View File

@ -0,0 +1,64 @@
package com.gh.common.util;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author 温冠超
* @email 294299195@qq.com
* @date 2015-8-19
* @update 2015-8-19
* @des 控制debug调试信息
*/
public class Trace {
private final String TAG = "gh_debug";
private Map<String, Boolean> maps;//(tag, boolean), boolean = true,表示debug信息可以显示,否则不能显示
private static Trace mInstance;
private Trace(){
maps = new HashMap<String ,Boolean>();
}
public static Trace getInstance(){
synchronized (Trace.class) {
if(mInstance == null)
mInstance = new Trace();
return mInstance;
}
}
public void debug(String tag, String msg){
if(maps.get(tag) == null){
maps.put(tag, false);
}
if(maps.get(tag) == true){
Log.d(TAG, tag + "==>" + msg);
}
}
/**
*
* @param tag debug的tag
* @param flag true则输出该tag的debug信息否则不输出该tag的debug信息
*/
public void setClassDebug(String tag, boolean flag){
maps.put(tag, flag);
}
/**
*
* @param flag true--所有tag的debug消息都可以输出否则全部都不输出
*/
public void setDebug(boolean flag){
for ( String tag : maps.keySet()) {
maps.put(tag, flag);
}
}
}

View File

@ -26,12 +26,14 @@ public class TrafficUtils {
synchronized (TrafficUtils.class) {
if (instance == null) {
instance = new TrafficUtils(context);
if (update)
instance.update();
return instance;
}
}
}
if (update) {
if (update)
instance.update();
}
return instance;
}
@ -45,7 +47,9 @@ public class TrafficUtils {
// 获取所有的安装在手机上的应用软件的信息,并且获取这些软件里面的权限信息
PackageManager pm = context.getPackageManager();// 获取系统应用包管理
// 获取每个包内的androidmanifest.xml信息它的权限等等
List<PackageInfo> pinfos = pm.getInstalledPackages(PackageManager.GET_PERMISSIONS);
List<PackageInfo> pinfos = pm
.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES
| PackageManager.GET_PERMISSIONS);
// 遍历每个应用包信息
for (PackageInfo info : pinfos) {
// 请求每个程序包对应的androidManifest.xml里面的权限
@ -60,7 +64,9 @@ public class TrafficUtils {
long rx = TrafficStats.getUidRxBytes(uId);
// 如果返回-1代表不支持使用该方法注意必须是2.2以上的
long tx = TrafficStats.getUidTxBytes(uId);
if (rx >= 0 && tx >= 0) {
if (rx < 0 || tx < 0) {
continue;
} else {
db.update(info.packageName, rx + tx);
}
}

View File

@ -1,48 +1,29 @@
package com.gh.common.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import com.gh.common.constant.Config;
import com.gh.gamecenter.R;
import java.lang.reflect.Field;
public class Utils {
private static final boolean DEBUG = true;
private final static String TAG = "result";
private static final boolean DEBUG = false;
public static void log(String msg) {
log(TAG, msg);
}
public static void log(Object obj) {
log(TAG, obj.getClass().getSimpleName() + ":" + obj.toString());
}
public static void log(String tag, String msg) {
log(Log.ERROR, tag, msg);
}
public static void log(String tag, Object obj) {
log(Log.ERROR, tag, obj.getClass().getSimpleName() + ":" + obj.toString());
}
private static void log(int priority, String tag, String msg) {
if (DEBUG) {
Log.println(priority, tag, msg);
Log.e("result", msg);
}
}
private static void log(int priority, String tag, Object obj) {
public static void log(Object obj) {
if (DEBUG) {
Log.println(priority, tag, obj.getClass().getSimpleName() + ":" + obj.toString());
Log.e("result", obj.getClass().getSimpleName() + " = " + obj.toString());
}
}
@ -50,20 +31,6 @@ public class Utils {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
/*
* 获取服务器时间
*/
public static long getTime(Context context) {
SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
long serverTime = sp.getLong("server_time", 0);
long clientTime = sp.getLong("client_time", 0);
if (serverTime == 0 || clientTime == 0) {
return System.currentTimeMillis() / 1000;
} else {
return serverTime + (System.currentTimeMillis() / 1000 - clientTime);
}
}
public static void hideSoftInput(Context context, EditText editText) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);

View File

@ -1,249 +0,0 @@
package com.gh.common.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import com.gh.gamecenter.R;
/**
* Created by LGT on 2016/8/31.
*/
public class CardLinearLayout extends LinearLayout {
private Drawable mLeftDrawable, mTopDrawable, mRightDrawable, mBottomDrawable, mCenterDrawable;
private Drawable mLeftTopDrawable, mRightTopDrawable, mLeftBottomDrawable, mRightBottomDrawable;
private int mLeft, mTop, mRight, mBottom;
private boolean isBottom;
public CardLinearLayout(Context context) {
this(context, null);
}
public CardLinearLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CardLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
setWillNotDraw(false);
isBottom = true;
mLeftDrawable = getContext().getResources().getDrawable(R.drawable.frame_left);
mTopDrawable = getContext().getResources().getDrawable(R.drawable.frame_top);
mRightDrawable = getContext().getResources().getDrawable(R.drawable.frame_right);
mBottomDrawable = getContext().getResources().getDrawable(R.drawable.frame_bottom);
mCenterDrawable = getContext().getResources().getDrawable(R.drawable.frame_center);
mLeftTopDrawable = getContext().getResources().getDrawable(R.drawable.frame_left_top_square);
mRightTopDrawable = getContext().getResources().getDrawable(R.drawable.frame_right_top_square);
mLeftBottomDrawable = getContext().getResources().getDrawable(R.drawable.frame_left_bottom_square);
mRightBottomDrawable = getContext().getResources().getDrawable(R.drawable.frame_right_bottom_square);
if (attrs != null) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CardLayout);
mLeft = ta.getDimensionPixelSize(R.styleable.CardLayout_left, 0);
mTop = ta.getDimensionPixelSize(R.styleable.CardLayout_top, 0);
mRight = ta.getDimensionPixelSize(R.styleable.CardLayout_right, 0);
mBottom = ta.getDimensionPixelSize(R.styleable.CardLayout_bottom, 0);
ta.recycle();
}
setPadding(getPaddingLeft() + mLeft, getPaddingTop() + mTop, getPaddingRight() + mRight, getPaddingBottom() + mBottom);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mLeft != 0 && mTop != 0 && mRight != 0 && mBottom != 0) {
// 左、上、右、下
if (mLeftTopDrawable != null) {
mLeftTopDrawable.setBounds(0, 0, mLeft, mTop);
mLeftTopDrawable.draw(canvas);
}
if (mTopDrawable != null) {
mTopDrawable.setBounds(mLeft, 0, getWidth() - mRight, mTop);
mTopDrawable.draw(canvas);
}
if (mRightTopDrawable != null) {
mRightTopDrawable.setBounds(getWidth() - mRight, 0, getWidth(), mTop);
mRightTopDrawable.draw(canvas);
}
if (mLeftDrawable != null) {
mLeftDrawable.setBounds(0, mTop, mLeft, getHeight() - mBottom);
mLeftDrawable.draw(canvas);
}
if (mRightDrawable != null) {
mRightDrawable.setBounds(getWidth() - mRight, mTop, getWidth(), getHeight() - mBottom);
mRightDrawable.draw(canvas);
}
if (mLeftBottomDrawable != null) {
mLeftBottomDrawable.setBounds(0, getHeight() - mBottom, mLeft, getHeight());
mLeftBottomDrawable.draw(canvas);
}
if (isBottom) {
if (mBottomDrawable != null) {
mBottomDrawable.setBounds(mLeft, getHeight() - mBottom, getWidth() - mRight, getHeight());
mBottomDrawable.draw(canvas);
}
} else {
if (mCenterDrawable != null) {
mCenterDrawable.setBounds(mLeft, getHeight() - mBottom, getWidth() - mRight, getHeight());
mCenterDrawable.draw(canvas);
}
}
if (mRightBottomDrawable != null) {
mRightBottomDrawable.setBounds(getWidth() - mRight, getHeight() - mBottom, getWidth(), getHeight());
mRightBottomDrawable.draw(canvas);
}
} else if (mLeft != 0 && mTop != 0 && mRight != 0) {
// 左、上、右
if (mLeftTopDrawable != null) {
mLeftTopDrawable.setBounds(0, 0, mLeft, mTop);
mLeftTopDrawable.draw(canvas);
}
if (mTopDrawable != null) {
mTopDrawable.setBounds(mLeft, 0, getWidth() - mRight, mTop);
mTopDrawable.draw(canvas);
}
if (mRightTopDrawable != null) {
mRightTopDrawable.setBounds(getWidth() - mRight, 0, getWidth(), mTop);
mRightTopDrawable.draw(canvas);
}
if (mLeftDrawable != null) {
mLeftDrawable.setBounds(0, mTop, mLeft, getHeight());
mLeftDrawable.draw(canvas);
}
if (mRightDrawable != null) {
mRightDrawable.setBounds(getWidth() - mRight, mTop, getWidth(), getHeight());
mRightDrawable.draw(canvas);
}
} else if (mLeft != 0 && mBottom != 0 && mRight != 0) {
// 左、下、右
if (mLeftDrawable != null) {
mLeftDrawable.setBounds(0, 0, mLeft, getHeight() - mBottom);
mLeftDrawable.draw(canvas);
}
if (mRightDrawable != null) {
mRightDrawable.setBounds(getWidth() - mRight, 0, getWidth(), getHeight() - mBottom);
mRightDrawable.draw(canvas);
}
if (mLeftBottomDrawable != null) {
mLeftBottomDrawable.setBounds(0, getHeight() - mBottom, mLeft, getHeight());
mLeftBottomDrawable.draw(canvas);
}
if (isBottom) {
if (mBottomDrawable != null) {
mBottomDrawable.setBounds(mLeft, getHeight() - mBottom, getWidth() - mRight, getHeight());
mBottomDrawable.draw(canvas);
}
} else {
if (mCenterDrawable != null) {
mCenterDrawable.setBounds(mLeft, getHeight() - mBottom, getWidth() - mRight, getHeight());
mCenterDrawable.draw(canvas);
}
}
if (mRightBottomDrawable != null) {
mRightBottomDrawable.setBounds(getWidth() - mRight, getHeight() - mBottom, getWidth(), getHeight());
mRightBottomDrawable.draw(canvas);
}
} else if (mLeft != 0 && mRight != 0) {
// 左、右
if (mLeftDrawable != null) {
mLeftDrawable.setBounds(0, 0, mLeft, getHeight());
mLeftDrawable.draw(canvas);
}
if (mRightDrawable != null) {
mRightDrawable.setBounds(getWidth() - mRight, 0, getWidth(), getHeight());
mRightDrawable.draw(canvas);
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int newHeight = MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec) + mTop + mBottom,
MeasureSpec.getMode(heightMeasureSpec));
super.onMeasure(widthMeasureSpec, newHeight);
}
public void setBottom(boolean bottom) {
isBottom = bottom;
}
public void setShadow(int left, int top, int right, int bottom) {
setPadding(getPaddingLeft() - mLeft + left,
getPaddingTop() - mTop + top,
getPaddingRight() - mRight + right,
getPaddingBottom() - mBottom + bottom);
this.mLeft = left;
this.mTop = top;
this.mRight = right;
this.mBottom = bottom;
}
public void setmLeft(int left) {
setPadding(getPaddingLeft() - mLeft + left, getPaddingTop(), getPaddingRight(), getPaddingBottom());
this.mLeft = left;
}
public void setmTop(int top) {
setPadding(getPaddingLeft(), getPaddingTop() - mTop + top, getPaddingRight(), getPaddingBottom());
this.mTop = top;
}
public void setmRight(int right) {
setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight() - mRight + right, getPaddingBottom());
this.mRight = right;
}
public void setmBottom(int bottom) {
setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), getPaddingBottom() - mBottom + bottom);
this.mBottom = bottom;
}
public int getmLeft() {
return mLeft;
}
public int getmTop() {
return mTop;
}
public int getmRight() {
return mRight;
}
public int getmBottom() {
return mBottom;
}
}

View File

@ -1,99 +0,0 @@
package com.gh.common.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
import com.gh.gamecenter.R;
/**
* Created by LGT on 2016/9/9.
*/
public class CardRelativeLayout extends RelativeLayout {
private Drawable topDrawable, bottomDrawable;
private Drawable leftTopDrawable, rightTopDrawable, leftBottomDrawable, rightBottomDrawable;
private int mLeft, mTop, mRight, mBottom;
public CardRelativeLayout(Context context) {
this(context, null);
}
public CardRelativeLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CardRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
setWillNotDraw(false);
topDrawable = getContext().getResources().getDrawable(R.drawable.frame_top);
bottomDrawable = getContext().getResources().getDrawable(R.drawable.frame_bottom);
leftTopDrawable = getContext().getResources().getDrawable(R.drawable.frame_left_top_square);
rightTopDrawable = getContext().getResources().getDrawable(R.drawable.frame_right_top_square);
leftBottomDrawable = getContext().getResources().getDrawable(R.drawable.frame_left_bottom_square);
rightBottomDrawable = getContext().getResources().getDrawable(R.drawable.frame_right_bottom_square);
if (attrs != null) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CardLayout);
mLeft = ta.getDimensionPixelSize(R.styleable.CardLayout_left, 0);
mTop = ta.getDimensionPixelSize(R.styleable.CardLayout_top, 0);
mRight = ta.getDimensionPixelSize(R.styleable.CardLayout_right, 0);
mBottom = ta.getDimensionPixelSize(R.styleable.CardLayout_bottom, 0);
ta.recycle();
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mTop != 0) {
if (leftBottomDrawable != null) {
leftBottomDrawable.setBounds(0, 0, mLeft, mTop);
leftBottomDrawable.draw(canvas);
}
if (bottomDrawable != null) {
bottomDrawable.setBounds(mLeft, 0, getWidth() - mRight, mTop);
bottomDrawable.draw(canvas);
}
if (rightBottomDrawable != null) {
rightBottomDrawable.setBounds(getWidth() - mRight, 0, getWidth(), mTop);
rightBottomDrawable.draw(canvas);
}
}
if (mBottom != 0) {
if (leftTopDrawable != null) {
leftTopDrawable.setBounds(0, getHeight() - mBottom, mLeft, getHeight());
leftTopDrawable.draw(canvas);
}
if (topDrawable != null) {
topDrawable.setBounds(mLeft, getHeight() - mBottom, getWidth() - mRight, getHeight());
topDrawable.draw(canvas);
}
if (rightTopDrawable != null) {
rightTopDrawable.setBounds(getWidth() - mRight, getHeight() - mBottom, getWidth(), getHeight());
rightTopDrawable.draw(canvas);
}
}
}
public void setmBottom(int mBottom) {
this.mBottom = mBottom;
}
public void setmTop(int mTop) {
this.mTop = mTop;
}
}

View File

@ -32,7 +32,7 @@ public class Concern_LinearLayout extends LinearLayout {
if (concern_rv_recommend.getHeight() < height) {
postDelayed(show, 10);
} else {
concern_iv_delete.setImageResource(R.drawable.concern_down);
concern_iv_delete.setImageResource(R.drawable.concern_delete);
}
}
};
@ -52,7 +52,7 @@ public class Concern_LinearLayout extends LinearLayout {
postDelayed(hide, 10);
} else {
concern_rv_recommend.setVisibility(View.GONE);
concern_iv_delete.setImageResource(R.drawable.concern_up);
concern_iv_delete.setImageResource(R.drawable.concern_arrow);
}
}
};

View File

@ -58,25 +58,19 @@ public class CropImageCustom extends RelativeLayout {
return mZoomImageView.clip();
}
public boolean savePicture(String path) {
public void savePicture(String path) {
Bitmap bitmap = mZoomImageView.clip();
File file = new File(path);
int quality = 80;
do {
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
bos.flush();
bos.close();
} catch (IOException e) {
file.delete();
e.printStackTrace();
return false;
}
quality -= 10;
} while (file.length() > 81920);
return true;
try {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
} catch (IOException e) {
file.delete();
e.printStackTrace();
}
}
public ImageView getCropImageZoomView() {

File diff suppressed because it is too large Load Diff

View File

@ -6,31 +6,32 @@ import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.RelativeLayout;
public class Gh_RelativeLayout extends RelativeLayout {
public class Gh_ImageLayout extends RelativeLayout {
private GestureDetector mGestureDetector;
private OnSingleTapListener listener;
public Gh_RelativeLayout(Context context) {
public Gh_ImageLayout(Context context) {
this(context, null);
}
public Gh_RelativeLayout(Context context, AttributeSet attrs) {
public Gh_ImageLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context,
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
if (listener != null) {
listener.onSingleTap();
}
return super.onSingleTapUp(e);
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
if (listener != null) {
listener.onSingleTap();
}
return super.onSingleTapUp(e);
}
});
});
}
public void setOnSingleTapListener(OnSingleTapListener listener) {

View File

@ -0,0 +1,105 @@
package com.gh.common.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import com.gh.common.util.DisplayUtils;
import com.gh.gamecenter.R;
import com.gh.gamecenter.eventbus.EBShowDone;
import de.greenrobot.event.EventBus;
public class Gh_LinearLayout extends LinearLayout {
private LinearLayout dm_item, dm_item_ll_delete;
private int height;
private int total;
private int distance;
private boolean isSliding;
public boolean isSliding() {
return isSliding;
}
private int position;
Runnable show = new Runnable() {
@Override
public void run() {
LayoutParams lparams = new LayoutParams(
LayoutParams.MATCH_PARENT, height);
lparams.height = dm_item.getHeight() + distance;
if (lparams.height > total) {
lparams.height = total;
}
dm_item.setLayoutParams(lparams);
invalidate();
if (dm_item.getHeight() < total) {
postDelayed(show, 10);
} else {
isSliding = false;
EventBus.getDefault().post(new EBShowDone("下载管理", position));
}
}
};
Runnable hide = new Runnable() {
@Override
public void run() {
LayoutParams lparams = new LayoutParams(
LayoutParams.MATCH_PARENT, height);
lparams.height = dm_item.getHeight() - distance;
if (lparams.height < height) {
lparams.height = height;
}
dm_item.setLayoutParams(lparams);
invalidate();
if (dm_item.getHeight() > height) {
postDelayed(hide, 10);
} else {
dm_item_ll_delete.setVisibility(View.GONE);
isSliding = false;
}
}
};
public Gh_LinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
height = DisplayUtils.dip2px(getContext(), 66);
total = DisplayUtils.dip2px(getContext(), 96);
distance = DisplayUtils.dip2px(getContext(), 3);
isSliding = false;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
dm_item = (LinearLayout) findViewById(R.id.dm_item);
dm_item_ll_delete = (LinearLayout) findViewById(R.id.dm_item_ll_delete);
}
public void showDeleteView(int position) {
this.position = position;
isSliding = true;
dm_item_ll_delete.setVisibility(View.VISIBLE);
removeCallbacks(hide);
post(show);
getHandler();
}
public void hideDeleteView() {
isSliding = true;
removeCallbacks(show);
post(hide);
}
}

View File

@ -5,56 +5,25 @@ import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import com.gh.gamecenter.eventbus.EBReuse;
import de.greenrobot.event.EventBus;
public class Gh_ViewPager extends ViewPager {
private boolean mChildIsBeingDragged=false;//当前子控件是否处理拖动状态
public Gh_ViewPager(Context context) {
this(context, null);
}
public Gh_ViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
EventBus.getDefault().register(this);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
// for (int i = 0; i < getChildCount(); i++) {
// getChildAt(i).dispatchTouchEvent(event);
// }
for (int i = 0; i < getChildCount(); i++) {
getChildAt(i).dispatchTouchEvent(event);
}
return super.dispatchTouchEvent(event);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if(mChildIsBeingDragged){
return false;
}
//指针索引超出范围异常
try {
return super.onInterceptTouchEvent(ev);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
}
}
public void onEvent(EBReuse reuse) {
if ("isStopMove".equals(reuse.getType())) {
mChildIsBeingDragged = false;
}
if ("isStartove".equals(reuse.getType())){
mChildIsBeingDragged = true;
}
}
public void onDestory (){
EventBus.getDefault().unregister(this);
}
}

View File

@ -1,7 +1,6 @@
package com.gh.common.view;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
@ -17,7 +16,7 @@ public class HorizontalItemDecoration extends RecyclerView.ItemDecoration {
public HorizontalItemDecoration(Context context, int interval, int size) {
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setColor(0xffffffff);
mInterval = DisplayUtils.dip2px(context, interval);
mSize = size;
}

View File

@ -0,0 +1,38 @@
package com.gh.common.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
public class KeyboardLayout extends RelativeLayout {
private OnKeyboardChangedListener mListener;
public KeyboardLayout(Context context) {
super(context);
}
public KeyboardLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mListener != null) {
mListener.OnKeyboardChanged(w, h, oldw, oldh);
}
}
public interface OnKeyboardChangedListener {
void OnKeyboardChanged(int w, int h, int oldw, int oldh);
}
public void setOnKeyboardChangedListener(OnKeyboardChangedListener listener) {
this.mListener = listener;
}
}

View File

@ -0,0 +1,91 @@
package com.gh.common.view;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import com.gh.common.util.DisplayUtils;
import com.gh.gamecenter.R;
import com.gh.gamecenter.eventbus.EBShowDone;
import de.greenrobot.event.EventBus;
public class MyGame_LinearLayout extends LinearLayout {
private LinearLayout mygame_ll;
private RecyclerView mygame_rv_show;
private int height;
private int distance;
private int total;
private int position;
Runnable show = new Runnable() {
@Override
public void run() {
LayoutParams lparams = new LayoutParams(
LayoutParams.MATCH_PARENT, height);
lparams.height = mygame_ll.getHeight() + distance;
if (lparams.height > total) {
lparams.height = total;
}
mygame_ll.setLayoutParams(lparams);
invalidate();
if (lparams.height < total) {
postDelayed(show, 10);
} else {
EventBus.getDefault().post(new EBShowDone("我的游戏", position));
}
}
};
Runnable hide = new Runnable() {
@Override
public void run() {
LayoutParams lparams = new LayoutParams(
LayoutParams.MATCH_PARENT, height);
lparams.height = mygame_ll.getHeight() - distance;
if (lparams.height < height) {
lparams.height = height;
}
mygame_ll.setLayoutParams(lparams);
invalidate();
if (lparams.height > height) {
postDelayed(hide, 10);
} else {
mygame_rv_show.setVisibility(View.GONE);
}
}
};
public MyGame_LinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
height = DisplayUtils.dip2px(getContext(), 66);
distance = DisplayUtils.dip2px(getContext(), 5);
total = DisplayUtils.dip2px(getContext(), 136);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mygame_rv_show = (RecyclerView) findViewById(R.id.mygame_rv_show);
mygame_ll = (LinearLayout) findViewById(R.id.mygame_ll);
}
public void showRecyclerView(int position) {
this.position = position;
mygame_rv_show.setVisibility(View.VISIBLE);
removeCallbacks(hide);
post(show);
}
public void hideRecyclerView() {
removeCallbacks(show);
post(hide);
}
}

View File

@ -0,0 +1,48 @@
package com.gh.common.view;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
/**
* 重写RecyclerView 解决触摸事件
*
* @author 黄壮华
*
*/
public class MyRecyclerView extends RecyclerView {
public static boolean isCanMove = false;
public MyRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
private float xDis;
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
xDis = ev.getX();
break;
case MotionEvent.ACTION_MOVE:
if (isCanMove) {
if (xDis - ev.getX() > 0) {
MyViewPager.isCanMove = true;
return false;
} else if (xDis - ev.getX() < 0) {
isCanMove = false;
}
}
xDis = ev.getX();
break;
default:
break;
}
return super.dispatchTouchEvent(ev);
}
}

View File

@ -0,0 +1,60 @@
package com.gh.common.view;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
/**
* 重写ViewPager 解决触摸事件
*
* @author 黄壮华
*
*/
public class MyViewPager extends ViewPager {
public static boolean isCanMove = false;
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_MOVE:
if (isCanMove) {
return true;
}
break;
default:
break;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
isCanMove = false;
break;
case MotionEvent.ACTION_MOVE:
if (isCanMove) {
return onTouchEvent(ev);
}
break;
case MotionEvent.ACTION_UP:
if (isCanMove) {
return onTouchEvent(ev);
}
break;
default:
break;
}
return super.dispatchTouchEvent(ev);
}
}

View File

@ -1,44 +0,0 @@
package com.gh.common.view;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by LGT on 2016/10/11.
*/
public class RecyclerViewExtended extends RecyclerView {
public RecyclerViewExtended(Context context) {
super(context);
}
public RecyclerViewExtended(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RecyclerViewExtended(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private OnDispatchTouchListener mListener;
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mListener != null) {
mListener.onDispatch(this, ev);
}
return super.dispatchTouchEvent(ev);
}
public void setOnDispatchTouchListener(OnDispatchTouchListener listener) {
mListener = listener;
}
public interface OnDispatchTouchListener {
void onDispatch(View v, MotionEvent event);
}
}

View File

@ -17,7 +17,7 @@ public class VerticalItemDecoration extends RecyclerView.ItemDecoration {
public VerticalItemDecoration(Context context, int interval) {
paint = new Paint();
paint.setColor(context.getResources().getColor(R.color.background));
paint.setColor(context.getResources().getColor(R.color.bg_color));
mInterval = DisplayUtils.dip2px(context, interval);
}

View File

@ -1,279 +0,0 @@
package com.gh.common.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.net.Uri;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gh.gamecenter.eventbus.EBReuse;
import de.greenrobot.event.EventBus;
/**
* Created by khy on 2016/10/26.
*/
public class ZoomSimpleDraweeView extends SimpleDraweeView {
private ScaleGestureDetector mScaleDetector;
private GestureDetector mGestureDetector;
private float mCurrentScale = 1f;
private Matrix mCurrentMatrix;
private setOnSingleClickListener mClickListener;
private float imgagePro = -1; // 图片宽高比
public ZoomSimpleDraweeView(Context context) {
super(context);
init();
}
public ZoomSimpleDraweeView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ZoomSimpleDraweeView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
mCurrentMatrix = new Matrix();
ScaleGestureDetector.OnScaleGestureListener scaleListener = new ScaleGestureDetector
.SimpleOnScaleGestureListener() {
@Override
public boolean onScale(ScaleGestureDetector detector) {
float scaleFactor = detector.getScaleFactor();
if (mCurrentScale < 4f || detector.getScaleFactor() < 1f){
mCurrentScale *= scaleFactor;
mCurrentMatrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());
invalidate();
}
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
super.onScaleEnd(detector);
if (mCurrentScale < 1f) {
reset();
}
checkBorder();
}
};
mScaleDetector = new ScaleGestureDetector(getContext(), scaleListener);
GestureDetector.SimpleOnGestureListener gestureListener = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (mClickListener != null) {
mClickListener.onClick();
}
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (mCurrentScale > 1f) {
mCurrentMatrix.postTranslate(-distanceX, -distanceY);
invalidate();
checkBorder();
}
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
final float x = e.getX();
final float y = e.getY();
float scaleSize ; //扩大或缩小的倍数
if (mCurrentScale > 1.5f){ //缩小时直接回到原画大小
scaleSize = 0.5f;
ZoomSimpleDraweeView.this.post(new AutoScaleRunnable(mCurrentScale * scaleSize, getWidth() / 2f, getHeight() / 2f, false));
} else {
scaleSize = 2.0f;
ZoomSimpleDraweeView.this.post(new AutoScaleRunnable(mCurrentScale * scaleSize, x, y, true));
}
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return super.onSingleTapUp(e);
}
};
mGestureDetector = new GestureDetector(getContext(), gestureListener);
}
/**
* 检查图片边界是否移到view以内
* 目的是让图片边缘不要移动到view里面
*/
private void checkBorder() {
RectF rectF = getDisplayRect(mCurrentMatrix);
boolean reset = false;
float dx = 0;
float dy = 0;
if (rectF.left > 0) {
dx = getLeft() - rectF.left;
reset = true;
}
if (rectF.top > 0) {
dy = getTop() - rectF.top;
reset = true;
}
if (rectF.right < getRight()) {
dx = getRight() - rectF.right;
reset = true;
}
if (rectF.bottom < getHeight()) {
dy = getHeight() - rectF.bottom;
reset = true;
}
if (reset) {
mCurrentMatrix.postTranslate(dx, dy);
invalidate();
}
if (dy == 0 && reset || mCurrentScale == 1f){
EventBus.getDefault().post(new EBReuse("isStopMove"));
} else{
EventBus.getDefault().post(new EBReuse("isStartove"));
}
}
/**
* Helper method that maps the supplied Matrix to the current Drawable
*
* @param matrix - Matrix to map Drawable against
* @return RectF - Displayed Rectangle
*/
private RectF getDisplayRect(Matrix matrix) {
// int bottom;
// if (imgagePro != -1){
// bottom = (int) (getRight()*imgagePro);
// } else {
// bottom = getBottom();
// }
RectF rectF = new RectF(getLeft(), getTop(), getRight(), getBottom());
matrix.mapRect(rectF);
return rectF;
}
@Override
public void setImageURI(Uri uri) {
reset();
super.setImageURI(uri);
}
@Override
protected void onDraw(Canvas canvas) {
int saveCount = canvas.save();
canvas.concat(mCurrentMatrix);
super.onDraw(canvas);
canvas.restoreToCount(saveCount);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
if (!mScaleDetector.isInProgress()) {
mGestureDetector.onTouchEvent(event);
}
return true;
}
/**
* 重置图片
*/
public void reset() {
mCurrentMatrix.reset();
mCurrentScale = 1f;
invalidate();
EventBus.getDefault().post(new EBReuse("isStopMove"));
}
private final float[] matrixValues = new float[9];
public final float getScale() {
mCurrentMatrix.getValues(matrixValues);
return matrixValues[Matrix.MSCALE_X];
}
/**
* 自动缩放的任务
*/
private class AutoScaleRunnable implements Runnable {
static final float BIGGER = 1.07f;
static final float SMALLER = 0.96f;
private float mTargetScale;
private boolean isExp;
/**
* 缩放的中心
*/
private float x;
private float y;
/**
* @param isExp :判断是否是放大
*/
public AutoScaleRunnable(float targetScale, float x, float y, boolean isExp) {
this.mTargetScale = targetScale;
this.x = x;
this.y = y;
this.isExp = isExp;
}
@Override
public void run() {
if (isExp){ //放大
mCurrentMatrix.postScale(BIGGER, BIGGER, x, y);
invalidate();
if (mCurrentScale < mTargetScale && mCurrentScale <= 4) {
ZoomSimpleDraweeView.this.postDelayed(this, 10);
mCurrentScale = mCurrentScale * BIGGER;
} else {
checkBorder();
mCurrentScale = getScale();
}
}else {//缩小
mCurrentMatrix.postScale(SMALLER, SMALLER, x, y);
invalidate();
checkBorder();
if (getScale() > 1.01) {
ZoomSimpleDraweeView.this.postDelayed(this, 1);
mCurrentScale = mCurrentScale * SMALLER;
} else {
reset();
}
}
}
}
//图片宽高比例
public void setImagePro (float imgPro){
this.imgagePro = imgPro;
}
public void setOnSingleClickListener(setOnSingleClickListener listener) {
mClickListener = listener;
}
public interface setOnSingleClickListener {
void onClick();
}
}

View File

@ -2,48 +2,51 @@ package com.gh.download;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.gh.common.util.Utils;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
public class DBHelper extends OrmLiteSqliteOpenHelper {
public class DBHelper extends OrmLiteSqliteOpenHelper
{
private static final String DB_NAME = "gh_download.db";
private static final int VERSION = 3;
/**
* downloadDao ,每张表对应一个
*/
private Dao<DownloadEntity, String> downloadDao;
private Dao<DownloadEntry, String> downloadDao;
private DBHelper(Context context) {
private DBHelper(Context context)
{
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource)
{
try {
Utils.log("ormlite_test", "onCreate ====================");
TableUtils.createTable(connectionSource, DownloadEntity.class);
Log.v("ormlite_test", "onCreate ====================");
TableUtils.createTable(connectionSource, DownloadEntry.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase database,
ConnectionSource connectionSource,
int oldVersion,
int newVersion) {
public void onUpgrade(SQLiteDatabase database,
ConnectionSource connectionSource, int oldVersion, int newVersion)
{
try {
TableUtils.dropTable(connectionSource, DownloadEntity.class, true);
onCreate(database, connectionSource);
TableUtils.dropTable(connectionSource, DownloadEntry.class, true);
onCreate(database, connectionSource);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
}
private static DBHelper mInstance;
@ -54,22 +57,25 @@ public class DBHelper extends OrmLiteSqliteOpenHelper {
* @param context
* @return
*/
public static synchronized DBHelper getInstance(Context context) {
public static synchronized DBHelper getInstance(Context context)
{
context = context.getApplicationContext();
if (mInstance == null) {
synchronized (DBHelper.class) {
if (mInstance == null) {
mInstance = new DBHelper(context);
}
}
}
if (mInstance == null)
{
synchronized (DBHelper.class)
{
if (mInstance == null)
mInstance = new DBHelper(context);
}
}
return mInstance;
}
public Dao<DownloadEntity, String> getDownloadDao() {
public Dao<DownloadEntry, String> getDownloadDao(){
try {
if (downloadDao == null) {
downloadDao = getDao(DownloadEntity.class);
if(downloadDao == null){
downloadDao = getDao(DownloadEntry.class);
}
} catch (java.sql.SQLException e) {
e.printStackTrace();
@ -81,9 +87,10 @@ public class DBHelper extends OrmLiteSqliteOpenHelper {
* 释放资源
*/
@Override
public void close() {
public void close()
{
super.close();
downloadDao= null;
}
}
}

View File

@ -1,57 +1,81 @@
package com.gh.download;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
public class DataChanger extends Observable {
public class DataChanger extends Observable{
private HashMap<String, DownloadTask> mDownloadingTasks;//当前正在下载的任务队列
private HashMap<String, DownloadEntry> mDownloadEntries;//包含所有下载任务的任务队列
private static DataChanger mInstance;
public static DataChanger getInstance() {
private DataChanger() {
mDownloadingTasks = new HashMap<String, DownloadTask>();
mDownloadEntries = new HashMap<String, DownloadEntry>();
}
public static DataChanger getInstance(){
if(mInstance == null){
mInstance = new DataChanger();
}
return mInstance;
}
private final Map<String, DownloadTask> mDownloadingTasks;//当前正在下载的任务队列
private final Map<String, DownloadEntity> mDownloadEntries;//包含所有下载任务的任务队列
private DataChanger() {
mDownloadingTasks = Collections.synchronizedMap(new HashMap<String, DownloadTask>());
mDownloadEntries = Collections.synchronizedMap(new HashMap<String, DownloadEntity>());
public HashMap<String, DownloadTask> getDownloadingTasks() {
return mDownloadingTasks;
}
public Map<String, DownloadTask> getDownloadingTasks() {
synchronized (mDownloadingTasks) {
return mDownloadingTasks;
}
public HashMap<String, DownloadEntry> getDownloadEntries() {
return mDownloadEntries;
}
public Map<String, DownloadEntity> getDownloadEntries() {
synchronized (mDownloadEntries) {
return mDownloadEntries;
}
public void addToDownloadEntries(DownloadEntry entry) {
mDownloadEntries.put(entry.getUrl(), entry);
}
public synchronized void notifyDataChanged(DownloadEntity entry) {
if (entry != null) {
if (getDownloadEntries().get(entry.getUrl()) != null) {
getDownloadEntries().put(entry.getUrl(), entry);
public int getDownloadingSize() {
return mDownloadingTasks.size();
}
public synchronized void notifyDataChanged(DownloadEntry entry) {
if(entry != null){
if(mDownloadEntries.get(entry.getUrl()) != null){
mDownloadEntries.put(entry.getUrl(), entry);
setChanged();
notifyObservers();
}
setChanged();
notifyObservers(entry);
}
}
public synchronized void pauseDownloadingTasks(String url) {
DownloadTask downloadTask = getDownloadingTasks().remove(url);
if (downloadTask != null) {
public void addToDownloadingTask(String url, DownloadTask task) {
mDownloadingTasks.put(url, task);
}
public void removeDownloadingTask(String url) {
getDownloadingTasks().remove(url);
}
public void removeDownloadEntry(String url) {
getDownloadEntries().remove(url);
}
public void pauseDownloadingTasks(String url) {
DownloadTask downloadTask = getDownloadingTasks().get(url);
if(downloadTask != null){
downloadTask.pause();
removeDownloadingTask(url);
}
pauseDownloadEntries(url);
}
public void pauseDownloadEntries(String url) {
DownloadEntry entry = getDownloadEntries().get(url);
if(entry != null){
entry.setStatus(DownloadStatus.pause);
}
}
}

View File

@ -1,5 +1,6 @@
package com.gh.download;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;
@ -8,11 +9,10 @@ public abstract class DataWatcher implements Observer{
@Override
public void update(Observable observable, Object data) {
if (data != null && data instanceof DownloadEntity) {
onDataChanged((DownloadEntity) data);
}
onDataChanged(DataChanger.getInstance().getDownloadEntries());
}
public abstract void onDataChanged(DownloadEntity downloadEntity);
public abstract void onDataChanged(HashMap<String, DownloadEntry> downloadingEntries);
}

View File

@ -8,8 +8,7 @@ import com.j256.ormlite.dao.Dao;
import java.util.List;
public class DownloadDao {
private static Dao<DownloadEntity, String> downloadDaoOpe;
private static Dao<DownloadEntry, String> downloadDaoOpe;
private static DBHelper helper;
private static DownloadDao mInstance;
@ -38,7 +37,7 @@ public class DownloadDao {
return mInstance;
}
public void newOrUpdate(DownloadEntity entry) {
public void newOrUpdate(DownloadEntry entry) {
try {
if (DownloadStatus.cancel.equals(entry.getStatus())) {
downloadDaoOpe.delete(entry);
@ -50,17 +49,18 @@ public class DownloadDao {
}
}
public DownloadEntity get(String url) {
public DownloadEntry get(String url) {
try {
return downloadDaoOpe.queryForId(url);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
return null;
}
public List<DownloadEntity> getAll() {
List<DownloadEntity> list = null;
public List<DownloadEntry> getAll() {
List<DownloadEntry> list = null;
try {
list = downloadDaoOpe.queryForAll();
} catch (java.sql.SQLException e) {
@ -75,6 +75,6 @@ public class DownloadDao {
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
}
}

View File

@ -1,351 +0,0 @@
package com.gh.download;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import java.io.Serializable;
import java.util.HashMap;
@DatabaseTable(tableName = "download")
public class DownloadEntity implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@DatabaseField(id = true, columnName="url")
private String url;
@DatabaseField(columnName="name")
private String name;
@DatabaseField(columnName="status")
private DownloadStatus status;
@DatabaseField(columnName="path")
private String path;
@DatabaseField(columnName="progress")
private long progress;
@DatabaseField(columnName="size")
private long size;
@DatabaseField(columnName="percent")
private double percent;
@DatabaseField(columnName="speed")
private long speed;
@DatabaseField(columnName="meta", dataType=DataType.SERIALIZABLE)
private HashMap<String, String> meta;//其他
public String getGameId() {
if (meta != null) {
return meta.get("gameId");
}
return null;
}
public void setGameId(String gameId) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("gameId", gameId);
}
public String getPackageName() {
if (meta != null) {
return meta.get("packageName");
}
return null;
}
public void setPackageName(String packageName) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("packageName", packageName);
}
public String getETag() {
if (meta != null) {
return meta.get("ETag");
}
return null;
}
public void setETag(String ETag) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("ETag", ETag);
}
public boolean isUpdate() {
if (meta != null) {
if ("true".equals(meta.get("isUpdate"))) {
return true;
}
}
return false;
}
public void setUpdate(boolean update) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("isUpdate", String.valueOf(update));
}
public boolean isPlugin() {
if (meta != null) {
if ("true".equals(meta.get("isPlugin"))) {
return true;
}
}
return false;
}
public void setPlugin(boolean plugin) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("isPlugin", String.valueOf(plugin));
}
public boolean isPluggable() {
if (meta != null) {
if ("true".equals(meta.get("isPluggable"))) {
return true;
}
}
return false;
}
public void setPluggable(boolean pluggable) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("isPluggable", String.valueOf(pluggable));
}
public boolean isReset() {
if (meta != null) {
if ("true".equals(meta.get("isReset"))) {
return true;
}
}
return false;
}
public void setReset(boolean reset) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("isReset", String.valueOf(reset));
}
public String getPlatform() {
if (meta != null) {
return meta.get("platform");
}
return null;
}
public void setPlatform(String platform) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("platform", platform);
}
public String getIcon() {
if (meta != null) {
return meta.get("icon");
}
return null;
}
public void setIcon(String icon) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("icon", icon);
}
public String getEntrance() {
if (meta != null) {
return meta.get("entrance");
}
return null;
}
public void setEntrance(String entrance) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("entrance", entrance);
}
public String getLocation() {
if (meta != null) {
return meta.get("location");
}
return null;
}
public void setLocation(String location) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("location", location);
}
public long getSpeed() {
return speed;
}
public void setSpeed(long speed) {
this.speed = speed;
}
public String getError() {
if (meta != null) {
return meta.get("error");
}
return null;
}
public void setError(String error) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("error", error);
}
public long getStart() {
if (meta != null) {
String start = meta.get("start");
if (start == null) {
return 0;
}
return Long.valueOf(start);
}
return 0;
}
public void setStart(long start) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("start", String.valueOf(start));
}
public long getEnd() {
if (meta != null) {
String end = meta.get("end");
if (end == null) {
return 0;
}
return Long.valueOf(end);
}
return 0;
}
public void setEnd(long end) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("end", String.valueOf(end));
}
public long getInstalled() {
if (meta != null) {
String installed = meta.get("installed");
if (installed == null) {
return 0;
}
return Integer.valueOf(installed);
}
return 0;
}
public void setInstalled(int installed) {
if (meta == null) {
meta = new HashMap<>();
}
meta.put("installed", String.valueOf(installed));
}
public HashMap<String, String> getMeta() {
return meta;
}
public void setMeta(HashMap<String, String> meta) {
if (this.meta != null) {
this.meta.putAll(meta);
} else {
this.meta = meta;
}
}
public double getPercent() {
return percent;
}
public void setPercent(double percent) {
this.percent = percent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DownloadStatus getStatus() {
return status;
}
public void setStatus(DownloadStatus status) {
this.status = status;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public long getProgress() {
return progress;
}
public void setProgress(long progress) {
this.progress = progress;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
}

View File

@ -0,0 +1,144 @@
package com.gh.download;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map.Entry;
@DatabaseTable(tableName = "download")
public class DownloadEntry implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@DatabaseField(id = true,columnName="url")
private String url;
// @DatabaseField(columnName="id")
// private String id;
@DatabaseField(columnName="name")
private String name;
@DatabaseField(columnName="status")
private DownloadStatus status;
@DatabaseField(columnName="path")
private String path;
@DatabaseField(columnName="progress")
private long progress;
@DatabaseField(columnName="size")
private long size;
@DatabaseField(columnName="percent")
private double percent;
@DatabaseField(columnName="speed")
private long speed;
@DatabaseField(columnName="meta", dataType=DataType.SERIALIZABLE)
private HashMap<String, String> meta;//其他
public long getSpeed() {
return speed;
}
public void setSpeed(long speed) {
this.speed = speed;
}
public HashMap<String, String> getMeta() {
return meta;
}
public void setMeta(HashMap<String, String> meta) {
this.meta = meta;
}
public double getPercent() {
return percent;
}
public void setPercent(double percent) {
this.percent = percent;
}
// public String getId() {
// return id;
// }
// public void setId(String id) {
// this.id = id;
// }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DownloadStatus getStatus() {
return status;
}
public void setStatus(DownloadStatus status) {
this.status = status;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public long getProgress() {
return progress;
}
public void setProgress(long progress) {
this.progress = progress;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
@Override
public String toString() {
StringBuilder metas = new StringBuilder();
metas.append("(");
int i = 1;
if(meta != null){
for (Entry<String, String> entry : meta.entrySet()) {
metas.append(entry.getKey());
metas.append(":");
metas.append(entry.getValue());
if(i != meta.size()){
metas.append(",");
}
}
}
metas.append(")");
return "["
+ name + "==="
+ url + "==="
+ path + "==="
+ status + "==="
+ progress + "==="
+ size + "==="
+ percent + "%==="
+ speed + "k/s==="
+ metas +
"]";
}
}

View File

@ -6,11 +6,11 @@ package com.gh.download;
* @version create timeSep 23, 2014 5:52:11 PM
*/
public interface DownloadListener {
/**
* 更新每一次下载的大小
* @param downloadedSize
*/
// void onProgressChanged(int downloadedSize);
void onProgressChanged(long length, int downloadedSize);
/**
@ -19,10 +19,5 @@ public interface DownloadListener {
*/
void onStatusChanged(DownloadStatus status);
/**
* 更新任务下载状态
* @param status
*/
void onStatusChanged(DownloadStatus status, String error);
}

View File

@ -9,38 +9,22 @@ import android.widget.Toast;
import com.gh.common.constant.Constants;
import com.gh.common.util.FileUtils;
import com.gh.common.util.MD5Utils;
import com.gh.common.util.Utils;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.manager.PackageManager;
import com.gh.common.util.Trace;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.LinkedBlockingQueue;
public class DownloadManager {
private static DownloadManager mInstance;
private Context context;
private Handler handler;
private Handler handler;
private ArrayMap<String, Long> lastTimeMap;
private ArrayMap<String, LinkedBlockingQueue<String>> platformMap;
private ArrayMap<String, ArrayMap<String, DownloadEntity>> gameMap;
private ArrayMap<String, String> statusMap;
private DownloadManager(Context context) {
this.context = context;
lastTimeMap = new ArrayMap<>();
platformMap = new ArrayMap<>();
gameMap = new ArrayMap<>();
statusMap = new ArrayMap<>();
lastTimeMap = new ArrayMap<String, Long>();
handler = new Handler(context.getMainLooper()){
@Override
public void handleMessage(Message msg) {
@ -54,70 +38,16 @@ public class DownloadManager {
if (System.currentTimeMillis() - lastTimeMap.get(url) >= 1000) {
pause(url);
}
} else if (msg.what == Constants.DOWNLOAD_ROLL) {
String name = (String) msg.obj;
LinkedBlockingQueue<String> queue = platformMap.get(name);
if (queue.size() > 1) {
queue.offer(queue.poll());
Message message = Message.obtain();
message.obj = name;
message.what = Constants.DOWNLOAD_ROLL;
sendMessageDelayed(message, 3000);
}
}
}
};
context.startService(new Intent(context, DownloadService.class));
}
public void put(String url, long time) {
lastTimeMap.put(url, time);
}
public void putQueue(String name, LinkedBlockingQueue<String> queue) {
platformMap.put(name, queue);
}
public LinkedBlockingQueue<String> getQueue(String name) {
return platformMap.get(name);
}
public void removePlatform(String name, String platform) {
LinkedBlockingQueue<String> queue = platformMap.get(name);
if (queue != null) {
queue.remove(platform);
platformMap.put(name, queue);
}
}
public void initGameMap() {
gameMap.clear();
List<DownloadEntity> list = getAll();
if (list != null && list.size() != 0) {
String name;
for (DownloadEntity downloadEntity : list) {
name = downloadEntity.getName();
ArrayMap<String, DownloadEntity> map = gameMap.get(name);
if (map == null) {
map = new ArrayMap<>();
gameMap.put(name, map);
}
map.put(downloadEntity.getPlatform(), downloadEntity);
}
}
}
public ArrayMap<String, DownloadEntity> getEntryMap(String name) {
return gameMap.get(name);
}
public void putStatus(String url, String status) {
statusMap.put(url, status);
}
public String getStatus(String url) {
return statusMap.get(url);
}
public void sendMessageDelayed(Message msg, long delayMillis) {
handler.sendMessageDelayed(msg, delayMillis);
}
@ -129,7 +59,7 @@ public class DownloadManager {
return mInstance;
}
private Intent getIntent(DownloadEntity entry, DownloadStatus status) {
private Intent getIntent(DownloadEntry entry, DownloadStatus status) {
Intent service = new Intent(context, DownloadService.class);
service.putExtra(Constants.KEY_DOWNLOAD_ENTRY, entry);
service.putExtra(Constants.KEY_DOWNLOAD_ACTION, status.name());
@ -139,15 +69,18 @@ public class DownloadManager {
/**
* 根据url到本地sqlite数据库中查找并获取该文件的保存路径 并检查改路径下文件是否存在,不存在则删除该条无效记录
*
* @param url 下载任务的标识url
* @param url
* 下载任务的标识url
*/
private boolean checkDownloadEntryRecordValidate(String url) {
DownloadEntity entry = get(url);
DownloadEntry entry = get(url);
if (entry != null && ((int)entry.getPercent()) != 0) {
File file = new File(entry.getPath());
if (!file.exists()) {
DownloadDao.getInstance(context).delete(url);
Utils.log(DownloadManager.class.getSimpleName(), "文件不存在,删除该条无效数据库记录!");
Trace.getInstance().debug(
DownloadManager.class.getSimpleName(),
"文件不存在,删除该条无效数据库记录!");
return true;
}
}
@ -161,11 +94,12 @@ public class DownloadManager {
* @return
*/
public boolean isFileCompleted(String url) {
DownloadEntity entry = get(url);
DownloadEntry entry = get(url);
if (entry != null) {
if (entry.getPercent() == 100) {
Utils.log(DownloadManager.class.getSimpleName(), "文件已经下载完成!");
Trace.getInstance().debug(
DownloadManager.class.getSimpleName(), "文件已经下载完成!");
return true;
}
}
@ -175,7 +109,8 @@ public class DownloadManager {
public boolean isTaskDownloading(String url) {
if (DataChanger.getInstance().getDownloadingTasks().get(url) != null) {
Utils.log(DownloadManager.class.getSimpleName(), url + "正在下载!");
Trace.getInstance().debug(DownloadManager.class.getSimpleName(),
url + "正在下载!");
return true;
}
return false;
@ -184,63 +119,17 @@ public class DownloadManager {
/**
* 添加一个下载任务
*
* @param downloadEntity
* @param entry
*/
public void add(DownloadEntity downloadEntity) {
if (downloadEntity != null) {
String url = downloadEntity.getUrl();
public void add(DownloadEntry entry) {
if (entry != null) {
String url = entry.getUrl();
checkDownloadEntryRecordValidate(url);
if (isFileCompleted(url)) {
downloadEntity.setStatus(DownloadStatus.done);
DataChanger.getInstance().notifyDataChanged(downloadEntity);
} else if (!isTaskDownloading(url)) {
context.startService(getIntent(downloadEntity, DownloadStatus.add));
if (!isFileCompleted(url) && !isTaskDownloading(url)) {
context.startService(getIntent(entry, DownloadStatus.add));
}
}
Utils.log(DownloadManager.class.getSimpleName(), "add");
}
public static void createDownload(Context context,
GameEntity gameEntity,
String method,
String entrance,
String location) {
createDownload(context, gameEntity.getApk().get(0), gameEntity, method, entrance, location);
}
public static void createDownload(Context context,
ApkEntity apkEntity,
GameEntity gameEntity,
String method,
String entrance,
String location) {
DownloadEntity downloadEntity = new DownloadEntity();
downloadEntity.setUrl(apkEntity.getUrl());
downloadEntity.setName(gameEntity.getName());
downloadEntity.setPath(FileUtils.getDownloadPath(context,
MD5Utils.getContentMD5(gameEntity.getName() + "_" + System.currentTimeMillis()) + ".apk"));
downloadEntity.setETag(apkEntity.getEtag());
downloadEntity.setIcon(gameEntity.getIcon());
downloadEntity.setPlatform(apkEntity.getPlatform());
downloadEntity.setPackageName(apkEntity.getPackageName());
downloadEntity.setGameId(gameEntity.getId());
downloadEntity.setEntrance(entrance);
downloadEntity.setLocation(location);
int installed = 0;
for (ApkEntity apk : gameEntity.getApk()) {
if (PackageManager.isInstalled(apk.getPackageName())) {
installed++;
}
}
downloadEntity.setInstalled(installed);
if (method.equals("更新")) {
downloadEntity.setUpdate(true);
} else if (method.equals("插件化")) {
downloadEntity.setPluggable(true);
}
downloadEntity.setPlugin(gameEntity.getTag() != null && gameEntity.getTag().size() != 0);
DownloadManager.getInstance(context.getApplicationContext()).add(downloadEntity);
Trace.getInstance().debug(DownloadManager.class.getSimpleName(), "add");
}
/**
@ -250,12 +139,13 @@ public class DownloadManager {
*/
public void pause(String url) {
checkDownloadEntryRecordValidate(url);
DownloadEntity entry = DataChanger.getInstance().getDownloadEntries()
DownloadEntry entry = DataChanger.getInstance().getDownloadEntries()
.get(url);
if (entry != null) {
context.startService(getIntent(entry, DownloadStatus.pause));
}
Utils.log(DownloadManager.class.getSimpleName(), "pause");
Trace.getInstance().debug(DownloadManager.class.getSimpleName(),
"pause");
}
/**
@ -264,7 +154,7 @@ public class DownloadManager {
* @param url
*/
public void resume(String url) {
DownloadEntity entry = get(url);
DownloadEntry entry = get(url);
// 暂停任务后,把文件删除,然后点继续,文件不存在,需要重新加入下载队列进行下载
if (checkDownloadEntryRecordValidate(url)) {
@ -273,143 +163,121 @@ public class DownloadManager {
add(entry);
} else {
if (entry != null) {
if (isFileCompleted(url)) {
entry.setStatus(DownloadStatus.done);
DataChanger.getInstance().notifyDataChanged(entry);
} else if (!isTaskDownloading(url)) {
if (!isFileCompleted(url) && !isTaskDownloading(url)) {
context.startService(getIntent(entry, DownloadStatus.resume));
}
}
}
Utils.log(DownloadManager.class.getSimpleName(), "resume");
Trace.getInstance().debug(DownloadManager.class.getSimpleName(),
"resume");
}
/**
* 根据url取消下载并删除已下载的文件
*
* @param url
* @param id
*/
public void cancel(String url) {
cancel(url, true);
}
public void cancel(String url, boolean isDeleteFile) {
DownloadEntity entry = DownloadDao.getInstance(context).get(url);
if (entry != null) {
DownloadEntry temp = DownloadDao.getInstance(context).get(url);
if (temp != null) {
if (isDeleteFile) {
FileUtils.deleteFile(entry.getPath());
FileUtils.deleteFile(temp.getPath());
}
DownloadDao.getInstance(context).delete(url);
Utils.log(DownloadManager.class.getSimpleName(), "cancle==>file and record were deleted!");
Trace.getInstance().debug(DownloadManager.class.getSimpleName(),
"cancle==>file and record were deleted!");
}
DownloadEntry entry = DataChanger.getInstance().getDownloadEntries()
.get(url);
if (entry != null) {
entry.setStatus(DownloadStatus.cancel);
context.startService(getIntent(entry, DownloadStatus.cancel));
Utils.log(DownloadManager.class.getSimpleName(), "cancel");
Trace.getInstance().debug(DownloadManager.class.getSimpleName(),
"cancel");
}
}
/**
* 取消并删除所有下载任务(包括下载中、等待、暂停状态的任务)
*/
public void cancleAll() {
for (Entry<String, DownloadEntity> entry : DataChanger.getInstance()
for (Entry<String, DownloadEntry> entry : DataChanger.getInstance()
.getDownloadEntries().entrySet()) {
cancel(entry.getValue().getUrl(), true);
}
Utils.log(DownloadManager.class.getSimpleName(), "cancel all");
Trace.getInstance().debug(DownloadManager.class.getSimpleName(),
"cancel all");
}
/**
* 开始所有下载任务
*/
public void startAll() {
for (Entry<String, DownloadEntity> entry : DataChanger.getInstance()
for (Entry<String, DownloadEntry> entry : DataChanger.getInstance()
.getDownloadEntries().entrySet()) {
add(entry.getValue());
}
Utils.log(DownloadManager.class.getSimpleName(), "start all");
Trace.getInstance().debug(DownloadManager.class.getSimpleName(),
"start all");
}
/**
* 暂停所有正在下载的任务
*/
public void pauseAll() {
for (Entry<String, DownloadEntity> entry : DataChanger.getInstance().getDownloadEntries().entrySet()) {
for (Entry<String, DownloadEntry> entry : DataChanger.getInstance()
.getDownloadEntries().entrySet()) {
if (entry.getValue().getStatus() == DownloadStatus.downloading) {
pause(entry.getValue().getUrl());
}
}
Utils.log(DownloadManager.class.getSimpleName(), "pause all");
Trace.getInstance().debug(DownloadManager.class.getSimpleName(),
"pause all");
}
/**
* 根据url获取某一个下载任务
*
* @param url 下载链接
* @param url
* @return null表示下载列表中不存在该任务否则返回下载任务
*/
public DownloadEntity get(String url) {
public DownloadEntry get(String url) {
return DownloadDao.getInstance(context).get(url);
}
/**
* 根据包名获取某一个下载任务
*
* @param packageName 包名
* @return null表示下载列表中不存在该任务否则返回下载任务
*/
public DownloadEntity getByPackage(String packageName) {
for (DownloadEntity downloadEntity : DownloadDao.getInstance(context).getAll()) {
if (packageName.equals(downloadEntity.getPackageName())) {
return downloadEntity;
}
}
return null;
}
/**
* 获取所有下载列表中的任务
*
* @return null表示没有下载任务
*/
public List<DownloadEntity> getAll() {
Utils.log(DownloadManager.class.getSimpleName(), "getAll");
public List<DownloadEntry> getAll() {
Trace.getInstance().debug(DownloadManager.class.getSimpleName(),
"getAll");
return DownloadDao.getInstance(context).getAll();
}
/**
* 检查数据库中当前是下载状态,但并未在下载进程中的下载数据
*/
public void checkAll() {
List<String> urlList = new ArrayList<>();
for (Entry<String, DownloadTask> entry : DataChanger.getInstance()
.getDownloadingTasks().entrySet()) {
urlList.add(entry.getValue().getEntry().getUrl());
}
for (DownloadEntity downloadEntity : getAll()) {
if (!urlList.contains(downloadEntity.getUrl())
&& downloadEntity.getStatus().equals(DownloadStatus.downloading)) {
downloadEntity.setStatus(DownloadStatus.pause);
DownloadDao.getInstance(context).newOrUpdate(downloadEntity);
DataChanger.getInstance().notifyDataChanged(downloadEntity);
}
}
}
public void addObserver(DataWatcher dataWatcher) {
DataChanger.getInstance().addObserver(dataWatcher);
Utils.log(DownloadManager.class.getSimpleName(), "addObserver");
Trace.getInstance().debug(DownloadManager.class.getSimpleName(),
"addObserver");
}
public void removeObserver(DataWatcher dataWatcher) {
DataChanger.getInstance().deleteObserver(dataWatcher);
Utils.log(DownloadManager.class.getSimpleName(), "removeObserver");
Trace.getInstance().debug(DownloadManager.class.getSimpleName(),
"removeObserver");
}
public void removeObservers() {
DataChanger.getInstance().deleteObservers();
Utils.log(DownloadManager.class.getSimpleName(), "removeObserver");
Trace.getInstance().debug(DownloadManager.class.getSimpleName(),
"removeObservers");
}
}

Some files were not shown because too many files have changed in this diff Show More