Commit 544be0d1 authored by clotee's avatar clotee

update android

parent 86c39069
...@@ -30,14 +30,6 @@ pids ...@@ -30,14 +30,6 @@ pids
# built application files # built application files
*.apk *.apk
*.ap_ *.ap_
wxframework
sdk
ErosPluginAmap
erosplugingt
erospluginumeng
erospluginwxpay
nexus
erospluginum
# files for the dex VM # files for the dex VM
*.dex *.dex
......
## 介绍 ## 介绍
> lm-weex app 快速开发模板,可通过脚手架 lm-weex-cli `init` 指令快速生成。 > sl-weex app 快速开发模板,可通过脚手架 sl-weex-cli `init` 指令快速生成。
### 运行命令:```lm-weex dev``` ### 运行命令:```sl-weex dev```
### 项目构建:```lm-weex build``` ### 项目构建:```sl-weex build```
### 打包到IOS:```lm-weex pack ios``` ### 打包到IOS:```sl-weex pack ios```
### 打包到安卓:```lm-weex pack android``` ### 打包到安卓:```sl-weex pack android```
{ {
"name": "lm-template-source", "name": "sl-template-source",
"version": "1.0.0", "version": "1.0.0",
"lockfileVersion": 1, "lockfileVersion": 1,
"requires": true, "requires": true,
...@@ -131,7 +131,7 @@ ...@@ -131,7 +131,7 @@
"@babel/highlight": { "@babel/highlight": {
"version": "7.0.0-beta.44", "version": "7.0.0-beta.44",
"resolved": "http://registry.npm.taobao.org/@babel/highlight/download/@babel/highlight-7.0.0-beta.44.tgz", "resolved": "http://registry.npm.taobao.org/@babel/highlight/download/@babel/highlight-7.0.0-beta.44.tgz",
"integrity": "sha1-GMlM5UORaoBVPtzc9oGJCyAHR9U=", "integrity": "sha1-GMsl5UORaoBVPtzc9oGJCyAHR9U=",
"dev": true, "dev": true,
"requires": { "requires": {
"chalk": "^2.0.0", "chalk": "^2.0.0",
...@@ -1032,7 +1032,7 @@ ...@@ -1032,7 +1032,7 @@
"babel-plugin-transform-export-extensions": { "babel-plugin-transform-export-extensions": {
"version": "6.22.0", "version": "6.22.0",
"resolved": "http://registry.npm.taobao.org/babel-plugin-transform-export-extensions/download/babel-plugin-transform-export-extensions-6.22.0.tgz", "resolved": "http://registry.npm.taobao.org/babel-plugin-transform-export-extensions/download/babel-plugin-transform-export-extensions-6.22.0.tgz",
"integrity": "sha1-U3OLR+deghhYnuqUbLvTkQm75lM=", "integrity": "sha1-U3OLR+deghhYnuqUbLvTkQm75sl=",
"dev": true, "dev": true,
"requires": { "requires": {
"babel-plugin-syntax-export-extensions": "^6.8.0", "babel-plugin-syntax-export-extensions": "^6.8.0",
...@@ -1090,7 +1090,7 @@ ...@@ -1090,7 +1090,7 @@
"babel-preset-env": { "babel-preset-env": {
"version": "1.5.2", "version": "1.5.2",
"resolved": "http://registry.npm.taobao.org/babel-preset-env/download/babel-preset-env-1.5.2.tgz", "resolved": "http://registry.npm.taobao.org/babel-preset-env/download/babel-preset-env-1.5.2.tgz",
"integrity": "sha1-zUrpCm6Utwn5c3SzPl+LmDVWre8=", "integrity": "sha1-zUrpCm6Utwn5c3SzPl+slDVWre8=",
"dev": true, "dev": true,
"requires": { "requires": {
"babel-plugin-check-es2015-constants": "^6.22.0", "babel-plugin-check-es2015-constants": "^6.22.0",
...@@ -1292,7 +1292,7 @@ ...@@ -1292,7 +1292,7 @@
"brace-expansion": { "brace-expansion": {
"version": "1.1.11", "version": "1.1.11",
"resolved": "http://registry.npm.taobao.org/brace-expansion/download/brace-expansion-1.1.11.tgz", "resolved": "http://registry.npm.taobao.org/brace-expansion/download/brace-expansion-1.1.11.tgz",
"integrity": "sha1-PH/L9SnYcibz0vUrlm/1Jx60Qd0=", "integrity": "sha1-PH/L9SnYcibz0vUrsl/1Jx60Qd0=",
"dev": true, "dev": true,
"requires": { "requires": {
"balanced-match": "^1.0.0", "balanced-match": "^1.0.0",
...@@ -1302,7 +1302,7 @@ ...@@ -1302,7 +1302,7 @@
"browserslist": { "browserslist": {
"version": "2.11.3", "version": "2.11.3",
"resolved": "http://registry.npm.taobao.org/browserslist/download/browserslist-2.11.3.tgz", "resolved": "http://registry.npm.taobao.org/browserslist/download/browserslist-2.11.3.tgz",
"integrity": "sha1-/jYWeu0bvN5IJ+v+cTR6LMcLmbI=", "integrity": "sha1-/jYWeu0bvN5IJ+v+cTR6slcslbI=",
"dev": true, "dev": true,
"requires": { "requires": {
"caniuse-lite": "^1.0.30000792", "caniuse-lite": "^1.0.30000792",
...@@ -1531,7 +1531,7 @@ ...@@ -1531,7 +1531,7 @@
"entities": { "entities": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "http://registry.npm.taobao.org/entities/download/entities-1.1.2.tgz", "resolved": "http://registry.npm.taobao.org/entities/download/entities-1.1.2.tgz",
"integrity": "sha1-vfpzUplmTfr9NFKe1PhSKidf6lY=", "integrity": "sha1-vfpzUpslTfr9NFKe1PhSKidf6lY=",
"dev": true "dev": true
}, },
"eros-widget": { "eros-widget": {
...@@ -2006,7 +2006,7 @@ ...@@ -2006,7 +2006,7 @@
"json-schema-traverse": { "json-schema-traverse": {
"version": "0.3.1", "version": "0.3.1",
"resolved": "http://registry.npm.taobao.org/json-schema-traverse/download/json-schema-traverse-0.3.1.tgz", "resolved": "http://registry.npm.taobao.org/json-schema-traverse/download/json-schema-traverse-0.3.1.tgz",
"integrity": "sha1-NJptRMU6Ud6JtAgFxdXlm0F9M0A=", "integrity": "sha1-NJptRMU6Ud6JtAgFxdXsl0F9M0A=",
"dev": true "dev": true
}, },
"json-stable-stringify-without-jsonify": { "json-stable-stringify-without-jsonify": {
...@@ -2259,7 +2259,7 @@ ...@@ -2259,7 +2259,7 @@
"regenerator-runtime": { "regenerator-runtime": {
"version": "0.12.1", "version": "0.12.1",
"resolved": "http://registry.npm.taobao.org/regenerator-runtime/download/regenerator-runtime-0.12.1.tgz", "resolved": "http://registry.npm.taobao.org/regenerator-runtime/download/regenerator-runtime-0.12.1.tgz",
"integrity": "sha1-+hpxVEdkwDb4xJsToIsllMn4oN4=", "integrity": "sha1-+hpxVEdkwDb4xJsToIslsln4oN4=",
"dev": true "dev": true
}, },
"regenerator-transform": { "regenerator-transform": {
...@@ -2325,7 +2325,7 @@ ...@@ -2325,7 +2325,7 @@
"require-uncached": { "require-uncached": {
"version": "1.0.3", "version": "1.0.3",
"resolved": "http://registry.npm.taobao.org/require-uncached/download/require-uncached-1.0.3.tgz", "resolved": "http://registry.npm.taobao.org/require-uncached/download/require-uncached-1.0.3.tgz",
"integrity": "sha1-Tg1W1slmL9MeQwEcS5WqSZVUIdM=", "integrity": "sha1-Tg1W1sslL9MeQwEcS5WqSZVUIdM=",
"dev": true, "dev": true,
"requires": { "requires": {
"caller-path": "^0.1.0", "caller-path": "^0.1.0",
...@@ -2527,7 +2527,7 @@ ...@@ -2527,7 +2527,7 @@
"supports-color": { "supports-color": {
"version": "5.5.0", "version": "5.5.0",
"resolved": "http://registry.npm.taobao.org/supports-color/download/supports-color-5.5.0.tgz", "resolved": "http://registry.npm.taobao.org/supports-color/download/supports-color-5.5.0.tgz",
"integrity": "sha1-4uaaRKyHcveKHsCzW2id9lMO/I8=", "integrity": "sha1-4uaaRKyHcveKHsCzW2id9slO/I8=",
"requires": { "requires": {
"has-flag": "^3.0.0" "has-flag": "^3.0.0"
} }
......
{ {
"name": "lm-template-source", "name": "sl-template-source",
"version": "1.0.0", "version": "1.0.0",
"description": "a project for weex", "description": "a project for weex",
"main": "index.js", "main": "index.js",
......
# eros-nexus
Android基础框架
Android Base抽象层。
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
group = 'myliuyx'
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
}
}
android {
compileSdkVersion 25
buildToolsVersion '26.0.2'
defaultConfig {
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
abortOnError false
}
}
def PROJECT_SUPPORTLIBV_NEXUS = "25.3.1"
dependencies {
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile 'junit:junit:4.12'
compile "com.android.support:appcompat-v7:${PROJECT_SUPPORTLIBV_NEXUS}"
compile "com.android.support:support-v4:${PROJECT_SUPPORTLIBV_NEXUS}"
compile "com.android.support:recyclerview-v7:${PROJECT_SUPPORTLIBV_NEXUS}"
compile 'com.alibaba:fastjson:1.1.68.android'
// compile 'com.taobao.android:weex_sdk:0.18.0'
// compile project(':sdk')
compile 'com.gsst.mobile:gsst-weex-base-sdk:0.0.02-SNAPSHOT'
compile 'com.squareup.okhttp:okhttp-ws:2.3.0'
compile 'com.squareup.okhttp3:okhttp:3.3.1'
compile files('libs/otto-1.3.5.jar')
compile 'com.lzy.widget:imagepicker:0.6.1'
compile('com.github.bumptech.glide:glide:4.7.1', {
exclude group: 'com.android.support'
})
annotationProcessor('com.github.bumptech.glide:compiler:4.8.0', {
exclude group: 'com.android.support'
})
compile('com.github.bumptech.glide:okhttp3-integration:4.7.1', {
exclude group: 'com.android.support'
})
compile 'org.weex.plugin:processor:1.0.2'
uploadArchives {
repositories {
mavenDeployer {
//maven address
repository(url: 'http://192.168.12.122:8090/nexus/repository/maven-snapshots/') {
authentication(userName: "deployment", password: "deployment123")
}
pom.project {
groupId 'com.gsst.mobile'
artifactId 'gsst-weex-base-plugin'
version '0.0.04-SNAPSHOT'
packaging 'jar'
}
}
}
}
}
repositories {
maven { url 'http://192.168.12.122:8090/nexus/repository/maven-snapshots/' }
jcenter()
mavenCentral()
}
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
package com.benmu;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.benmu.test", appContext.getPackageName());
}
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.eros" />
package android.support.v4.view;
import android.content.Context;
import android.util.AttributeSet;
/**
* {@linkplain #setChildrenDrawingOrderEnabledCompat(boolean)} does some reflection that isn't needed.
* And was making view creation time rather large. So lets override it and make it better!
*/
public class BetterViewPager extends ViewPager {
public BetterViewPager(Context context) {
super(context);
}
public BetterViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setChildrenDrawingOrderEnabledCompat(boolean enable) {
setChildrenDrawingOrderEnabled(enable);
}
}
package com.eros.framework;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import com.eros.framework.constant.Constant;
import com.eros.framework.manager.impl.FileManager;
import com.eros.framework.model.PlatformConfigBean;
import com.eros.framework.utils.SharePreferenceUtil;
import java.io.File;
import java.util.Map;
/**
* Created by Carry on 2017/8/23.
*/
public class BMWXEnvironment {
public static PlatformConfigBean mPlatformConfig;
public static Context mApplicationContext;
public static Map<String, String> mCustomer;
public static String loadBmLocal(Context context, Uri uri) {
StringBuffer path = new StringBuffer();
path.append(uri.getHost()).append(uri.getPath());
if (!TextUtils.isEmpty(uri.getQuery())) {
path.append("?").append(uri.getQuery());
}
if (Constant.INTERCEPTOR_ACTIVE.equalsIgnoreCase(SharePreferenceUtil.getInterceptorActive
(context))) {
return FileManager.getPathBundleDir(context, "bundle/" + path.toString())
.getAbsolutePath();
} else {
return String.format("%s/dist/%s", BMWXEnvironment.mPlatformConfig.getUrl()
.getJsServer
(), path.toString());
}
}
}
package com.eros.framework.adapter;
import android.content.Context;
import com.eros.framework.utils.SharePreferenceUtil;
import java.io.Serializable;
/**
* Created by Carry on 2017/8/21. 默认存储实现 基于SP实现
*/
public class DefaultStorageAdapter {
private static DefaultStorageAdapter mInstance = new DefaultStorageAdapter();
private DefaultStorageAdapter() {
}
public static DefaultStorageAdapter getInstance() {
return mInstance;
}
public boolean deleteData(Context context, String key) {
return SharePreferenceUtil.deleteData(context, key);
}
public boolean setData(Context context, String key, Serializable value) {
return SharePreferenceUtil.setData(context, key, value);
}
public <T> T getData(Context context, String key, Class<T> clazz) {
return SharePreferenceUtil.getData(context, key, clazz);
}
public boolean removeData(Context context) {
return SharePreferenceUtil.clearSp(context);
}
}
package com.eros.framework.adapter.router;
import android.app.Activity;
import android.util.Log;
import java.util.Stack;
/**
* Created by Carry on 2017/8/21. activity stack tracker
*/
public class RouterTracker {
private static Stack<ActivityStackFrame> mTotal = new Stack<>();
private static String TAG = "RouterTracker";
public static void push(Activity activity, String stackName) {
if (mTotal.size() == 0) {
ActivityStackFrame frame = new ActivityStackFrame();
frame.setName(stackName);
Stack<Activity> activities = new Stack<>();
activities.push(activity);
frame.setActivities(activities);
mTotal.push(frame);
} else {
ActivityStackFrame frame = mTotal.peek();
frame.getActivities().push(activity);
}
}
public static void push(Activity activity) {
push(activity, activity.getClass().getSimpleName());
}
/**
* 此方法用于创建新的activity栈
*
* @param activity 新的activity
*/
public static void newInstancePush(Activity activity, String stackName) {
ActivityStackFrame newInstance = new ActivityStackFrame();
newInstance.setName(stackName);
Stack<Activity> activities = new Stack<>();
activities.push(activity);
newInstance.setActivities(activities);
mTotal.push(newInstance);
}
/**
* 移除最上方activity栈最上方activity
*
* @return 移除的activity
*/
public static Activity popActivity() {
if (mTotal.isEmpty()) return null;
return pop(mTotal.peek());
}
/**
* 移除最上方栈帧
*
* @return 移除的栈帧
*/
public static ActivityStackFrame popStackFrame() {
if (mTotal.isEmpty()) return null;
return pop();
}
/**
* 得到最上方activity
*/
public static Activity peekActivity() {
if (mTotal.isEmpty()) return null;
ActivityStackFrame peek = mTotal.peek();
if (null == peek.getActivities() || peek.getActivities().isEmpty()) return null;
return peek.getActivities().peek();
}
/**
* 得到最上方栈帧
*/
public static ActivityStackFrame peekStackFrame() {
if (mTotal.isEmpty()) return null;
return mTotal.peek();
}
/**
* 移除某个activity
*/
public static void removeActivity(Activity activity) {
ActivityStackFrame findFrame = null;
outer:
for (ActivityStackFrame frame : mTotal) {
Stack<Activity> activities = frame.getActivities();
for (Activity item : activities) {
if (item == activity) {
findFrame = frame;
notifyActivityRemove(activity,true);
break outer;
}
}
}
if (findFrame != null) {
removeActivitySinglely(activity, findFrame);
}
}
/**
* 生命周期自变化导致移除某个activity
*/
public static void autoRemoveActivity(Activity activity) {
ActivityStackFrame findFrame = null;
outer:
for (ActivityStackFrame frame : mTotal) {
Stack<Activity> activities = frame.getActivities();
for (Activity item : activities) {
if (item == activity) {
findFrame = frame;
notifyActivityRemove(activity,false);
break outer;
}
}
}
if (findFrame != null) {
removeActivitySinglely(activity, findFrame);
}
}
/**
* 根据名字移除栈帧
*/
public static void removeStackFrame(String name) {
ActivityStackFrame findFrame = null;
for (ActivityStackFrame frame : mTotal) {
if (frame.getName().equals(name)) {
findFrame = frame;
break;
}
}
if (findFrame != null) {
removeFrameEntirely(findFrame);
}
}
/**
* 根据activity移除栈帧
*/
public static void removeStackFrame(Activity activity) {
ActivityStackFrame findFrame = null;
outer:
for (ActivityStackFrame frame : mTotal) {
Stack<Activity> activities = frame.getActivities();
for (Activity item : activities) {
if (item == activity) {
findFrame = frame;
break outer;
}
}
}
if (findFrame != null) {
removeFrameEntirely(findFrame);
}
}
/**
* 移除activity直到
*
* @param surplus 剩余activity的数量
*/
public static void clearActivitySurplus(int surplus) {
int length = length();
while (!mTotal.isEmpty()) {
ActivityStackFrame frame = mTotal.peek();
Stack<Activity> activities = frame.getActivities();
while (!activities.isEmpty()) {
if (length == surplus) {
return;
}
pop(frame);
length--;
}
}
}
/**
* 得到activity数量
*/
public static int length() {
int length = 0;
for (ActivityStackFrame frame : mTotal) {
for (Activity item : frame.getActivities()) {
length++;
}
}
return length;
}
/**
* pop最上方activity 并通知activity销毁
*/
private static Activity pop(ActivityStackFrame frame) {
Stack<Activity> activities = frame.getActivities();
if (null == activities || activities.isEmpty()) return null;
Activity activity = activities.pop();
notifyActivityRemove(activity,true);
if (activities.isEmpty()) {
//当前栈帧中activity全部弹出,弹出当前栈帧
if (mTotal.size() > 1) {
mTotal.pop();
}
}
return activity;
}
/**
* pop最上方栈帧 并通知栈帧所有activity销毁
*/
private static ActivityStackFrame pop() {
ActivityStackFrame frame = mTotal.pop();
removeFrameEntirely(frame);
return frame;
}
/**
* 移除某个activity
*/
private static void removeActivitySinglely(Activity act, ActivityStackFrame frame) {
Stack<Activity> activities = frame.getActivities();
activities.remove(act);
if (activities.isEmpty()) {
//当前栈帧中activity全部弹出,弹出当前栈帧
mTotal.remove(frame);
}
}
private static void removeFrameEntirely(ActivityStackFrame frame) {
Stack<Activity> activities = frame.activities;
for (Activity activity : activities) {
notifyActivityRemove(activity,true);
}
activities.clear();
mTotal.remove(frame);
}
private static void notifyActivityRemove(Activity act,boolean force) {
if (act instanceof RouterTrackerListener) {
RouterTrackerListener routerTrackerListener = (RouterTrackerListener) act;
routerTrackerListener.onDetach(act,force);
} else {
Log.e(TAG, act.getClass().getName() + "is unTrack");
}
}
private static class ActivityStackFrame {
private Stack<Activity> activities;
private String name;
public ActivityStackFrame(Stack<Activity> activities, String name) {
this.activities = activities;
this.name = name;
}
ActivityStackFrame() {
}
Stack<Activity> getActivities() {
return activities;
}
void setActivities(Stack<Activity> activities) {
this.activities = activities;
}
int getLength() {
return activities.size();
}
String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
}
public interface RouterTrackerListener {
void onAttach(Activity activity);
void onAttach(Activity activity, String activityName);
void onDetach(Activity activity, boolean force);
void onDetach(Activity activity, String activityName);
}
}
package com.eros.framework.constant;
/**
* Created by Carry on 2017/8/7.
*/
public class Constant {
/**
* router参数
*/
public static final String ROUTERPARAMS = "ROUTERPARAMS";
public static final String TABBAR = "tabBar";
/**
* 首页url
*/
public static final String HOME_URL = "HOME_URL";
/**
* 分享内容key
*/
public static final String WEBVIEW_PARAMS = "WEBVIEW_PARAMS";
/*
地图页面接受参数
*/
public static final String MAPVIEW_PARAMS = "MAPVIEW_PARAMS";
// public static final String AMAP_KEY = "a3308e6aef150346915922d2ea292590";
// 自定义customer_componets
public static final String CUSTOMER_COMPONETS = "customer_componets";
// 自定义 customer_modules
public static final String CUSTOMER_MODULES = "customer_modules";
/**
* 通知相关
*/
public static class Notification {
/**
* 显示通知的ID
*/
public static final int NOTIFY_ID_MESSAGE = 1;
/**
* 消息通知参数key
*/
public static final String TAG_NOTIFICATION = "TAG_NOTIFICATION";
/**
* 推送function type
*/
public static final class FunctionType {
//顶号
public static final String OCCUPY = "APP_OCCUPY";
//健康助手
public static final String SEND_REPLY = "SEND_REPLY";
//健康助手关单
public static final String SEND_CLOSE = "SEND_CLOSE";
}
}
/**
* sp存储key
*/
public static class SP {
public static final String SP_API_URL = "API_URL_SP";
public static final String SP_NATIVE_NAME = "BMWEEXOPEN_NATIVE_SP";
public static final String SP_JS_NAME = "BMWEEXOPEN_JS_SP";
public static final String SP_TOKEN = "SP_TOKEN";
public static final String SP_USERINFO = "SP_USERINFO";
public static final String SP_VERSION = "SP_VERSION";
public static final String SP_FIRST_LAUNCHER = "SP_FIRST_LAUNCHER";
public static final String SP_DOWNLOAD_VERSION = "SP_DOWNLOAD_VERSION";
public static final String SP_CID = "SP_CID";
public static final String SP_INTERCEPTOR_ACTIVE = "SP_INTERCEPTOR_ACTIVE";
public static final String SP_HOTREFRESH_SWITCH = "SP_HOTREFRESH_SWITCH";
public static final String SP_FONTSIZE = "SP_FONTSIZE";
public static final String SP_APPCHANNEL = "SP_APPCHANNEL";
public static final String SP_KEY_WH = "SP_KEY_WH";
public static final String SP_HOMEPAGE_URL = "SP_HOMEPAGE_URL";
public static final String SP_TABBAR_JSON = "SP_TABBAR_JSON";
}
/**
* native事件
*/
public static class Action {
public static String ACTION_GOBALFONTSIZE_CHANGE = "com.benmu.jyt" +
".ACTION_GOBALFONTSIZE_CHANGE";
public static String ACTION_SCREENSHOT = "com.benmu.jyt.ACTION_SCREENSHOT";
public static String ACTION_UPDATE_DEBUG = "com.benmu.jyt.ACTION_UPDATE_DEBUG";
public static final String ACTION_NOTIFICATION = "com.benmu.jyt.ACTION_NOTIFICATION";
public static final String ACTION_ALERT_UPDATE = "com.benmu.jyt.ACTION_ALERT_UPDATE";
public static final String ACTION_AUTHLOGIN_CANCEL = "com.benmu.jyt" +
".ACTION_AUTHLOGIN_CANCEL";
}
/**
* 本地字体配置
*/
public static class FontSize {
public static String NORM = "NORM";
public static String BIG = "BIG";
public static String EXTRALARGE = "EXTRALARGE";
}
/**
* -------------------------监控配置-------------------------------
**/
public static class Monintor {
public static final String APP_NAME = "fe_app_jyt";
public static final String MONINTOR_RENDERTIME = "screenRenderTime";
public static final String PLATFORM = "Android";
public static final String MONINTOR_RENDERTIME_ALIAS = "js渲染时间";
public static final String MONINTOR_REQUEST_TIME = "request_time";
public static final String MONINTOR_REQUEST_TIME_ALIAS = "接口时间";
public static final String MONINTOR_REQUEST_FAILED = "request_error";
public static final String MONINTOR_REQUEST_FAILED_ALIAS = "请求失败";
public static final String MONINTOR_IMAGE_FAILED = "img_error";
public static final String MONINTOR_IMAGE_FAILED_ALIAS = "图片错误";
public static final String MONINTOR_JSERROR = "jsError";
public static final String MONINTOR_JSERROR_ALIAS = "js错误";
public static final String MONINTOR_DOWNLOADERROR = "downloadJsFailed";
public static final String MONINTOR_DOWNLOADERROR_ALIAS = "下载js资源失败";
public static final String MONINTOR_DIFFERROR = "jsDiffFailed";
public static final String MONINTOR_DIFFERROR_ALIAS = "jsDiff失败";
}
/**
* -------------------------客制化环境配置-------------------------------
**/
public static class CustomOptions {
//bmFontSize
public static final String CUSTOM_FONTSIZE = "bmFontSize";
//bmFontScale
public static final String CUSTOM_FONTSCALE = "bmFontScale";
//deviceId
public static final String CUSTOM_DEVICEID = "deviceId";
//jsServer
public static final String CUSTOM_SERVERURL = "jsServer";
//logLevel
public static final String CUSTOM_LOGLEVEL = "logLevel";
//reqeust
public static final String CUSTOM_REQUESTURL = "request";
//scale
public static final String CUSTOM_SCALE = "scale";
//状态栏高度
public static final String CUSTOM_STATUSBARHEIGHT = "statusBarHeight";
//导航栏高度
public static final String CUSTOM_NAVBARHEIGHT = "navBarHeight";
//内置js版本
public static final String CUSTOM_JSVERSION = "jsVersion";
//deviceHeight
public static final String CUSTOM_DEVICEHEIGHT = "deviceHeight";
//deviceWidth
public static final String CUSTOM_DEVICEWIDTH = "deviceWidth";
public static final String CUSTOM_VIRTUAL_BUTTONS_HEIGHT = "virtualButtonsHeight";
//appName
public static final String CUSTOM_APPNAME = "appName";
public static final String CUSTOM_REALDEVICEHEIGHT = "realDeviceHeight";
public static final String CUSTOM_TABBARHEIGHT = "tabbarHeight";
}
/**
* ------------------------ImageMager --------------------------
*/
public static final class ImageConstants {
public static final int IMAGE_PICKER = 100;
public static final int IMAGE_NOT_UPLOADER_PICKER = 101;
//上传图片最大宽度像素
public static int BIGGESTWIDTH = 828;
public static final String UPLOAD_IMAGE_BEAN = "upload_image_bean";
public static final int PICK_FROM_CAMERA = 1000;
public static final int PICK_FROM_GALLERY = 1001;
}
/**
* 唤醒action
*/
public static final class AwakeAction {
public static final String ACTION_OPENPAGE = "openPage";
public static final String ACTION_OPENTAB = "openTab";
}
public static final class BROWSE_EVENT {
public static final String BROWSE_IMG_BEAN = "browse_img_bean";
}
public static String APPLICATION_ID;
public static void setApplicationId(String appId) {
APPLICATION_ID = appId;
}
public static String getPageCategory() {
return APPLICATION_ID + ".categoty.page";
}
// public static String BMPAGE_CATEGORY =
public static String getWebViewCategory() {
return APPLICATION_ID + ".category.web";
}
// public static String BMDEBUG_CATEGORY = APPLICATION_ID + ".category.debug";
public static final class ACTIVITIES_ANIMATION {
public static final String ANIMATION_PUSH = "PUSH";
public static final String ANIMATION_PRESENT = "PRESENT";
public static final String ANIMATION_TRANSLATION = "TRANSLATION";
}
public static final String PLATFORM_CONFIG_NAME = "config.native.json";
public static final String BUNDLE_ZIP_NAME = "bundle.zip";
public static final String INTERCEPTOR_ACTIVE = "active";
public static final String INTERCEPTOR_DEACTIVE = "deactivate";
public static class Version {
public static final int UPDATING = 0;
public static final int SLEEP = 1;
}
/**
* 解密Key
*/
public static final String AES_KEY = "e17efea89bafc8af4fdda9a13c79e61b";
/**
* Request Code 相关
*/
public static final class REQUEST_CODE {
public static final int REQUEST_CODE_CONTRACT = 0xf71;
}
}
package com.eros.framework.constant;
/**
* Created by liuyuanxiao on 18/4/8.
*/
public class WXEventCenter {
public static final String EVENT_JS_ON = "EVENT_JS_ON";
public static final String EVENT_JS_EMIT = "EVENT_JS_EMIT";
public static final String EVENT_JS_OFF = "EVENT_JS_OFF";
public static final String EVENT_JS_OFFALL = "EVENT_JS_OFFALL";
public static final String EVENT_INSTANCE_DESTORY = "EVENT_INSTANCE_DESTORY";
public static final String EVENT_PAYBYWECHAT = "com.eros.erospluginwxpay.EventPay";
public static final String EVENT_OPEN = "com.eros.framework.event.router.EventOpen";
public static final String EVENT_GETPARAMS = "com.eros.framework.event.router.EventGetParams";
public static final String EVENT_BACK = "com.eros.framework.event.router.EventBack";
public static final String EVENT_GETBACKPARAMS = "com.eros.framework.event.router" +
".EventGetBackParams";
public static final String EVENT_LOGINSUCCESS = "EVENT_LOGINSUCCESS";
public static final String EVENT_REFRESH = "com.eros.framework.event.router.EventRefresh";
public static final String EVENT_FINISH = "com.eros.framework.event.router.EventFinish";
public static final String EVENT_BACKHOME = "EVENT_BACKHOME";
public static final String EVENT_TOLOGIN = "EVENT_TOLOGIN";
public static final String EVENT_TOMAP = "EVENT_TOMAP";
public static final String EVENT_TOWEBVIEW = "com.eros.framework.event.router.EventWebView";
public static final String EVENT_CALL = "com.eros.framework.event.router.EventCall";
public static final String EVENT_SHARE = "EVENT_SHARE";
public static final String EVENT_SETDATA = "com.eros.framework.event.shorage.EventSetData";
public static final String EVENT_GETDATA = "com.eros.framework.event.shorage.EventGetData";
public static final String EVENT_DELETEDATA = "com.eros.framework.event.shorage" +
".EventDeleteData";
public static final String EVENT_REMOVEDATA = "com.eros.framework.event.shorage" +
".EventRemoveData";
public static final String EVENT_RESIGNKEYBOARD = "EVENT_RESIGNKEYBOARD";
public static final String EVENT_ISINSTALLWXAPP = "EVENT_ISINSTALLWXAPP";
public static final String EVENT_GETCID = "EVENT_GETCID";
public static final String EVENT_WECHATLOGIN = "com.eros.erospluginumeng.event.EventAuth";
public static final String EVENT_LEFTITEM = "com.eros.framework.event.nav.EventLeftItem";
public static final String EVENT_RIGHTITEM = "com.eros.framework.event.nav.EventRightItem";
public static final String EVENT_CENTERITEM = "com.eros.framework.event.nav.EventCenterItem";
public static final String EVENT_BROWSERIMG = "com.eros.framework.event.browse.EventBrowse";
public static final String EVENT_CAMERA = "EVENT_CAMERA";
public static final String EVENT_CAMERA_UPLOADIMAGE = "EVENT_CAMERA_UPLOADIMAGE";
public static final String EVENT_CAMERA_PATH = "EVENT_CAMERA_PATH";
public static final String EVENT_CAMERA_UPLOADSCREENSHOT = "EVENT_CAMERA_UPLOADSCREENSHOT";
public static final String EVENT_GEOLOCATION_GET = "com.plugamap.EventGeo";
public static final String EVENT_MODAL_ALERT = "com.eros.framework.event.modal.EventAlert";
public static final String EVENT_MODAL_CONFIRM = "com.eros.framework.event.modal.EventConfirm";
public static final String EVENT_MODAL_SHOWLOADING = "com.eros.framework.event.modal" +
".EventShowLoading";
public static final String EVENT_MODAL_DISMISSLOADING = "com.eros.framework.event.modal" +
".EventDismissLoading";
public static final String EVENT_MODAL_TOAST = "com.eros.framework.event.modal.EventToast";
public static final String EVENT_FETCH = "EVENT_FETCH";
public static final String EVENT_GETREQUESTURL = "EVENT_GETREQUESTURL";
public static final String EVENT_NAVIGATIONINFO = "com.eros.framework.event.nav" +
".EventNavigationInfo";
public static final String EVENT_COPYSTRING = "EVENT_COPYSTRING";
public static final String EVENT_RELAYTOFRIEND = "EVENT_RELAYTOFRIEND";
public static final String EVENT_RELAYTOCRICLE = "EVENT_RELAYTOCRICLE";
public static final String EVENT_OPENBROWSER = "com.eros.framework.event.router" +
".EventOpenBrowser";
public static final String EVENT_COMMUNICATION_SMS = "EVENT_COMMUNICATION_SMS";
public static final String EVENT_COMMUNICATION_CONTACTS = "EVENT_COMMUNICATION_CONTACTS";
public static final String EVENT_SET_HOMEPAGE = "com.eros.framework.event.router" +
".EventSetHomePage";
public static final String EVENT_IMAGE_PICK = "EVENT_IMAGE_PICK";
public static final String EVENT_IMAGE_SCAN = "EVENT_IMAGE_SCAN";
public static final String EVENT_IMAGE_UPLOAD = "EVENT_IMAGE_UPLOAD";
public static final String EVENT_NAV = "com.eros.framework.event.router.EventNav";
public static final String EVENT_PUSHMANAGER = "EVENT_PUSHMANAGER";
public static final String EVENT_TABBAR_SHOWBADGE = "EVENT_TABBAR_SHOWBADGE";
public static final String EVENT_TABBAR_HIDBADGE = "EVENT_TABBAR_HIDBADGE";
public static final String EVENT_TABBAR_OPENPAGE = "EVENT_TABBAR_OPENPAGE";
public static final String EVENT_TABBAR_SETTABBAR = "EVENT_TABBAR_SETTABBAR";
public static final String EVENT_TABBAR_WATCHINDEX = "EVENT_TABBAR_WATCHINDEX";
public static final String EVENT_TABBAR_CLEARWATCH = "EVENT_TABBAR_CLEARWATCH";
public static final String EVENT_TABBAR_CLEARTABBARINFO = "EVENT_TABBAR_CLEARTABBARINFO";
public static final String EVENT_DOWNLOAD_BUNDLE = "EVENT_DOWNLOAD_BUNDLE";
public static final String EVENT_UPDATE_BUNDLE = "EVENT_UPDATE_BUNDLE";
}
package com.eros.framework.event;
import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import com.eros.framework.adapter.router.RouterTracker;
import com.eros.framework.constant.WXEventCenter;
import com.eros.framework.manager.ManagerFactory;
import com.eros.framework.manager.impl.dispatcher.DispatchEventManager;
import com.eros.framework.model.BaseEventBean;
import com.eros.framework.model.WeexEventBean;
import com.eros.framework.utils.JsPoster;
import com.eros.wxbase.EventGate;
import com.eros.wxbase.EventGateFactory;
import com.squareup.otto.Subscribe;
import com.taobao.weex.WXSDKInstance;
import com.taobao.weex.bridge.JSCallback;
import java.util.ArrayList;
/**
* Created by Carry on 2017/8/23.
*/
public class DispatchEventCenter {
private static DispatchEventCenter mInstance = new DispatchEventCenter();
private DispatchEventCenter() {
}
public static DispatchEventCenter getInstance() {
return mInstance;
}
public void register() {
ManagerFactory.getManagerService(DispatchEventManager.class).getBus().register(this);
}
public void unregister() {
ManagerFactory.getManagerService(DispatchEventManager.class).getBus().unregister(this);
}
private Context safeContext(Context context) {
if (!(context instanceof Activity)) {
context = RouterTracker.peekActivity();
}
return context;
}
@Subscribe
public void onBaseEvent(BaseEventBean eventBean) {
reflectionClazzPerform(eventBean);
}
@Subscribe
public void onWeexEvent(WeexEventBean weexEventBean) {
if (weexEventBean == null) return;
Context context = safeContext(weexEventBean.getContext());
if (context == null) return;
String params = weexEventBean.getJsParams();
switch (weexEventBean.getKey()) {
case WXEventCenter.EVENT_IMAGE_UPLOAD:
case WXEventCenter.EVENT_FETCH:
reflectionClazzPerform("com.eros.framework.event.http.EventFetch", context
, weexEventBean
, "", weexEventBean.getKey());
break;
case WXEventCenter.EVENT_IMAGE_PICK:
case WXEventCenter.EVENT_IMAGE_SCAN:
reflectionClazzPerform("com.eros.framework.event.camera.EventImage", context
, weexEventBean
, "", weexEventBean.getKey());
break;
case WXEventCenter.EVENT_CAMERA_UPLOADIMAGE:
case WXEventCenter.EVENT_CAMERA_PATH:
case WXEventCenter.EVENT_CAMERA:
reflectionClazzPerform("com.eros.framework.event.camera.EventCamera", context
, weexEventBean
, "", weexEventBean.getKey());
break;
case WXEventCenter.EVENT_RESIGNKEYBOARD:
case WXEventCenter.EVENT_ISINSTALLWXAPP:
case WXEventCenter.EVENT_GETCID:
case WXEventCenter.EVENT_COPYSTRING:
reflectionClazzPerform("com.eros.framework.event.tool.EventTool", context
, weexEventBean
, "", weexEventBean.getKey());
break;
case WXEventCenter.EVENT_SHARE:
case WXEventCenter.EVENT_RELAYTOFRIEND:
case WXEventCenter.EVENT_RELAYTOCRICLE:
reflectionClazzPerform("com.eros.erospluginumeng.event.EventShare", context
, weexEventBean
, "", weexEventBean.getKey());
break;
case WXEventCenter.EVENT_TABBAR_SHOWBADGE:
case WXEventCenter.EVENT_TABBAR_HIDBADGE:
case WXEventCenter.EVENT_TABBAR_OPENPAGE:
case WXEventCenter.EVENT_TABBAR_SETTABBAR:
case WXEventCenter.EVENT_TABBAR_WATCHINDEX:
case WXEventCenter.EVENT_TABBAR_CLEARTABBARINFO:
case WXEventCenter.EVENT_TABBAR_CLEARWATCH:
reflectionClazzPerform("com.eros.framework.event.TabbarEvent", context
, weexEventBean
, "", weexEventBean.getKey());
break;
case WXEventCenter.EVENT_UPDATE_BUNDLE:
case WXEventCenter.EVENT_DOWNLOAD_BUNDLE:
reflectionClazzPerform("com.eros.framework.event.UpdateJsBundleEvent", context
, weexEventBean
, "", weexEventBean.getKey());
break;
case WXEventCenter.EVENT_COMMUNICATION_SMS:
case WXEventCenter.EVENT_COMMUNICATION_CONTACTS:
reflectionClazzPerform("com.eros.framework.event.EventCommunication", context
, weexEventBean
, "", weexEventBean.getKey());
break;
case WXEventCenter.EVENT_GEOLOCATION_GET:
reflectionClazzPerform(WXEventCenter.EVENT_GEOLOCATION_GET
, context
, weexEventBean
, "");
break;
default:
reflectionClazzPerform(weexEventBean.getKey()
, context
, weexEventBean
, "");
break;
}
}
private void reflectionClazzPerform(String clazzName, Context context, WeexEventBean
weexEventBean, String errosMsg) {
reflectionClazzPerform(weexEventBean.getKey()
, context
, weexEventBean
, "", null);
}
private void reflectionClazzPerform(BaseEventBean eventBean) {
if (eventBean == null) return;
if (TextUtils.isEmpty(eventBean.clazzName)) return;
if (eventBean.context == null) return;
EventGate event = EventGateFactory.getEventGate(eventBean.clazzName);
if (null != event) {
event.perform(eventBean.context, eventBean);
}
}
private void reflectionClazzPerform(String clazzName, Context context, WeexEventBean
weexEventBean, String errosMsg, String type) {
EventGate event = EventGateFactory.getEventGate(clazzName);
String params = weexEventBean.getJsParams();
if (null != event) {
if (TextUtils.isEmpty(type)) {
event.perform(context, weexEventBean);
} else {
event.perform(context, weexEventBean, type);
}
} else {
if (TextUtils.isEmpty(params)) {
JsPoster.postFailed(weexEventBean.getJscallback());
} else {
JsPoster.postFailed(errosMsg, weexEventBean.getJscallback());
}
}
}
}
package com.eros.framework.http;
import com.eros.framework.BMWXEnvironment;
/**
* Created by Carry on 2017/8/21.
*/
public class Api {
public static String BASE_URL = BMWXEnvironment.mPlatformConfig.getUrl().getRequest();
public static String UPLOAD_URL = BMWXEnvironment.mPlatformConfig.getUrl().getImage();
}
package com.eros.framework.http;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import com.eros.framework.http.okhttp.cookie.store.CookieStore;
import com.eros.framework.http.okhttp.cookie.store.SerializableHttpCookie;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
/**
* Created by Carry on 2017/7/6.
*/
public class BMPersistentCookieStore implements CookieStore {
private static final String LOG_TAG = "PersistentCookieStore";
private static final String COOKIE_PREFS = "CookiePrefsFile";
private static final String COOKIE_NAME_PREFIX = "cookie_";
private final HashMap<String, ConcurrentHashMap<String, Cookie>> cookies;
private final SharedPreferences cookiePrefs;
/**
* Construct a persistent cookie store.
*
* @param context Context to attach cookie store to
*/
public BMPersistentCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new HashMap<String, ConcurrentHashMap<String, Cookie>>();
// Load any previously stored cookies into the store
Map<String, ?> prefsMap = cookiePrefs.getAll();
for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
if (entry.getValue() != null && !((String) entry.getValue()).startsWith
(COOKIE_NAME_PREFIX)) {
String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
for (String name : cookieNames) {
String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
if (encodedCookie != null) {
Cookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null) {
if (!cookies.containsKey(entry.getKey()))
cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>
());
cookies.get(entry.getKey()).put(name, decodedCookie);
}
}
}
}
}
}
protected void add(HttpUrl uri, Cookie cookie) {
String name = getCookieToken(cookie);
if (!cookie.persistent()) {
if (!cookies.containsKey(uri.host())) {
cookies.put(uri.host(), new ConcurrentHashMap<String, Cookie>());
}
cookies.get(uri.host()).put(name, cookie);
} else {
if (!cookies.containsKey(uri.host())) {
cookies.put(uri.host(), new ConcurrentHashMap<String, Cookie>());
}
cookies.get(uri.host()).put(name, cookie);
// if (cookies.containsKey(uri.host()))
// {
// cookies.get(uri.host()).remove(name);
// }else
// {
// return ;
// }
}
// Save cookie into persistent store
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(uri.host(), TextUtils.join(",", cookies.get(uri.host()).keySet()));
prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableHttpCookie
(cookie)));
prefsWriter.apply();
}
protected String getCookieToken(Cookie cookie) {
return cookie.name() + cookie.domain();
}
@Override
public void add(HttpUrl uri, List<Cookie> cookies) {
for (Cookie cookie : cookies) {
add(uri, cookie);
}
}
@Override
public List<Cookie> get(HttpUrl uri) {
ArrayList<Cookie> ret = new ArrayList<Cookie>();
if (cookies.containsKey(uri.host())) {
Collection<Cookie> cookies = this.cookies.get(uri.host()).values();
for (Cookie cookie : cookies) {
ret.add(cookie);
}
}
return ret;
}
private static boolean isCookieExpired(Cookie cookie) {
return cookie.expiresAt() < System.currentTimeMillis();
}
@Override
public boolean removeAll() {
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.clear();
prefsWriter.apply();
cookies.clear();
return true;
}
@Override
public boolean remove(HttpUrl uri, Cookie cookie) {
String name = getCookieToken(cookie);
if (cookies.containsKey(uri.host()) && cookies.get(uri.host()).containsKey(name)) {
cookies.get(uri.host()).remove(name);
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
if (cookiePrefs.contains(COOKIE_NAME_PREFIX + name)) {
prefsWriter.remove(COOKIE_NAME_PREFIX + name);
}
prefsWriter.putString(uri.host(), TextUtils.join(",", cookies.get(uri.host()).keySet
()));
prefsWriter.apply();
return true;
} else {
return false;
}
}
@Override
public List<Cookie> getCookies() {
ArrayList<Cookie> ret = new ArrayList<Cookie>();
for (String key : cookies.keySet())
ret.addAll(cookies.get(key).values());
return ret;
}
protected String encodeCookie(SerializableHttpCookie cookie) {
if (cookie == null)
return null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ObjectOutputStream outputStream = new ObjectOutputStream(os);
outputStream.writeObject(cookie);
} catch (IOException e) {
Log.d(LOG_TAG, "IOException in encodeCookie", e);
return null;
}
return byteArrayToHexString(os.toByteArray());
}
protected Cookie decodeCookie(String cookieString) {
byte[] bytes = hexStringToByteArray(cookieString);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
Cookie cookie = null;
try {
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
cookie = ((SerializableHttpCookie) objectInputStream.readObject()).getCookie();
} catch (IOException e) {
Log.d(LOG_TAG, "IOException in decodeCookie", e);
} catch (ClassNotFoundException e) {
Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
}
return cookie;
}
/**
* Using some super basic byte array &lt;-&gt; hex conversions so we don't have to rely on any
* large Base64 libraries. Can be overridden if you like!
*
* @param bytes byte array to be converted
* @return string containing hex values
*/
protected String byteArrayToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte element : bytes) {
int v = element & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase(Locale.US);
}
/**
* Converts hex values from strings to byte arra
*
* @param hexString string of hex-encoded values
* @return decoded byte array
*/
protected byte[] hexStringToByteArray(String hexString) {
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
.digit(hexString.charAt(i + 1), 16));
}
return data;
}
}
package com.eros.framework.http.okhttp;
import com.eros.framework.http.okhttp.builder.GetBuilder;
import com.eros.framework.http.okhttp.builder.HeadBuilder;
import com.eros.framework.http.okhttp.builder.OtherRequestBuilder;
import com.eros.framework.http.okhttp.builder.PostFileBuilder;
import com.eros.framework.http.okhttp.builder.PostFormBuilder;
import com.eros.framework.http.okhttp.builder.PostStringBuilder;
import com.eros.framework.http.okhttp.callback.Callback;
import com.eros.framework.http.okhttp.exception.CancelException;
import com.eros.framework.http.okhttp.exception.HttpException;
import com.eros.framework.http.okhttp.request.RequestCall;
import com.eros.framework.http.okhttp.utils.Platform;
import java.io.IOException;
import java.util.concurrent.Executor;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Response;
/**
* Created by zhy on 15/8/17.
*/
public class OkHttpUtils {
public static final long DEFAULT_MILLISECONDS = 10_000L;
private volatile static OkHttpUtils mInstance;
private OkHttpClient mOkHttpClient;
private Platform mPlatform;
public OkHttpUtils(OkHttpClient okHttpClient) {
if (okHttpClient == null) {
mOkHttpClient = new OkHttpClient();
} else {
mOkHttpClient = okHttpClient;
}
mPlatform = Platform.get();
}
public void updateHttpClient(OkHttpClient okHttpClient) {
if (okHttpClient == null) return;
mOkHttpClient = okHttpClient;
}
public static OkHttpUtils initClient(OkHttpClient okHttpClient) {
if (mInstance == null) {
synchronized (OkHttpUtils.class) {
if (mInstance == null) {
mInstance = new OkHttpUtils(okHttpClient);
}
}
}
return mInstance;
}
public static OkHttpUtils getInstance() {
return initClient(null);
}
public Executor getDelivery() {
return mPlatform.defaultCallbackExecutor();
}
public OkHttpClient getOkHttpClient() {
return mOkHttpClient;
}
public static GetBuilder get() {
return new GetBuilder();
}
public static PostStringBuilder postString() {
return new PostStringBuilder();
}
public static PostFileBuilder postFile() {
return new PostFileBuilder();
}
public static PostFormBuilder post() {
return new PostFormBuilder();
}
public static OtherRequestBuilder put() {
return new OtherRequestBuilder(METHOD.PUT);
}
public static HeadBuilder head() {
return new HeadBuilder();
}
public static OtherRequestBuilder delete() {
return new OtherRequestBuilder(METHOD.DELETE);
}
public static OtherRequestBuilder patch() {
return new OtherRequestBuilder(METHOD.PATCH);
}
public void execute(final RequestCall requestCall, Callback callback) {
if (callback == null)
callback = Callback.CALLBACK_DEFAULT;
final Callback finalCallback = callback;
final int id = requestCall.getOkHttpRequest().getId();
requestCall.getCall().enqueue(new okhttp3.Callback() {
@Override
public void onFailure(Call call, final IOException e) {
Exception exception = e;
if (exception == null) {
exception = new IOException();
}
if (call.isCanceled()) {
exception = new CancelException(exception.getMessage());
}
sendFailResultCallback(call, exception, finalCallback, id);
}
@Override
public void onResponse(final Call call, final Response response) {
try {
if (call.isCanceled()) {
//request canceled
Exception canceled = new CancelException("canceled !");
sendFailResultCallback(call, canceled, finalCallback, id);
return;
}
// if (!finalCallback.validateReponse(response, id)) {
// //request failed
// Exception failed = new HttpException(response.code(), "request failed" +
// response.message());
// sendFailResultCallback(call, failed, finalCallback, id);
// return;
// }
Object o = finalCallback.parseNetworkResponse(response, id);
sendSuccessResultCallback(o, finalCallback, id);
} catch (Exception e) {
sendFailResultCallback(call, e, finalCallback, id);
} finally {
if (response.body() != null)
response.body().close();
}
}
});
}
public void sendFailResultCallback(final Call call, final Exception e, final Callback
callback, final int id) {
if (callback == null) return;
mPlatform.execute(new Runnable() {
@Override
public void run() {
callback.onError(call, e, id);
callback.onAfter(id);
}
});
}
public void sendSuccessResultCallback(final Object object, final Callback callback, final int
id) {
if (callback == null) return;
mPlatform.execute(new Runnable() {
@Override
public void run() {
callback.onResponse(object, id);
callback.onAfter(id);
}
});
}
public void cancelTag(Object tag) {
for (Call call : mOkHttpClient.dispatcher().queuedCalls()) {
if (tag.equals(call.request().tag())) {
call.cancel();
}
}
for (Call call : mOkHttpClient.dispatcher().runningCalls()) {
if (tag.equals(call.request().tag())) {
call.cancel();
}
}
}
public static class METHOD {
public static final String HEAD = "HEAD";
public static final String DELETE = "DELETE";
public static final String PUT = "PUT";
public static final String PATCH = "PATCH";
public static final String GET = "GET";
public static final String POST = "POST";
}
}
package com.eros.framework.http.okhttp.builder;
import android.net.Uri;
import com.eros.framework.http.okhttp.request.GetRequest;
import com.eros.framework.http.okhttp.request.RequestCall;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* Created by zhy on 15/12/14.
*/
public class GetBuilder extends OkHttpRequestBuilder<GetBuilder> implements HasParamsable
{
@Override
public RequestCall build()
{
if (params != null)
{
url = appendParams(url, params);
}
return new GetRequest(url, tag, params, headers,id).build();
}
protected String appendParams(String url, Map<String, String> params)
{
if (url == null || params == null || params.isEmpty())
{
return url;
}
Uri.Builder builder = Uri.parse(url).buildUpon();
Set<String> keys = params.keySet();
Iterator<String> iterator = keys.iterator();
while (iterator.hasNext())
{
String key = iterator.next();
builder.appendQueryParameter(key, params.get(key));
}
return builder.build().toString();
}
@Override
public GetBuilder params(Map<String, String> params)
{
this.params = params;
return this;
}
@Override
public GetBuilder addParams(String key, String val)
{
if (this.params == null)
{
params = new LinkedHashMap<>();
}
params.put(key, val);
return this;
}
}
package com.eros.framework.http.okhttp.builder;
import java.util.Map;
/**
* Created by zhy on 16/3/1.
*/
public interface HasParamsable
{
OkHttpRequestBuilder params(Map<String, String> params);
OkHttpRequestBuilder addParams(String key, String val);
}
package com.eros.framework.http.okhttp.builder;
import com.eros.framework.http.okhttp.OkHttpUtils;
import com.eros.framework.http.okhttp.request.OtherRequest;
import com.eros.framework.http.okhttp.request.RequestCall;
/**
* Created by zhy on 16/3/2.
*/
public class HeadBuilder extends GetBuilder
{
@Override
public RequestCall build()
{
return new OtherRequest(null, null, OkHttpUtils.METHOD.HEAD, url, tag, params, headers,id).build();
}
}
package com.eros.framework.http.okhttp.builder;
import com.eros.framework.http.okhttp.request.RequestCall;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by zhy on 15/12/14.
*/
public abstract class OkHttpRequestBuilder<T extends OkHttpRequestBuilder>
{
protected String url;
protected Object tag;
protected Map<String, String> headers;
protected Map<String, String> params;
protected int id;
public T id(int id)
{
this.id = id;
return (T) this;
}
public T url(String url)
{
this.url = url;
return (T) this;
}
public T tag(Object tag)
{
this.tag = tag;
return (T) this;
}
public T headers(Map<String, String> headers)
{
this.headers = headers;
return (T) this;
}
public T addHeader(String key, String val)
{
if (this.headers == null)
{
headers = new LinkedHashMap<>();
}
headers.put(key, val);
return (T) this;
}
public abstract RequestCall build();
}
package com.eros.framework.http.okhttp.builder;
import com.eros.framework.http.okhttp.request.OtherRequest;
import com.eros.framework.http.okhttp.request.RequestCall;
import okhttp3.RequestBody;
/**
* DELETE、PUT、PATCH等其他方法
*/
public class OtherRequestBuilder extends OkHttpRequestBuilder<OtherRequestBuilder>
{
private RequestBody requestBody;
private String method;
private String content;
public OtherRequestBuilder(String method)
{
this.method = method;
}
@Override
public RequestCall build()
{
return new OtherRequest(requestBody, content, method, url, tag, params, headers,id).build();
}
public OtherRequestBuilder requestBody(RequestBody requestBody)
{
this.requestBody = requestBody;
return this;
}
public OtherRequestBuilder requestBody(String content)
{
this.content = content;
return this;
}
}
package com.eros.framework.http.okhttp.builder;
import com.eros.framework.http.okhttp.request.PostFileRequest;
import com.eros.framework.http.okhttp.request.RequestCall;
import java.io.File;
import okhttp3.MediaType;
/**
* Created by zhy on 15/12/14.
*/
public class PostFileBuilder extends OkHttpRequestBuilder<PostFileBuilder>
{
private File file;
private MediaType mediaType;
public OkHttpRequestBuilder file(File file)
{
this.file = file;
return this;
}
public OkHttpRequestBuilder mediaType(MediaType mediaType)
{
this.mediaType = mediaType;
return this;
}
@Override
public RequestCall build()
{
return new PostFileRequest(url, tag, params, headers, file, mediaType,id).build();
}
}
package com.eros.framework.http.okhttp.builder;
import com.eros.framework.http.okhttp.request.PostFormRequest;
import com.eros.framework.http.okhttp.request.RequestCall;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Created by zhy on 15/12/14.
*/
public class PostFormBuilder extends OkHttpRequestBuilder<PostFormBuilder> implements HasParamsable
{
private List<FileInput> files = new ArrayList<>();
@Override
public RequestCall build()
{
return new PostFormRequest(url, tag, params, headers, files,id).build();
}
public PostFormBuilder files(String key, Map<String, File> files)
{
for (String filename : files.keySet())
{
this.files.add(new FileInput(key, filename, files.get(filename)));
}
return this;
}
public PostFormBuilder addFile(String name, String filename, File file)
{
files.add(new FileInput(name, filename, file));
return this;
}
public static class FileInput
{
public String key;
public String filename;
public File file;
public FileInput(String name, String filename, File file)
{
this.key = name;
this.filename = filename;
this.file = file;
}
@Override
public String toString()
{
return "FileInput{" +
"key='" + key + '\'' +
", filename='" + filename + '\'' +
", file=" + file +
'}';
}
}
@Override
public PostFormBuilder params(Map<String, String> params)
{
this.params = params;
return this;
}
@Override
public PostFormBuilder addParams(String key, String val)
{
if (this.params == null)
{
params = new LinkedHashMap<>();
}
params.put(key, val);
return this;
}
}
package com.eros.framework.http.okhttp.builder;
import com.eros.framework.http.okhttp.request.PostStringRequest;
import com.eros.framework.http.okhttp.request.RequestCall;
import okhttp3.MediaType;
/**
* Created by zhy on 15/12/14.
*/
public class PostStringBuilder extends OkHttpRequestBuilder<PostStringBuilder>
{
private String content;
private MediaType mediaType;
public PostStringBuilder content(String content)
{
this.content = content;
return this;
}
public PostStringBuilder mediaType(MediaType mediaType)
{
this.mediaType = mediaType;
return this;
}
@Override
public RequestCall build()
{
return new PostStringRequest(url, tag, params, headers, content, mediaType,id).build();
}
}
package com.eros.framework.http.okhttp.callback;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import okhttp3.Response;
/**
* Created by zhy on 15/12/14.
*/
public abstract class BitmapCallback extends Callback<Bitmap>
{
@Override
public Bitmap parseNetworkResponse(Response response , int id) throws Exception
{
return BitmapFactory.decodeStream(response.body().byteStream());
}
}
package com.eros.framework.http.okhttp.callback;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
public abstract class Callback<T>
{
/**
* UI Thread
*
* @param request
*/
public void onBefore(Request request, int id)
{
}
/**
* UI Thread
*
* @param
*/
public void onAfter(int id)
{
}
/**
* UI Thread
*
* @param progress
*/
public void inProgress(float progress, long total , int id)
{
}
/**
* if you parse reponse code in parseNetworkResponse, you should make this method return true.
*
* @param response
* @return
*/
public boolean validateReponse(Response response, int id)
{
return response.isSuccessful();
}
/**
* Thread Pool Thread
*
* @param response
*/
public abstract T parseNetworkResponse(Response response, int id) throws Exception;
public abstract void onError(Call call, Exception e, int id);
public abstract void onResponse(T response, int id);
public static Callback CALLBACK_DEFAULT = new Callback()
{
@Override
public Object parseNetworkResponse(Response response, int id) throws Exception
{
return null;
}
@Override
public void onError(Call call, Exception e, int id)
{
}
@Override
public void onResponse(Object response, int id)
{
}
};
}
\ No newline at end of file
package com.eros.framework.http.okhttp.callback;
import com.eros.framework.http.okhttp.OkHttpUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import okhttp3.Response;
/**
* Created by zhy on 15/12/15.
*/
public abstract class FileCallBack extends Callback<File>
{
/**
* 目标文件存储的文件夹路径
*/
private String destFileDir;
/**
* 目标文件存储的文件名
*/
private String destFileName;
public FileCallBack(String destFileDir, String destFileName)
{
this.destFileDir = destFileDir;
this.destFileName = destFileName;
}
@Override
public File parseNetworkResponse(Response response, int id) throws Exception
{
return saveFile(response,id);
}
public File saveFile(Response response,final int id) throws IOException
{
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try
{
is = response.body().byteStream();
final long total = response.body().contentLength();
long sum = 0;
File dir = new File(destFileDir);
if (!dir.exists())
{
dir.mkdirs();
}
File file = new File(dir, destFileName);
fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -1)
{
sum += len;
fos.write(buf, 0, len);
final long finalSum = sum;
OkHttpUtils.getInstance().getDelivery().execute(new Runnable()
{
@Override
public void run()
{
inProgress(finalSum * 1.0f / total,total,id);
}
});
}
fos.flush();
return file;
} finally
{
try
{
response.body().close();
if (is != null) is.close();
} catch (IOException e)
{
}
try
{
if (fos != null) fos.close();
} catch (IOException e)
{
}
}
}
}
package com.eros.framework.http.okhttp.callback;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import okhttp3.Response;
/**
* Created by JimGong on 2016/6/23.
*/
public abstract class GenericsCallback<T> extends Callback<T> {
IGenericsSerializator mGenericsSerializator;
public GenericsCallback(IGenericsSerializator serializator) {
mGenericsSerializator = serializator;
}
@Override
public T parseNetworkResponse(Response response, int id) throws IOException {
String string = response.body().string();
Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
if (entityClass == String.class) {
return (T) string;
}
T bean = mGenericsSerializator.transform(string, entityClass);
return bean;
}
}
package com.eros.framework.http.okhttp.callback;
/**
* Created by JimGong on 2016/6/23.
*/
public interface IGenericsSerializator {
<T> T transform(String response, Class<T> classOfT);
}
package com.eros.framework.http.okhttp.callback;
import java.io.IOException;
import okhttp3.Response;
/**
* Created by zhy on 15/12/14.
*/
public abstract class StringCallback extends Callback<String> {
@Override
public String parseNetworkResponse(Response response, int id) throws IOException {
return response.body().string();
}
}
package com.eros.framework.http.okhttp.cookie;
import com.eros.framework.http.okhttp.cookie.store.CookieStore;
import com.eros.framework.http.okhttp.utils.Exceptions;
import java.util.List;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
/**
* Created by zhy on 16/3/10.
*/
public class CookieJarImpl implements CookieJar
{
private CookieStore cookieStore;
public CookieJarImpl(CookieStore cookieStore)
{
if (cookieStore == null) Exceptions.illegalArgument("cookieStore can not be null.");
this.cookieStore = cookieStore;
}
@Override
public synchronized void saveFromResponse(HttpUrl url, List<Cookie> cookies)
{
cookieStore.add(url, cookies);
}
@Override
public synchronized List<Cookie> loadForRequest(HttpUrl url)
{
return cookieStore.get(url);
}
public CookieStore getCookieStore()
{
return cookieStore;
}
}
package com.eros.framework.http.okhttp.cookie.store;
import java.util.List;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
public interface CookieStore
{
void add(HttpUrl uri, List<Cookie> cookie);
List<Cookie> get(HttpUrl uri);
List<Cookie> getCookies();
boolean remove(HttpUrl uri, Cookie cookie);
boolean removeAll();
}
package com.eros.framework.http.okhttp.cookie.store;
/**
* Created by zhy on 16/3/10.
*/
public interface HasCookieStore
{
CookieStore getCookieStore();
}
package com.eros.framework.http.okhttp.cookie.store;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
/**
* Created by zhy on 16/3/10.
*/
public class MemoryCookieStore implements CookieStore
{
private final HashMap<String, List<Cookie>> allCookies = new HashMap<>();
@Override
public void add(HttpUrl url, List<Cookie> cookies)
{
List<Cookie> oldCookies = allCookies.get(url.host());
if (oldCookies != null)
{
Iterator<Cookie> itNew = cookies.iterator();
Iterator<Cookie> itOld = oldCookies.iterator();
while (itNew.hasNext())
{
String va = itNew.next().name();
while (va != null && itOld.hasNext())
{
String v = itOld.next().name();
if (v != null && va.equals(v))
{
itOld.remove();
}
}
}
oldCookies.addAll(cookies);
} else
{
allCookies.put(url.host(), cookies);
}
}
@Override
public List<Cookie> get(HttpUrl uri)
{
List<Cookie> cookies = allCookies.get(uri.host());
if (cookies == null)
{
cookies = new ArrayList<>();
allCookies.put(uri.host(), cookies);
}
return cookies;
}
@Override
public boolean removeAll()
{
allCookies.clear();
return true;
}
@Override
public List<Cookie> getCookies()
{
List<Cookie> cookies = new ArrayList<>();
Set<String> httpUrls = allCookies.keySet();
for (String url : httpUrls)
{
cookies.addAll(allCookies.get(url));
}
return cookies;
}
@Override
public boolean remove(HttpUrl uri, Cookie cookie)
{
List<Cookie> cookies = allCookies.get(uri.host());
if (cookie != null)
{
return cookies.remove(cookie);
}
return false;
}
}
package com.eros.framework.http.okhttp.cookie.store;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
/**
* <pre>
* OkHttpClient client = new OkHttpClient.Builder()
* .cookieJar(new JavaNetCookieJar(new CookieManager(
* new PersistentCookieStore(getApplicationContext()),
* CookiePolicy.ACCEPT_ALL))
* .build();
*
* </pre>
* <p/>
* from http://stackoverflow.com/questions/25461792/persistent-cookie-store-using-okhttp-2-on-android
* <p/>
* <br/>
* A persistent cookie store which implements the Apache HttpClient CookieStore interface.
* Cookies are stored and will persist on the user's device between application sessions since they
* are serialized and stored in SharedPreferences. Instances of this class are
* designed to be used with AsyncHttpClient#setCookieStore, but can also be used with a
* regular old apache HttpClient/HttpContext if you prefer.
*/
public class PersistentCookieStore implements CookieStore
{
private static final String LOG_TAG = "PersistentCookieStore";
private static final String COOKIE_PREFS = "CookiePrefsFile";
private static final String COOKIE_NAME_PREFIX = "cookie_";
private final HashMap<String, ConcurrentHashMap<String, Cookie>> cookies;
private final SharedPreferences cookiePrefs;
/**
* Construct a persistent cookie store.
*
* @param context Context to attach cookie store to
*/
public PersistentCookieStore(Context context)
{
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new HashMap<String, ConcurrentHashMap<String, Cookie>>();
// Load any previously stored cookies into the store
Map<String, ?> prefsMap = cookiePrefs.getAll();
for (Map.Entry<String, ?> entry : prefsMap.entrySet())
{
if (((String) entry.getValue()) != null && !((String) entry.getValue()).startsWith(COOKIE_NAME_PREFIX))
{
String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
for (String name : cookieNames)
{
String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
if (encodedCookie != null)
{
Cookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null)
{
if (!cookies.containsKey(entry.getKey()))
cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
cookies.get(entry.getKey()).put(name, decodedCookie);
}
}
}
}
}
}
protected void add(HttpUrl uri, Cookie cookie)
{
String name = getCookieToken(cookie);
if (cookie.persistent())
{
if (!cookies.containsKey(uri.host()))
{
cookies.put(uri.host(), new ConcurrentHashMap<String, Cookie>());
}
cookies.get(uri.host()).put(name, cookie);
} else
{
if (cookies.containsKey(uri.host()))
{
cookies.get(uri.host()).remove(name);
}else
{
return ;
}
}
// Save cookie into persistent store
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(uri.host(), TextUtils.join(",", cookies.get(uri.host()).keySet()));
prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableHttpCookie(cookie)));
prefsWriter.apply();
}
protected String getCookieToken(Cookie cookie)
{
return cookie.name() + cookie.domain();
}
@Override
public void add(HttpUrl uri, List<Cookie> cookies)
{
for (Cookie cookie : cookies)
{
add(uri, cookie);
}
}
@Override
public List<Cookie> get(HttpUrl uri)
{
ArrayList<Cookie> ret = new ArrayList<Cookie>();
if (cookies.containsKey(uri.host()))
{
Collection<Cookie> cookies = this.cookies.get(uri.host()).values();
for (Cookie cookie : cookies)
{
if (isCookieExpired(cookie))
{
remove(uri, cookie);
} else
{
ret.add(cookie);
}
}
}
return ret;
}
private static boolean isCookieExpired(Cookie cookie)
{
return cookie.expiresAt() < System.currentTimeMillis();
}
@Override
public boolean removeAll()
{
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.clear();
prefsWriter.apply();
cookies.clear();
return true;
}
@Override
public boolean remove(HttpUrl uri, Cookie cookie)
{
String name = getCookieToken(cookie);
if (cookies.containsKey(uri.host()) && cookies.get(uri.host()).containsKey(name))
{
cookies.get(uri.host()).remove(name);
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
if (cookiePrefs.contains(COOKIE_NAME_PREFIX + name))
{
prefsWriter.remove(COOKIE_NAME_PREFIX + name);
}
prefsWriter.putString(uri.host(), TextUtils.join(",", cookies.get(uri.host()).keySet()));
prefsWriter.apply();
return true;
} else
{
return false;
}
}
@Override
public List<Cookie> getCookies()
{
ArrayList<Cookie> ret = new ArrayList<Cookie>();
for (String key : cookies.keySet())
ret.addAll(cookies.get(key).values());
return ret;
}
protected String encodeCookie(SerializableHttpCookie cookie)
{
if (cookie == null)
return null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
try
{
ObjectOutputStream outputStream = new ObjectOutputStream(os);
outputStream.writeObject(cookie);
} catch (IOException e)
{
Log.d(LOG_TAG, "IOException in encodeCookie", e);
return null;
}
return byteArrayToHexString(os.toByteArray());
}
protected Cookie decodeCookie(String cookieString)
{
byte[] bytes = hexStringToByteArray(cookieString);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
Cookie cookie = null;
try
{
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
cookie = ((SerializableHttpCookie) objectInputStream.readObject()).getCookie();
} catch (IOException e)
{
Log.d(LOG_TAG, "IOException in decodeCookie", e);
} catch (ClassNotFoundException e)
{
Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
}
return cookie;
}
/**
* Using some super basic byte array &lt;-&gt; hex conversions so we don't have to rely on any
* large Base64 libraries. Can be overridden if you like!
*
* @param bytes byte array to be converted
* @return string containing hex values
*/
protected String byteArrayToHexString(byte[] bytes)
{
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte element : bytes)
{
int v = element & 0xff;
if (v < 16)
{
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase(Locale.US);
}
/**
* Converts hex values from strings to byte arra
*
* @param hexString string of hex-encoded values
* @return decoded byte array
*/
protected byte[] hexStringToByteArray(String hexString)
{
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2)
{
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
}
return data;
}
}
package com.eros.framework.http.okhttp.cookie.store;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import okhttp3.Cookie;
/**
* from http://stackoverflow.com/questions/25461792/persistent-cookie-store-using-okhttp-2-on-android
* and<br/>
* http://www.geebr.com/post/okHttp3%E4%B9%8BCookies%E7%AE%A1%E7%90%86%E5%8F%8A%E6%8C%81%E4%B9%85%E5%8C%96
*/
public class SerializableHttpCookie implements Serializable
{
private static final long serialVersionUID = 6374381323722046732L;
private transient final Cookie cookie;
private transient Cookie clientCookie;
public SerializableHttpCookie(Cookie cookie)
{
this.cookie = cookie;
}
public Cookie getCookie()
{
Cookie bestCookie = cookie;
if (clientCookie != null)
{
bestCookie = clientCookie;
}
return bestCookie;
}
private void writeObject(ObjectOutputStream out) throws IOException
{
out.writeObject(cookie.name());
out.writeObject(cookie.value());
out.writeLong(cookie.expiresAt());
out.writeObject(cookie.domain());
out.writeObject(cookie.path());
out.writeBoolean(cookie.secure());
out.writeBoolean(cookie.httpOnly());
out.writeBoolean(cookie.hostOnly());
out.writeBoolean(cookie.persistent());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
String name = (String) in.readObject();
String value = (String) in.readObject();
long expiresAt = in.readLong();
String domain = (String) in.readObject();
String path = (String) in.readObject();
boolean secure = in.readBoolean();
boolean httpOnly = in.readBoolean();
boolean hostOnly = in.readBoolean();
boolean persistent = in.readBoolean();
Cookie.Builder builder = new Cookie.Builder();
builder = builder.name(name);
builder = builder.value(value);
builder = builder.expiresAt(expiresAt);
builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain);
builder = builder.path(path);
builder = secure ? builder.secure() : builder;
builder = httpOnly ? builder.httpOnly() : builder;
clientCookie = builder.build();
}
}
\ No newline at end of file
package com.eros.framework.http.okhttp.exception;
/**
* Created by Carry on 2017/9/21.
*/
public class CancelException extends Exception {
private String mErrosMeeage;
public CancelException(String mErrosMeeage) {
this.mErrosMeeage = mErrosMeeage;
}
public CancelException() {
}
public String getmErrosMeeage() {
return mErrosMeeage;
}
public void setmErrosMeeage(String mErrosMeeage) {
this.mErrosMeeage = mErrosMeeage;
}
}
package com.eros.framework.http.okhttp.exception;
/**
* Created by Carry on 2017/9/21.
*/
public class HttpException extends Exception {
private int mErrorCode;
private String mErrorMessage;
public HttpException(int mErrorCode, String mErrorMessage) {
this.mErrorCode = mErrorCode;
this.mErrorMessage = mErrorMessage;
}
public HttpException() {
}
public int getmErrorCode() {
return mErrorCode;
}
public void setmErrorCode(int mErrorCode) {
this.mErrorCode = mErrorCode;
}
public String getmErrorMessage() {
return mErrorMessage;
}
public void setmErrorMessage(String mErrorMessage) {
this.mErrorMessage = mErrorMessage;
}
}
package com.eros.framework.http.okhttp.exception;
/**
* Created by Carry on 2017/10/24.
*/
public class IrregularUrlException extends Exception {
private String mErrosMeeage;
public IrregularUrlException(String mErrosMeeage) {
this.mErrosMeeage = mErrosMeeage;
}
public IrregularUrlException() {
}
public String getmErrosMeeage() {
return mErrosMeeage;
}
public void setmErrosMeeage(String mErrosMeeage) {
this.mErrosMeeage = mErrosMeeage;
}
}
package com.eros.framework.http.okhttp.https;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
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;
/**
* Created by zhy on 15/12/14.
*/
public class HttpsUtils
{
public static class SSLParams
{
public SSLSocketFactory sSLSocketFactory;
public X509TrustManager trustManager;
}
public static SSLParams getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password)
{
SSLParams sslParams = new SSLParams();
try
{
TrustManager[] trustManagers = prepareTrustManager(certificates);
KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
SSLContext sslContext = SSLContext.getInstance("TLS");
X509TrustManager trustManager = null;
if (trustManagers != null)
{
trustManager = new MyTrustManager(chooseTrustManager(trustManagers));
} else
{
trustManager = new UnSafeTrustManager();
}
sslContext.init(keyManagers, new TrustManager[]{trustManager},null);
sslParams.sSLSocketFactory = sslContext.getSocketFactory();
sslParams.trustManager = trustManager;
return sslParams;
} catch (NoSuchAlgorithmException e)
{
throw new AssertionError(e);
} catch (KeyManagementException e)
{
throw new AssertionError(e);
} catch (KeyStoreException e)
{
throw new AssertionError(e);
}
}
private class UnSafeHostnameVerifier implements HostnameVerifier
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
}
private static class UnSafeTrustManager implements 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[]{};
}
}
private static TrustManager[] prepareTrustManager(InputStream... certificates)
{
if (certificates == null || certificates.length <= 0) return null;
try
{
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
int index = 0;
for (InputStream certificate : certificates)
{
String certificateAlias = Integer.toString(index++);
keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
try
{
if (certificate != null)
certificate.close();
} catch (IOException e)
{
}
}
TrustManagerFactory trustManagerFactory = null;
trustManagerFactory = TrustManagerFactory.
getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
return trustManagers;
} catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
} catch (CertificateException e)
{
e.printStackTrace();
} catch (KeyStoreException e)
{
e.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password)
{
try
{
if (bksFile == null || password == null) return null;
KeyStore clientKeyStore = KeyStore.getInstance("BKS");
clientKeyStore.load(bksFile, password.toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(clientKeyStore, password.toCharArray());
return keyManagerFactory.getKeyManagers();
} catch (KeyStoreException e)
{
e.printStackTrace();
} catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
} catch (UnrecoverableKeyException e)
{
e.printStackTrace();
} catch (CertificateException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers)
{
for (TrustManager trustManager : trustManagers)
{
if (trustManager instanceof X509TrustManager)
{
return (X509TrustManager) trustManager;
}
}
return null;
}
private static class MyTrustManager implements X509TrustManager
{
private X509TrustManager defaultTrustManager;
private X509TrustManager localTrustManager;
public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException
{
TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
var4.init((KeyStore) null);
defaultTrustManager = chooseTrustManager(var4.getTrustManagers());
this.localTrustManager = localTrustManager;
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException
{
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException
{
try
{
defaultTrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException ce)
{
localTrustManager.checkServerTrusted(chain, authType);
}
}
@Override
public X509Certificate[] getAcceptedIssuers()
{
return new X509Certificate[0];
}
}
}
package com.eros.framework.http.okhttp.log;
import android.text.TextUtils;
import android.util.Log;
import java.io.IOException;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
/**
* Created by zhy on 16/3/1.
*/
public class LoggerInterceptor implements Interceptor
{
public static final String TAG = "OkHttpUtils";
private String tag;
private boolean showResponse;
public LoggerInterceptor(String tag, boolean showResponse)
{
if (TextUtils.isEmpty(tag))
{
tag = TAG;
}
this.showResponse = showResponse;
this.tag = tag;
}
public LoggerInterceptor(String tag)
{
this(tag, false);
}
@Override
public Response intercept(Chain chain) throws IOException
{
Request request = chain.request();
logForRequest(request);
Response response = chain.proceed(request);
return logForResponse(response);
}
private Response logForResponse(Response response)
{
try
{
//===>response log
Log.e(tag, "========response'log=======");
Response.Builder builder = response.newBuilder();
Response clone = builder.build();
Log.e(tag, "url : " + clone.request().url());
Log.e(tag, "code : " + clone.code());
Log.e(tag, "protocol : " + clone.protocol());
if (!TextUtils.isEmpty(clone.message()))
Log.e(tag, "message : " + clone.message());
if (showResponse)
{
ResponseBody body = clone.body();
if (body != null)
{
MediaType mediaType = body.contentType();
if (mediaType != null)
{
Log.e(tag, "responseBody's contentType : " + mediaType.toString());
if (isText(mediaType))
{
String resp = body.string();
Log.e(tag, "responseBody's content : " + resp);
body = ResponseBody.create(mediaType, resp);
return response.newBuilder().body(body).build();
} else
{
Log.e(tag, "responseBody's content : " + " maybe [file part] , too large too print , ignored!");
}
}
}
}
Log.e(tag, "========response'log=======end");
} catch (Exception e)
{
// e.printStackTrace();
}
return response;
}
private void logForRequest(Request request)
{
try
{
String url = request.url().toString();
Headers headers = request.headers();
Log.e(tag, "========request'log=======");
Log.e(tag, "method : " + request.method());
Log.e(tag, "url : " + url);
if (headers != null && headers.size() > 0)
{
Log.e(tag, "headers : " + headers.toString());
}
RequestBody requestBody = request.body();
if (requestBody != null)
{
MediaType mediaType = requestBody.contentType();
if (mediaType != null)
{
Log.e(tag, "requestBody's contentType : " + mediaType.toString());
if (isText(mediaType))
{
Log.e(tag, "requestBody's content : " + bodyToString(request));
} else
{
Log.e(tag, "requestBody's content : " + " maybe [file part] , too large too print , ignored!");
}
}
}
Log.e(tag, "========request'log=======end");
} catch (Exception e)
{
// e.printStackTrace();
}
}
private boolean isText(MediaType mediaType)
{
if (mediaType.type() != null && mediaType.type().equals("text"))
{
return true;
}
if (mediaType.subtype() != null)
{
if (mediaType.subtype().equals("json") ||
mediaType.subtype().equals("xml") ||
mediaType.subtype().equals("html") ||
mediaType.subtype().equals("webviewhtml")
)
return true;
}
return false;
}
private String bodyToString(final Request request)
{
try
{
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
return buffer.readUtf8();
} catch (final IOException e)
{
return "something error when show requestBody.";
}
}
}
package com.eros.framework.http.okhttp.request;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;
/**
* Decorates an OkHttp request body to count the number of bytes written when writing it. Can
* decorate any request body, but is most useful for tracking the upload progress of large
* multipart requests.
*
* @author Leo Nikkilä
*/
public class CountingRequestBody extends RequestBody
{
protected RequestBody delegate;
protected Listener listener;
protected CountingSink countingSink;
public CountingRequestBody(RequestBody delegate, Listener listener)
{
this.delegate = delegate;
this.listener = listener;
}
@Override
public MediaType contentType()
{
return delegate.contentType();
}
@Override
public long contentLength()
{
try
{
return delegate.contentLength();
} catch (IOException e)
{
e.printStackTrace();
}
return -1;
}
@Override
public void writeTo(BufferedSink sink) throws IOException
{
countingSink = new CountingSink(sink);
BufferedSink bufferedSink = Okio.buffer(countingSink);
delegate.writeTo(bufferedSink);
bufferedSink.flush();
}
protected final class CountingSink extends ForwardingSink
{
private long bytesWritten = 0;
public CountingSink(Sink delegate)
{
super(delegate);
}
@Override
public void write(Buffer source, long byteCount) throws IOException
{
super.write(source, byteCount);
bytesWritten += byteCount;
listener.onRequestProgress(bytesWritten, contentLength());
}
}
public static interface Listener
{
public void onRequestProgress(long bytesWritten, long contentLength);
}
}
\ No newline at end of file
package com.eros.framework.http.okhttp.request;
import java.util.Map;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
* Created by zhy on 15/12/14.
*/
public class GetRequest extends OkHttpRequest
{
public GetRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers,int id)
{
super(url, tag, params, headers,id);
}
@Override
protected RequestBody buildRequestBody()
{
return null;
}
@Override
protected Request buildRequest(RequestBody requestBody)
{
return builder.get().build();
}
}
package com.eros.framework.http.okhttp.request;
import com.eros.framework.http.okhttp.callback.Callback;
import com.eros.framework.http.okhttp.utils.Exceptions;
import java.util.Map;
import okhttp3.Headers;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
* Created by zhy on 15/11/6.
*/
public abstract class OkHttpRequest
{
protected String url;
protected Object tag;
protected Map<String, String> params;
protected Map<String, String> headers;
protected int id;
protected Request.Builder builder = new Request.Builder();
protected OkHttpRequest(String url, Object tag,
Map<String, String> params, Map<String, String> headers,int id)
{
this.url = url;
this.tag = tag;
this.params = params;
this.headers = headers;
this.id = id ;
if (url == null)
{
Exceptions.illegalArgument("url can not be null.");
}
initBuilder();
}
/**
* 初始化一些基本参数 url , tag , headers
*/
private void initBuilder()
{
builder.url(url).tag(tag);
appendHeaders();
}
protected abstract RequestBody buildRequestBody();
protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
{
return requestBody;
}
protected abstract Request buildRequest(RequestBody requestBody);
public RequestCall build()
{
return new RequestCall(this);
}
public Request generateRequest(Callback callback)
{
RequestBody requestBody = buildRequestBody();
RequestBody wrappedRequestBody = wrapRequestBody(requestBody, callback);
Request request = buildRequest(wrappedRequestBody);
return request;
}
protected void appendHeaders()
{
Headers.Builder headerBuilder = new Headers.Builder();
if (headers == null || headers.isEmpty()) return;
for (String key : headers.keySet())
{
headerBuilder.add(key, headers.get(key));
}
builder.headers(headerBuilder.build());
}
public int getId()
{
return id ;
}
}
package com.eros.framework.http.okhttp.request;
import android.text.TextUtils;
import com.eros.framework.http.okhttp.OkHttpUtils;
import com.eros.framework.http.okhttp.utils.Exceptions;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.internal.http.HttpMethod;
/**
* Created by zhy on 16/2/23.
*/
public class OtherRequest extends OkHttpRequest
{
private static MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8");
private RequestBody requestBody;
private String method;
private String content;
public OtherRequest(RequestBody requestBody, String content, String method, String url, Object tag, Map<String, String> params, Map<String, String> headers,int id)
{
super(url, tag, params, headers,id);
this.requestBody = requestBody;
this.method = method;
this.content = content;
}
@Override
protected RequestBody buildRequestBody()
{
if (requestBody == null && TextUtils.isEmpty(content) && HttpMethod.requiresRequestBody(method))
{
Exceptions.illegalArgument("requestBody and content can not be null in method:" + method);
}
if (requestBody == null && !TextUtils.isEmpty(content))
{
requestBody = RequestBody.create(MEDIA_TYPE_PLAIN, content);
}
return requestBody;
}
@Override
protected Request buildRequest(RequestBody requestBody)
{
if (method.equals(OkHttpUtils.METHOD.PUT))
{
builder.put(requestBody);
} else if (method.equals(OkHttpUtils.METHOD.DELETE))
{
if (requestBody == null)
builder.delete();
else
builder.delete(requestBody);
} else if (method.equals(OkHttpUtils.METHOD.HEAD))
{
builder.head();
} else if (method.equals(OkHttpUtils.METHOD.PATCH))
{
builder.patch(requestBody);
}
return builder.build();
}
}
package com.eros.framework.http.okhttp.request;
import com.eros.framework.http.okhttp.OkHttpUtils;
import com.eros.framework.http.okhttp.callback.Callback;
import com.eros.framework.http.okhttp.utils.Exceptions;
import java.io.File;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
* Created by zhy on 15/12/14.
*/
public class PostFileRequest extends OkHttpRequest
{
private static MediaType MEDIA_TYPE_STREAM = MediaType.parse("application/octet-stream");
private File file;
private MediaType mediaType;
public PostFileRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, File file, MediaType mediaType,int id)
{
super(url, tag, params, headers,id);
this.file = file;
this.mediaType = mediaType;
if (this.file == null)
{
Exceptions.illegalArgument("the file can not be null !");
}
if (this.mediaType == null)
{
this.mediaType = MEDIA_TYPE_STREAM;
}
}
@Override
protected RequestBody buildRequestBody()
{
return RequestBody.create(mediaType, file);
}
@Override
protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
{
if (callback == null) return requestBody;
CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener()
{
@Override
public void onRequestProgress(final long bytesWritten, final long contentLength)
{
OkHttpUtils.getInstance().getDelivery().execute(new Runnable()
{
@Override
public void run()
{
callback.inProgress(bytesWritten * 1.0f / contentLength,contentLength,id);
}
});
}
});
return countingRequestBody;
}
@Override
protected Request buildRequest(RequestBody requestBody)
{
return builder.post(requestBody).build();
}
}
package com.eros.framework.http.okhttp.request;
import com.eros.framework.http.okhttp.OkHttpUtils;
import com.eros.framework.http.okhttp.builder.PostFormBuilder;
import com.eros.framework.http.okhttp.callback.Callback;
import java.io.UnsupportedEncodingException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
* Created by zhy on 15/12/14.
*/
public class PostFormRequest extends OkHttpRequest
{
private List<PostFormBuilder.FileInput> files;
public PostFormRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, List<PostFormBuilder.FileInput> files, int id)
{
super(url, tag, params, headers,id);
this.files = files;
}
@Override
protected RequestBody buildRequestBody()
{
if (files == null || files.isEmpty())
{
FormBody.Builder builder = new FormBody.Builder();
addParams(builder);
FormBody formBody = builder.build();
return formBody;
} else
{
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
addParams(builder);
for (int i = 0; i < files.size(); i++)
{
PostFormBuilder.FileInput fileInput = files.get(i);
RequestBody fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileInput.filename)), fileInput.file);
builder.addFormDataPart(fileInput.key, fileInput.filename, fileBody);
}
return builder.build();
}
}
@Override
protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
{
if (callback == null) return requestBody;
CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener()
{
@Override
public void onRequestProgress(final long bytesWritten, final long contentLength)
{
OkHttpUtils.getInstance().getDelivery().execute(new Runnable()
{
@Override
public void run()
{
callback.inProgress(bytesWritten * 1.0f / contentLength,contentLength,id);
}
});
}
});
return countingRequestBody;
}
@Override
protected Request buildRequest(RequestBody requestBody)
{
return builder.post(requestBody).build();
}
private String guessMimeType(String path)
{
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String contentTypeFor = null;
try
{
contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8"));
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
if (contentTypeFor == null)
{
contentTypeFor = "application/octet-stream";
}
return contentTypeFor;
}
private void addParams(MultipartBody.Builder builder)
{
if (params != null && !params.isEmpty())
{
for (String key : params.keySet())
{
builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
RequestBody.create(null, params.get(key)));
}
}
}
private void addParams(FormBody.Builder builder)
{
if (params != null)
{
for (String key : params.keySet())
{
builder.add(key, params.get(key));
}
}
}
}
package com.eros.framework.http.okhttp.request;
import com.eros.framework.http.okhttp.utils.Exceptions;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
* Created by zhy on 15/12/14.
*/
public class PostStringRequest extends OkHttpRequest
{
private static MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8");
private String content;
private MediaType mediaType;
public PostStringRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, String content, MediaType mediaType,int id)
{
super(url, tag, params, headers,id);
this.content = content;
this.mediaType = mediaType;
if (this.content == null)
{
Exceptions.illegalArgument("the content can not be null !");
}
if (this.mediaType == null)
{
this.mediaType = MEDIA_TYPE_PLAIN;
}
}
@Override
protected RequestBody buildRequestBody()
{
return RequestBody.create(mediaType, content);
}
@Override
protected Request buildRequest( RequestBody requestBody)
{
return builder.post(requestBody).build();
}
}
package com.eros.framework.http.okhttp.request;
import com.eros.framework.http.okhttp.OkHttpUtils;
import com.eros.framework.http.okhttp.callback.Callback;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by zhy on 15/12/15.
* 对OkHttpRequest的封装,对外提供更多的接口:cancel(),readTimeOut()...
*/
public class RequestCall
{
private OkHttpRequest okHttpRequest;
private Request request;
private Call call;
private long readTimeOut;
private long writeTimeOut;
private long connTimeOut;
private OkHttpClient clone;
public RequestCall(OkHttpRequest request)
{
this.okHttpRequest = request;
}
public RequestCall readTimeOut(long readTimeOut)
{
this.readTimeOut = readTimeOut;
return this;
}
public RequestCall writeTimeOut(long writeTimeOut)
{
this.writeTimeOut = writeTimeOut;
return this;
}
public RequestCall connTimeOut(long connTimeOut)
{
this.connTimeOut = connTimeOut;
return this;
}
public Call buildCall(Callback callback)
{
request = generateRequest(callback);
if (readTimeOut > 0 || writeTimeOut > 0 || connTimeOut > 0)
{
readTimeOut = readTimeOut > 0 ? readTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
writeTimeOut = writeTimeOut > 0 ? writeTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
connTimeOut = connTimeOut > 0 ? connTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
clone = OkHttpUtils.getInstance().getOkHttpClient().newBuilder()
.readTimeout(readTimeOut, TimeUnit.MILLISECONDS)
.writeTimeout(writeTimeOut, TimeUnit.MILLISECONDS)
.connectTimeout(connTimeOut, TimeUnit.MILLISECONDS)
.build();
call = clone.newCall(request);
} else
{
call = OkHttpUtils.getInstance().getOkHttpClient().newCall(request);
}
return call;
}
private Request generateRequest(Callback callback)
{
return okHttpRequest.generateRequest(callback);
}
public void execute(Callback callback)
{
buildCall(callback);
if (callback != null)
{
callback.onBefore(request, getOkHttpRequest().getId());
}
OkHttpUtils.getInstance().execute(this, callback);
}
public Call getCall()
{
return call;
}
public Request getRequest()
{
return request;
}
public OkHttpRequest getOkHttpRequest()
{
return okHttpRequest;
}
public Response execute() throws IOException
{
buildCall(null);
return call.execute();
}
public void cancel()
{
if (call != null)
{
call.cancel();
}
}
}
package com.eros.framework.http.okhttp.utils;
/**
* Created by zhy on 15/12/14.
*/
public class Exceptions
{
public static void illegalArgument(String msg, Object... params)
{
throw new IllegalArgumentException(String.format(msg, params));
}
}
package com.eros.framework.http.okhttp.utils;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.InputStream;
import java.lang.reflect.Field;
/**
* Created by zhy on 15/11/6.
*/
public class ImageUtils
{
/**
* 根据InputStream获取图片实际的宽度和高度
*
* @param imageStream
* @return
*/
public static ImageSize getImageSize(InputStream imageStream)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(imageStream, null, options);
return new ImageSize(options.outWidth, options.outHeight);
}
public static class ImageSize
{
int width;
int height;
public ImageSize()
{
}
public ImageSize(int width, int height)
{
this.width = width;
this.height = height;
}
@Override
public String toString()
{
return "ImageSize{" +
"width=" + width +
", height=" + height +
'}';
}
}
public static int calculateInSampleSize(ImageSize srcSize, ImageSize targetSize)
{
// 源图片的宽度
int width = srcSize.width;
int height = srcSize.height;
int inSampleSize = 1;
int reqWidth = targetSize.width;
int reqHeight = targetSize.height;
if (width > reqWidth && height > reqHeight)
{
// 计算出实际宽度和目标宽度的比率
int widthRatio = Math.round((float) width / (float) reqWidth);
int heightRatio = Math.round((float) height / (float) reqHeight);
inSampleSize = Math.max(widthRatio, heightRatio);
}
return inSampleSize;
}
/**
* 根据ImageView获适当的压缩的宽和高
*
* @param view
* @return
*/
public static ImageSize getImageViewSize(View view)
{
ImageSize imageSize = new ImageSize();
imageSize.width = getExpectWidth(view);
imageSize.height = getExpectHeight(view);
return imageSize;
}
/**
* 根据view获得期望的高度
*
* @param view
* @return
*/
private static int getExpectHeight(View view)
{
int height = 0;
if (view == null) return 0;
final ViewGroup.LayoutParams params = view.getLayoutParams();
//如果是WRAP_CONTENT,此时图片还没加载,getWidth根本无效
if (params != null && params.height != ViewGroup.LayoutParams.WRAP_CONTENT)
{
height = view.getWidth(); // 获得实际的宽度
}
if (height <= 0 && params != null)
{
height = params.height; // 获得布局文件中的声明的宽度
}
if (height <= 0)
{
height = getImageViewFieldValue(view, "mMaxHeight");// 获得设置的最大的宽度
}
//如果宽度还是没有获取到,憋大招,使用屏幕的宽度
if (height <= 0)
{
DisplayMetrics displayMetrics = view.getContext().getResources()
.getDisplayMetrics();
height = displayMetrics.heightPixels;
}
return height;
}
/**
* 根据view获得期望的宽度
*
* @param view
* @return
*/
private static int getExpectWidth(View view)
{
int width = 0;
if (view == null) return 0;
final ViewGroup.LayoutParams params = view.getLayoutParams();
//如果是WRAP_CONTENT,此时图片还没加载,getWidth根本无效
if (params != null && params.width != ViewGroup.LayoutParams.WRAP_CONTENT)
{
width = view.getWidth(); // 获得实际的宽度
}
if (width <= 0 && params != null)
{
width = params.width; // 获得布局文件中的声明的宽度
}
if (width <= 0)
{
width = getImageViewFieldValue(view, "mMaxWidth");// 获得设置的最大的宽度
}
//如果宽度还是没有获取到,憋大招,使用屏幕的宽度
if (width <= 0)
{
DisplayMetrics displayMetrics = view.getContext().getResources()
.getDisplayMetrics();
width = displayMetrics.widthPixels;
}
return width;
}
/**
* 通过反射获取imageview的某个属性值
*
* @param object
* @param fieldName
* @return
*/
private static int getImageViewFieldValue(Object object, String fieldName)
{
int value = 0;
try
{
Field field = ImageView.class.getDeclaredField(fieldName);
field.setAccessible(true);
int fieldValue = field.getInt(object);
if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE)
{
value = fieldValue;
}
} catch (Exception e)
{
}
return value;
}
}
package com.eros.framework.http.okhttp.utils;
import android.util.Log;
/**
* Created by zhy on 15/11/6.
*/
public class L
{
private static boolean debug = false;
public static void e(String msg)
{
if (debug)
{
Log.e("OkHttp", msg);
}
}
}
/*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.eros.framework.http.okhttp.utils;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class Platform
{
private static final Platform PLATFORM = findPlatform();
public static Platform get()
{
L.e(PLATFORM.getClass().toString());
return PLATFORM;
}
private static Platform findPlatform()
{
try
{
Class.forName("android.os.Build");
if (Build.VERSION.SDK_INT != 0)
{
return new Android();
}
} catch (ClassNotFoundException ignored)
{
}
return new Platform();
}
public Executor defaultCallbackExecutor()
{
return Executors.newCachedThreadPool();
}
public void execute(Runnable runnable)
{
defaultCallbackExecutor().execute(runnable);
}
static class Android extends Platform
{
@Override
public Executor defaultCallbackExecutor()
{
return new MainThreadExecutor();
}
static class MainThreadExecutor implements Executor
{
private final Handler handler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable r)
{
handler.post(r);
}
}
}
}
package com.eros.framework.manager;
import java.util.HashMap;
/**
* Created by Carry on 2017/8/7.
*/
public abstract class Manager {
public void init() {
}
public HashMap<String, HashMap<String, String>> getComponentsAndModules() {
return null;
}
}
package com.eros.framework.manager;
import android.text.TextUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Carry on 2017/8/7. manager instance factory
*/
public class ManagerFactory {
private static Map<String, Manager> mInstances = new HashMap();
public static <T extends Manager> T getManagerService(Class<T> flag) {
if (flag == null) throw new IllegalArgumentException("error flag");
if (mInstances.get(flag.getName()) == null) {
try {
mInstances.put(flag.getName(), flag.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
return (T) mInstances.get(flag.getName());
}
public static <T extends Manager> T getManagerService(String clazzName) {
if (TextUtils.isEmpty(clazzName)) throw new IllegalArgumentException("error flag");
if (mInstances.get(clazzName) == null) {
try {
Class instanse = Class.forName(clazzName);
mInstances.put(clazzName, (Manager) instanse.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
return (T) mInstances.get(clazzName);
}
}
package com.eros.framework.manager;
import android.content.Context;
import com.eros.framework.adapter.DefaultStorageAdapter;
import java.io.Serializable;
/**
* Created by Carry on 2017/8/21.
*/
public class StorageManager extends Manager {
public boolean setData(Context context, String key, Serializable value) {
return DefaultStorageAdapter.getInstance().setData(context, key, value);
}
public String getData(Context context, String key) {
return DefaultStorageAdapter.getInstance().getData(context, key, String.class);
}
public boolean deleteData(Context context, String key) {
String result = getData(context, key);
if (result == null) {
return false;
}
return DefaultStorageAdapter.getInstance().deleteData(context, key);
}
public boolean removeData(Context context) {
return DefaultStorageAdapter.getInstance().removeData(context);
}
}
package com.eros.framework.manager.impl;
import android.content.Context;
import android.os.Environment;
import com.eros.framework.manager.Manager;
import com.eros.framework.utils.ZipUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Created by Carry on 2017/8/7.
*/
public class FileManager extends Manager{
public static final String BASE_DIR = "benmu";
public static final String BUNDLE_NAME = "bundle.zip";
public static final String TEMP_BUNDLE_NAME = "temp_pages.zip";
public static final String JS_BUNDLE = "/.bundle";
public static final String JS_TEMP_REPERTORY = "/.temp_bundle";
public static final String PATCH_NAME = "patch.zip";
public static final String TEMP_NEW_BUNDLE_NAME = "newPages.zip";
public static final String TEMP_FILE = "/.temp_file";
public static final String PAGES_DIR = JS_BUNDLE + "/bundle/pages";
public static final String ICONFONT_DIR = JS_BUNDLE + "/bundle/iconfont";
public static final String BASEJS_DIR = JS_BUNDLE + "/bundle/config";
public static final String MEDIATOR_DIR = JS_BUNDLE + "/bundle/mediator";
public static boolean isSDCardAvailable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public static File getTempFilePath(Context context) {
return getPath(TEMP_FILE, context);
}
private static File getPath(String fileName, Context context) {
File file = new File(getBasePath(context), fileName);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
public static File getBasePath(Context context) {
File appDir = null;
if (isSDCardAvailable()) {
appDir = new File(context.getExternalFilesDir(null), BASE_DIR);
}
if (appDir == null) {
appDir = new File(context.getFilesDir(), BASE_DIR);
}
if (!appDir.exists()) {
appDir.mkdirs();
}
return appDir;
}
public static File getAppPath(String path, Context context) {
File appFile = new File(getBasePath(context), path);
if (!appFile.exists()) {
appFile.mkdirs();
}
return appFile;
}
public static File getBundleDir(Context context) {
return getAppPath(JS_BUNDLE, context);
}
public static File getPagesDir(Context context) {
return getAppPath(PAGES_DIR, context);
}
public static File getIconDir(Context context) {
return getAppPath(ICONFONT_DIR, context);
}
public static File getBaseJsDir(Context context) {
return getAppPath(BASEJS_DIR, context);
}
public static File getMediatorDir(Context context) {
return getAppPath(MEDIATOR_DIR, context);
}
public static File getTempBundleDir(Context context) {
return getAppPath(JS_TEMP_REPERTORY, context);
}
public static File getPathBundleDir(Context context, String path) {
return new File(getBundleDir(context), path);
}
public static boolean isExists(String path) {
File file = new File(path);
return file.exists();
}
public static String loadJs(String path) {
String str = null;
try {
FileInputStream inputStream = new FileInputStream(new File(path));
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
str = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public static byte[] loadLocalFile(String path) {
try {
FileInputStream inputStream = new FileInputStream(new File(path));
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
return buffer;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static boolean isEmptyDir(File file) {
if (file != null && file.isDirectory()) {
File[] files = file.listFiles();
return files.length == 0;
}
throw new RuntimeException("dir is null or not a directory");
}
public static File getFileInDir(File file, int index) {
if (file != null && file.isDirectory()) {
File[] files = file.listFiles();
if (files.length > index) {
return files[index];
}
return null;
}
return null;
}
public static void unZip(File fromFile, File toFile) {
if (toFile == null || fromFile == null) {
return;
}
try {
ZipUtil.unZip(fromFile.getAbsolutePath(), toFile.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] extractZip(File zipFile, String entryName) {
ZipFile zf = null;
ZipEntry ze = null;
byte[] buffer = null;
try {
zf = new ZipFile(zipFile);
ze = zf.getEntry(entryName);
InputStream in = zf.getInputStream(ze);
int size = in.available();
buffer = new byte[size];
in.read(buffer);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
public static void clearDir(File dir) {
if (dir.isFile()) {
dir.delete();
return;
}
if (dir.isDirectory()) {
File[] childFile = dir.listFiles();
if (childFile == null || childFile.length == 0) {
dir.delete();
return;
}
for (File f : childFile) {
clearDir(f);
}
dir.delete();
}
}
public static void deleteFile(File file) {
if (file != null && file.exists()) {
file.delete();
}
}
public static void renameFile(File path, String oldname, String newname) {
if (!oldname.equals(newname)) {//新的文件名和以前文件名不同时,才有必要进行重命名
File oldfile = new File(path, oldname);
File newfile = new File(path, newname);
if (!oldfile.exists()) {
return;//重命名文件不存在
}
if (newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名
System.out.println(newname + "已经存在!");
else {
oldfile.renameTo(newfile);
}
} else {
System.out.println("新文件名和旧文件名相同...");
}
}
}
package com.eros.framework.manager.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eros.framework.manager.Manager;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
/**
* Created by Carry on 2017/8/7. json parse
*/
public class ParseManager extends Manager {
public <T> T parseObject(String jsonString, Class<T> clazz) {
try {
return JSON.parseObject(jsonString, clazz);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String toJsonString(Object object) {
return JSON.toJSONString(object);
}
public JSONObject parseObject(String jsonString) {
try {
return JSON.parseObject(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Object parse(String s) {
try {
return JSON.parse(s);
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
public Object parse(String s, Class clazz) {
try {
return JSON.parseObject(s, clazz);
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
public HashMap<String, String> parseFetchParams(String data) {
HashMap<String, String> result = new HashMap<String, String>();
JSONObject jsonObj = JSONObject.parseObject(data);
Set<String> keys = jsonObj.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String str = it.next();
result.put(str, jsonObj.get(str).toString());
}
return result;
}
}
package com.eros.framework.manager.impl;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import com.eros.framework.manager.Manager;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Carry on 2017/8/21.
*/
public class PermissionManager extends Manager{
public static final int RUNTIME_PERMISSION = 23;
private PermissionListener mListenner;
public interface PermissionListener {
void onPermissionsGranted(List<String> perms);
void onPermissionsDenied(List<String> perms);
void onPermissionRequestRejected();
}
public boolean hasPermissions(Context context, String... perms) {
for (String perm : perms) {
boolean hasPerm = (ContextCompat.checkSelfPermission(context, perm) == PackageManager
.PERMISSION_GRANTED);
if (!hasPerm) {
return false;
}
}
return true;
}
public void requestPermissions(Object object, PermissionListener listener,
final String... perms) {
this.mListenner = listener;
executePermissionsRequest(object, perms, RUNTIME_PERMISSION);
}
public void onRequestPermissionsResult(Object object, int
requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == RUNTIME_PERMISSION) {
checkCallingObjectSuitability(object);
// Make a collection of granted and denied permissions from the request.
ArrayList<String> granted = new ArrayList<>();
ArrayList<String> denied = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
String perm = permissions[i];
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
granted.add(perm);
} else {
denied.add(perm);
}
}
if (mListenner == null) return;
// Report granted permissions, if any.
if (!granted.isEmpty()) {
// Notify callbacks
mListenner.onPermissionsGranted(granted);
}
// Report denied permissions, if any.
if (!denied.isEmpty()) {
mListenner.onPermissionsDenied(denied);
}
}
}
private boolean shouldShowRequestPermissionRationale(Object object, String perm) {
if (object instanceof Activity) {
return ActivityCompat.shouldShowRequestPermissionRationale((Activity) object, perm);
} else if (object instanceof Fragment) {
return ((Fragment) object).shouldShowRequestPermissionRationale(perm);
} else {
return false;
}
}
private void executePermissionsRequest(Object object, String[] perms, int requestCode) {
checkCallingObjectSuitability(object);
if (object instanceof Activity) {
ActivityCompat.requestPermissions((Activity) object, perms, requestCode);
} else if (object instanceof Fragment) {
((Fragment) object).requestPermissions(perms, requestCode);
}
}
private Activity getActivity(Object object) {
if (object instanceof Activity) {
return ((Activity) object);
} else if (object instanceof Fragment) {
return ((Fragment) object).getActivity();
} else {
return null;
}
}
private void checkCallingObjectSuitability(Object object) {
// Make sure Object is an Activity or Fragment
if (!((object instanceof Fragment) || (object instanceof Activity))) {
throw new IllegalArgumentException("Caller must be an Activity or a Fragment.");
}
}
}
package com.eros.framework.manager.impl.dispatcher;
import com.eros.framework.manager.Manager;
import com.squareup.otto.Bus;
/**
* Created by Carry on 2017/8/7.
* event flow
*/
public class DispatchEventManager extends Manager {
private static Bus mBus;
public DispatchEventManager() {
if (mBus == null) {
mBus = new MainThreadBus();
}
}
public Bus getBus() {
return mBus;
}
}
package com.eros.framework.manager.impl.dispatcher;
import android.os.Handler;
import android.os.Looper;
import com.squareup.otto.Bus;
/**
* Created by Carry on 2017/5/21.
*/
public class MainThreadBus extends Bus {
private final Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public void post(final Object event) {
if (Looper.myLooper() == Looper.getMainLooper()) {
super.post(event);
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
MainThreadBus.super.post(event);
}
});
}
}
}
package com.eros.framework.model;
import android.content.Context;
import java.io.Serializable;
/**
* Created by liuyuanxiao on 18/4/9.
*/
public class BaseEventBean implements Serializable {
public Context context;
public String param;
public String type;
public String clazzName;
}
package com.eros.framework.model;
import java.io.Serializable;
/**
* Js 回调基础Bean
*/
public class BaseResultBean implements Serializable {
public int resCode;
public String msg;
public BaseResultBean(int resCode, String msg) {
this.resCode = resCode;
this.msg = msg;
}
public BaseResultBean() {
}
}
package com.eros.framework.model;
import java.io.Serializable;
/**
* Created by Carry on 2018/1/3.
* 基础js回调
*/
public class UniversalResultModule implements Serializable {
private String errorMsg;
private Object status;
private Object data;
public UniversalResultModule(String errorMsg, int status, Object data) {
this.errorMsg = errorMsg;
this.status = status;
this.data = data;
}
public UniversalResultModule() {
}
public static UniversalResultModule obtainSuccess(Object object) {
return new UniversalResultModule(null, 0
, object);
}
public static UniversalResultModule obtainFailed(String errorMsg) {
return new UniversalResultModule(errorMsg, 9, null);
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public Object getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
package com.eros.framework.module.glide;
import android.support.annotation.Nullable;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
public abstract class ImageRequestListener implements RequestListener, OnProgressListener {
private boolean mLoaded;
public ImageRequestListener() {
ProgressManager.addProgressListener(this);
}
@Override
public void onProgress(String imageUrl, long bytesRead, long totalBytes, boolean isDone,
Exception exception) {
if (!mLoaded) {
onLoading(imageUrl, bytesRead, totalBytes, isDone, exception);
}
}
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean
isFirstResource) {
mLoaded = true;
onFailed(e, model, target, isFirstResource);
return false;
}
@Override
public boolean onResourceReady(Object resource, Object model, Target target, DataSource
dataSource, boolean isFirstResource) {
mLoaded = true;
onReady(resource, model, target, dataSource, isFirstResource);
return false;
}
public abstract void onReady(Object resource, Object model, Target target, DataSource
dataSource, boolean isFirstResource);
public abstract void onFailed(GlideException e, Object model, Target target, boolean
isFirstResource);
public abstract void onLoading(String imageUrl, long bytesRead, long totalBytes, boolean isDone,
Exception exception);
}
package com.eros.framework.module.glide;
/**
* Created by sunfusheng on 2017/6/14.
*/
public interface OnProgressListener {
void onProgress(String imageUrl, long bytesRead, long totalBytes, boolean isDone,
Exception exception);
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment