From 54cfb3a728e3ba80ad72a9458c7344d894ee0dbb Mon Sep 17 00:00:00 2001 From: denghc Date: Tue, 6 Mar 2018 13:27:38 +0800 Subject: [PATCH 1/5] =?UTF-8?q?=E6=B7=BB=E5=8A=A0atlas=E5=AE=9E=E8=B7=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 +- app/build.gradle | 107 ++- app/dexPatchWraper.gradle | 118 +++ .../main/java/com/dhc/flyabbit/app/App.java | 53 ++ .../com/dhc/flyabbit/ui/MainFragment.java | 63 +- baselib/activitygroupcompat/.gitignore | 1 + baselib/activitygroupcompat/build.gradle | 33 + .../activitygroupcompat/proguard-rules.pro | 25 + .../src/main/AndroidManifest.xml | 5 + .../taobao/android/ActivityGroupDelegate.java | 271 ++++++ .../taobao/android/LocalActivityManager.java | 790 ++++++++++++++++++ .../src/main/res/values/strings.xml | 3 + baselib/imageloader/build.gradle | 25 +- .../glideloader/CustomCachingGlideModule.java | 14 +- baselib/library/build.gradle | 72 +- .../com/dhc/library/base/BaseApplication.java | 36 +- .../com/dhc/library/utils/ToolbarUtil.java | 2 +- .../java/com/dhc/library/utils/rx/RxUtil.java | 2 +- .../dhc/library/utils/string/Base64Utils.java | 15 +- baselib/uikit/build.gradle | 70 +- build.gradle | 40 +- girls/build.gradle | 33 +- girls/bundleBaseInfoFile.json | 4 + .../gank/debug/GirlsDebugActivity.java | 1 + .../flyabbit/gank/ui/adapter/GirlAdapter.java | 2 +- girls/src/main/release/AndroidManifest.xml | 2 +- gradle/wrapper/gradle-wrapper.properties | 4 +- home/build.gradle | 33 +- home/src/main/release/AndroidManifest.xml | 3 +- my/build.gradle | 29 +- my/src/main/release/AndroidManifest.xml | 2 +- settings.gradle | 6 +- version.gradle | 2 +- 33 files changed, 1677 insertions(+), 191 deletions(-) create mode 100644 app/dexPatchWraper.gradle create mode 100644 baselib/activitygroupcompat/.gitignore create mode 100644 baselib/activitygroupcompat/build.gradle create mode 100644 baselib/activitygroupcompat/proguard-rules.pro create mode 100644 baselib/activitygroupcompat/src/main/AndroidManifest.xml create mode 100644 baselib/activitygroupcompat/src/main/java/com/taobao/android/ActivityGroupDelegate.java create mode 100644 baselib/activitygroupcompat/src/main/java/com/taobao/android/LocalActivityManager.java create mode 100644 baselib/activitygroupcompat/src/main/res/values/strings.xml create mode 100644 girls/bundleBaseInfoFile.json diff --git a/.gitignore b/.gitignore index 32b3b28..a89f4bc 100644 --- a/.gitignore +++ b/.gitignore @@ -25,7 +25,7 @@ build/intermediates/incremental/packageDebugResources/merged.dir/ build/intermediates/incremental/packageDebugResources/stripped.dir/ build/intermediates/incremental/processDebugAndroidTestResources/ build/intermediates/incremental/processDebugResources/ -build/intermediates/jniLibs/ +build/intermediates/jniLibs build/intermediates/rs/ build/intermediates/shaders/ build/intermediates/tmp/ diff --git a/app/build.gradle b/app/build.gradle index 0ad4814..5c3cfea 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,5 +1,10 @@ apply plugin: 'com.android.application' +apply plugin: 'com.taobao.atlas' +apply plugin: 'com.taobao.atlas.dexpatch' +apply from: 'dexPatchWraper.gradle' + +def apVersion = getEnvValue("apVersion", ""); android { compileSdkVersion rootProject.ext.android.compileSdkVersion @@ -64,13 +69,13 @@ android { // } - compileOptions { - - sourceCompatibility JavaVersion.VERSION_1_8 - - targetCompatibility JavaVersion.VERSION_1_8 - - } +// compileOptions { +// +// sourceCompatibility JavaVersion.VERSION_1_8 +// +// targetCompatibility JavaVersion.VERSION_1_8 +// +// } dexOptions { jumboMode true //jenkins上使用有问题 @@ -79,34 +84,94 @@ android { } } +String getEnvValue(key, defValue) { + def val = System.getProperty(key); + if (null != val) { + return val; + } + val = System.getenv(key); + if (null != val) { + return val; + } + return defValue; +} + + + +atlas { + + atlasEnabled true + tBuildConfig { + autoStartBundles = ['com.dhc.flyabbit.gank'] //自启动bundle配置 + autoStartBundles = ['com.dhc.flyabbit.home'] //自启动bundle配置 + autoStartBundles = ['com.dhc.flyabbit.my'] //自启动bundle配置 +// outOfApkBundles = ['remotebundle'] +// preLaunch = 'com.taobao.demo.DemoPreLaunch' + classInject false +// dataBindingBundles = ['com.taobao.databindbundle'] + } + + manifestOptions { + addAtlasProxyComponents true + } + + + patchConfigs { + debug { + createTPatch true + } + } + + + buildTypes { + debug { + if (apVersion) { + baseApDependency "com.taobao.android.atlasdemo:AP-debug:${apVersion}@ap" + patchConfig patchConfigs.debug + } + } + } +} + + + + dependencies { - implementation fileTree(dir: 'libs', include: ['*.jar']) - androidTestImplementation 'com.android.support.test:runner:1.0.1' - androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' - testImplementation rootProject.ext.dependencies["junit"] + compile fileTree(include: ['*.jar'], dir: 'libs') + testCompile rootProject.ext.dependencies["junit"] provided rootProject.ext.dependencies["javax.annotation"] - debugImplementation rootProject.ext.dependencies["canary-debug"] - testImplementation rootProject.ext.dependencies["canary-test"] - releaseImplementation rootProject.ext.dependencies["canary-release"] + debugCompile rootProject.ext.dependencies["canary-debug"] + testCompile rootProject.ext.dependencies["canary-test"] + releaseCompile rootProject.ext.dependencies["canary-release"] //dagger2的apt注解 annotationProcessor rootProject.ext.dependencies["dagger-compiler"] //阿里的Arouter的注解 annotationProcessor rootProject.ext.dependencies["arouter-compiler"] + + compile(rootProject.ext.lib_atlas_core) { + transitive = true + } + + compile rootProject.ext.lib_atlas_update + //atlas if (isApp.toBoolean()) { - api(rootProject.ext.dependencies["homelib"]){ + compile(rootProject.ext.dependencies["homelib"]) { exclude module: 'library' } - api (rootProject.ext.dependencies["mylib"]){ + compile(rootProject.ext.dependencies["mylib"]) { exclude module: 'library' } - api (rootProject.ext.dependencies["girlslib"]){ + compile(rootProject.ext.dependencies["girlslib"]) { exclude module: 'library' } - api project(':library') + compile project(':library') } else { - api project(':my') - api project(':home') - api project(':girls') + bundleCompile project(':my') + bundleCompile project(':home') + bundleCompile project(':girls') + compile project(':library') +// providedCompile project(':girls') } + compile project(':activitygroupcompat') } diff --git a/app/dexPatchWraper.gradle b/app/dexPatchWraper.gradle new file mode 100644 index 0000000..e516094 --- /dev/null +++ b/app/dexPatchWraper.gradle @@ -0,0 +1,118 @@ +import groovy.json.JsonSlurper +import groovy.json.JsonOutput +import static Constants.* + + +/** + * Created by 种藏 on 2017/8/30. + * + * 1. 这个类只是对产物patches.json文件做个包装,用来模拟服务器控制dexPatch版本的逻辑,生成的产物是dexpatch-versionName.json + * + * 2. 正常开发情况,做dexPatch时,服务器会分配一个对应的dexPatchVersion。 + * 客户端比较dexPatchVersion来判断要不要做patch。 + * + * 3. 这里只是每次做dexPatch时,简单的将dexPatchVersion 加 1. + * + * 4. 具体字段含义,参考https://alibaba.github.io/atlas/update/dexpatch_use_guide.html + * + */ + +tasks.whenTaskAdded { task -> + if (task.name == "assembleDebug" || task.name == "assembleRelease") { + task.doLast { + wrapDexPatchFile(task.name.contains("Debug")) + } + } +// if (task.name == "clean") { +// task.doLast { cleanPatchVersion() } +// } +} + +class Constants { + static final ENCODE_UTF_8 = "UTF-8" + static final PATH_VERSION_FILE = "dexPatch.version" +} + +task tesetm << { + wrapDexPatchFile(true) +} + +def wrapDexPatchFile(boolean debug) { + + println "root project :${rootProject.projectDir.path}" + + def apVersion = getEnvValue("apVersion", "-1") + def versionName = getEnvValue("versionName", "-1") + if (apVersion == "-1" || versionName == "-1") { + println("jump dexPatch") + return + } + + if (apVersion != versionName) { + return + } + + + println "DexPatch wrap ,version $versionName" + + String path = rootProject.projectDir.path + "/app/build/outputs/tpatch-" + (debug ? "debug" : "release") + "/patchs.json" + String patchPath = path.replace('/', File.separator) + println "patchFile path :$patchPath" + + String fileContents = new File(patchPath).getText(ENCODE_UTF_8) + def patchConfig = new JsonSlurper().parseText(fileContents) + def updateInfo = patchConfig.patches[0] + updateInfo.dexPatch = true + def bundles = updateInfo.bundles + assert bundles instanceof List + def patchVersion = getPatchVersion() + bundles.each { + assert it instanceof Map + it.dexpatchVersion = patchVersion + it.isMainDex = it.mainBundle + it.remove("mainBundle") + if (it.isMainDex) { + println "=================>add empty main_dex dependency =============" + it.dependency=[] + } + } + //写回到最终的dexPatch产物文件中 + String wrapFilePath = "${rootProject.projectDir.path}/app/build/outputs/tpatch-" + (debug ? "debug" : "release") + "/dexpatch-${patchConfig.baseVersion}.json" + File wrapFile = new File(wrapFilePath.replace('/', File.separator)) + if (wrapFile.exists()) wrapFile.delete() + wrapFile.createNewFile() + def dexPatchJson = JsonOutput.toJson(patchConfig) + wrapFile.setText(dexPatchJson, ENCODE_UTF_8) +} + +//粗暴+1 +def getPatchVersion() { + File versionFile = new File(rootProject.projectDir.path, PATH_VERSION_FILE) + if (!versionFile.exists()) versionFile.createNewFile() + String versionStr = versionFile.getText(ENCODE_UTF_8) + if (null == versionStr || versionStr.isEmpty()) { + versionStr = "1" + } + String nextVersion = String.valueOf(Integer.valueOf(versionStr) + 1) + versionFile.setText(nextVersion, ENCODE_UTF_8) + return versionStr +} + +def cleanPatchVersion() { + File versionFile = new File(rootProject.projectDir.path, PATH_VERSION_FILE) + if (versionFile.exists()) { + versionFile.delete() + } +} + +String getEnvValue(key, defValue) { + def val = System.getProperty(key) + if (null != val) { + return val + } + val = System.getenv(key) + if (null != val) { + return val + } + return defValue +} \ No newline at end of file diff --git a/app/src/main/java/com/dhc/flyabbit/app/App.java b/app/src/main/java/com/dhc/flyabbit/app/App.java index 9707a98..72e4f51 100644 --- a/app/src/main/java/com/dhc/flyabbit/app/App.java +++ b/app/src/main/java/com/dhc/flyabbit/app/App.java @@ -1,9 +1,20 @@ package com.dhc.flyabbit.app; +import android.app.Activity; import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageInfo; import android.content.res.Configuration; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatDelegate; +import android.taobao.atlas.bundleInfo.AtlasBundleInfoManager; +import android.taobao.atlas.framework.Atlas; +import android.taobao.atlas.framework.BundleImpl; +import android.taobao.atlas.framework.BundleInstaller; +import android.taobao.atlas.runtime.ActivityTaskMgr; +import android.taobao.atlas.runtime.ClassNotFoundInterceptorCallback; +import android.text.TextUtils; +import android.widget.Toast; import com.alibaba.android.arouter.facade.annotation.Autowired; import com.alibaba.android.arouter.launcher.ARouter; @@ -12,6 +23,10 @@ import com.dhc.library.base.BaseApplication; import com.squareup.leakcanary.LeakCanary; +import org.osgi.framework.BundleException; + +import java.io.File; + /** * 创建者:邓浩宸 * 时间 :2017/3/21 10:51 @@ -46,6 +61,44 @@ public void onCreate() { if (mApplicationLikeMoudle3!=null) AsLibUtil.addAsLIbChild(mApplicationLikeMoudle3); AsLibUtil.doCreateAsLibrary(this); + + Atlas.getInstance().setClassNotFoundInterceptorCallback(new ClassNotFoundInterceptorCallback() { + @Override + public Intent returnIntent(Intent intent) { + final String className = intent.getComponent().getClassName(); + final String bundleName = AtlasBundleInfoManager.instance().getBundleForComponet(className); + + if (!TextUtils.isEmpty(bundleName) && !AtlasBundleInfoManager.instance().isInternalBundle(bundleName)) { + + //远程bundle + Activity activity = ActivityTaskMgr.getInstance().peekTopActivity(); + File remoteBundleFile = new File(activity.getExternalCacheDir(),"lib" + bundleName.replace(".","_") + ".so"); + + String path = ""; + if (remoteBundleFile.exists()){ + path = remoteBundleFile.getAbsolutePath(); + }else { + Toast.makeText(activity, " 远程bundle不存在,请确定 : " + remoteBundleFile.getAbsolutePath() , Toast.LENGTH_LONG).show(); + return intent; + } + + + PackageInfo info = activity.getPackageManager().getPackageArchiveInfo(path, 0); + try { + Atlas.getInstance().installBundle(info.packageName, new File(path)); + } catch (BundleException e) { + Toast.makeText(activity, " 远程bundle 安装失败," + e.getMessage() , Toast.LENGTH_LONG).show(); + + e.printStackTrace(); + } + + activity.startActivities(new Intent[]{intent}); + + } + + return intent; + } + }); } diff --git a/app/src/main/java/com/dhc/flyabbit/ui/MainFragment.java b/app/src/main/java/com/dhc/flyabbit/ui/MainFragment.java index dc51d60..c2113ff 100644 --- a/app/src/main/java/com/dhc/flyabbit/ui/MainFragment.java +++ b/app/src/main/java/com/dhc/flyabbit/ui/MainFragment.java @@ -1,20 +1,20 @@ package com.dhc.flyabbit.ui; +import android.content.Intent; import android.os.Bundle; +import android.support.annotation.Nullable; import android.view.View; +import android.view.ViewGroup; import com.alibaba.android.arouter.facade.annotation.Route; import com.dhc.flyabbit.R; -import com.dhc.flyabbit.gank.ui.GankFragment; -import com.dhc.flyabbit.home.ui.HomeFragment; -import com.dhc.flyabbit.my.MyFragment; import com.dhc.lib.widget.bottombar.BottomBar; import com.dhc.lib.widget.bottombar.BottomBarTab; import com.dhc.library.base.XDaggerFragment; import com.dhc.library.data.account.AccountManager; import com.dhc.library.framework.OnBackToFirstListener; +import com.taobao.android.ActivityGroupDelegate; -import me.yokeyword.fragmentation.SupportFragment; @@ -25,7 +25,8 @@ */ @Route(path = "/app/MainFragment") public class MainFragment extends XDaggerFragment implements OnBackToFirstListener { - + private ActivityGroupDelegate mActivityDelegate; + private ViewGroup mActivityGroupContainer; private BottomBar mBottomBar; private String[] mTitles = {"干货", "妹子", "关于"}; private int[] mIconUnselectIds = { @@ -35,8 +36,9 @@ public class MainFragment extends XDaggerFragment implements OnBackToFirstListen public static final int SECOND = 1; public static final int THIRD = 2; public int current = -1; - private SupportFragment[] mFragments = new SupportFragment[4]; - +// private SupportFragment[] mFragments = new SupportFragment[4]; +private String[] mTags={"home", "girls", "about"}; +private String[] mActs={"com.dhc.flyabbit.home.debug.HomeDebugActivity", "com.dhc.flyabbit.gank.debug.GirlsDebugActivity", "com.dhc.flyabbit.my.debug.MyDebugActivity"}; public static MainFragment newInstance() { Bundle args = new Bundle(); MainFragment fragment = new MainFragment(); @@ -44,8 +46,14 @@ public static MainFragment newInstance() { return fragment; } + @Override + public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + mActivityDelegate = new ActivityGroupDelegate(_mActivity,savedInstanceState); + } private void initView(View view) { + mActivityGroupContainer = (ViewGroup) $(R.id.fl_tab_container); mBottomBar = (BottomBar) view.findViewById(R.id.bottomBar); mBottomBar.addItem(new BottomBarTab(_mActivity, mIconUnselectIds[0], mTitles[0])) .addItem(new BottomBarTab(_mActivity, mIconUnselectIds[1], mTitles[1])) @@ -59,10 +67,13 @@ public boolean onTabSelected(int position, int prePosition) {//tab切换 if ((position != 0) && !isLogin) { current = position; // TODO: 2017/8/21 这里适用于条件触发式登录 - showHideFragment(mFragments[position], mFragments[prePosition]); +// showHideFragment(mFragments[position], mFragments[prePosition]); + switchToActivity(mTags[position],mActs[position]); return false; } else { - showHideFragment(mFragments[position], mFragments[prePosition]); + + switchToActivity(mTags[position],mActs[position]); +// showHideFragment(mFragments[position], mFragments[prePosition]); return false; } } @@ -76,26 +87,30 @@ public void onTabUnselected(int position) { public void onTabReselected(int position) { } }); - + switchToActivity(mTags[0],mActs[0]); } - + public void switchToActivity(String key,String activityName){ + Intent intent = new Intent(); + intent.setClassName(_mActivity.getBaseContext(),activityName); + mActivityDelegate.startChildActivity(mActivityGroupContainer,key,intent); + } @Override public void initInject(Bundle savedInstanceState) { - if (savedInstanceState == null) { - mFragments[FIRST] = HomeFragment.newInstance(); - mFragments[SECOND] = GankFragment.newInstance(); - mFragments[THIRD] = MyFragment.newInstance(); - loadMultipleRootFragment(R.id.fl_tab_container, FIRST, - mFragments[FIRST], - mFragments[SECOND], - mFragments[THIRD]); - } else { - mFragments[FIRST] = findChildFragment(HomeFragment.class); - mFragments[SECOND] = findChildFragment(GankFragment.class); - mFragments[THIRD] = findChildFragment(MyFragment.class); - } +// if (savedInstanceState == null) { +// mFragments[FIRST] = HomeFragment.newInstance(); +// mFragments[SECOND] = GankFragment.newInstance(); +// mFragments[THIRD] = MyFragment.newInstance(); +// loadMultipleRootFragment(R.id.fl_tab_container, FIRST, +// mFragments[FIRST], +// mFragments[SECOND], +// mFragments[THIRD]); +// } else { +// mFragments[FIRST] = findChildFragment(HomeFragment.class); +// mFragments[SECOND] = findChildFragment(GankFragment.class); +// mFragments[THIRD] = findChildFragment(MyFragment.class); +// } } diff --git a/baselib/activitygroupcompat/.gitignore b/baselib/activitygroupcompat/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/baselib/activitygroupcompat/.gitignore @@ -0,0 +1 @@ +/build diff --git a/baselib/activitygroupcompat/build.gradle b/baselib/activitygroupcompat/build.gradle new file mode 100644 index 0000000..a7cfdc8 --- /dev/null +++ b/baselib/activitygroupcompat/build.gradle @@ -0,0 +1,33 @@ +apply plugin: 'com.android.library' + +group = 'com.atlas.demo' +version = '1.0.1' + +android { + compileSdkVersion rootProject.ext.android.compileSdkVersion + buildToolsVersion rootProject.ext.android.buildToolsVersion + defaultConfig { + minSdkVersion rootProject.ext.android.minSdkVersion + targetSdkVersion rootProject.ext.android.targetSdkVersion + versionCode 1 + versionName "1.0" + + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + //ui + compile(rootProject.ext.dependencies["appcompat-v7"]) { + exclude module: 'support-annotations' + exclude module: 'support-v4' + } + compile rootProject.ext.lib_atlas_core + //compile project(':atlas-core') +} diff --git a/baselib/activitygroupcompat/proguard-rules.pro b/baselib/activitygroupcompat/proguard-rules.pro new file mode 100644 index 0000000..4aa71d8 --- /dev/null +++ b/baselib/activitygroupcompat/proguard-rules.pro @@ -0,0 +1,25 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /Users/guanjie/Library/Android/sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# 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 diff --git a/baselib/activitygroupcompat/src/main/AndroidManifest.xml b/baselib/activitygroupcompat/src/main/AndroidManifest.xml new file mode 100644 index 0000000..e70af07 --- /dev/null +++ b/baselib/activitygroupcompat/src/main/AndroidManifest.xml @@ -0,0 +1,5 @@ + + + + diff --git a/baselib/activitygroupcompat/src/main/java/com/taobao/android/ActivityGroupDelegate.java b/baselib/activitygroupcompat/src/main/java/com/taobao/android/ActivityGroupDelegate.java new file mode 100644 index 0000000..d77ef4b --- /dev/null +++ b/baselib/activitygroupcompat/src/main/java/com/taobao/android/ActivityGroupDelegate.java @@ -0,0 +1,271 @@ +package com.taobao.android; + +import android.app.Activity; +import android.app.Application; +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.pm.ResolveInfo; +import android.os.Build; +import android.os.Bundle; +import android.os.Looper; +import android.support.v4.app.FragmentActivity; +import android.taobao.atlas.bundleInfo.AtlasBundleInfoManager; +import android.taobao.atlas.framework.Atlas; +import android.taobao.atlas.framework.BundleImpl; +import android.taobao.atlas.framework.Framework; +import android.taobao.atlas.runtime.ActivityTaskMgr; +import android.taobao.atlas.runtime.BundleUtil; +import android.taobao.atlas.runtime.RuntimeVariables; +import android.taobao.atlas.util.StringUtils; +import android.text.TextUtils; +import android.util.Log; +import android.view.ViewGroup; + +/** + * Created by guanjie on 16/11/16. + */ + +public class ActivityGroupDelegate { + + private static final String STATES_KEY = "android:states"; + + + private LocalActivityManager mLocalActivityManager; + private FragmentActivity mActivity; + + public LocalActivityManager getLocalActivityManager(){ + return mLocalActivityManager; + } + + public ActivityGroupDelegate(FragmentActivity activity, Bundle bundle){ + mActivity = activity; + try { + mLocalActivityManager = new LocalActivityManager(activity, true); + }catch(Throwable e){ + throw new RuntimeException(e); + } +// Bundle states = bundle != null +// ? (Bundle) bundle.getBundle(STATES_KEY) : null; + mLocalActivityManager.dispatchCreate(null); + activity.getApplication().registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() { + @Override + public void onActivityCreated(Activity activity, Bundle bundle) { + } + + @Override + public void onActivityStarted(Activity activity) { + } + + @Override + public void onActivityResumed(Activity activity) { + if(mActivity == activity) { + mLocalActivityManager.dispatchResume(); + } + } + + @Override + public void onActivityPaused(Activity activity) { + if(mActivity == activity) { + mLocalActivityManager.dispatchPause(mActivity.isFinishing()); + } + } + + @Override + public void onActivityStopped(Activity activity) { + if(mActivity == activity) { + mLocalActivityManager.dispatchStop(); + } + } + + @Override + public void onActivitySaveInstanceState(Activity activity, Bundle bundle) { + if(mActivity == activity) { + Bundle state = mLocalActivityManager.saveInstanceState(); + if (state != null) { + bundle.putBundle(STATES_KEY, state); + } + } + } + + @Override + public void onActivityDestroyed(Activity activity) { + if(mActivity == activity) { + mLocalActivityManager.removeAllActivities(); + } + } + }); + } + +// public HashMap onRetainNonConfigurationChildInstances() { +// if(dispatchRetainNonConfigurationInstanceMethod!=null) { +// try { +// return (HashMap) dispatchRetainNonConfigurationInstanceMethod.invoke(mLocalActivityManager); +// } catch (Throwable e) { +// e.printStackTrace(); +// } +// } +// return null; +// } + +// private static Method dispatchRetainNonConfigurationInstanceMethod = null; +// private static Method onActivityResultMethod = null; +// private static Method noteStateNotSavedMethod = null; +// private static Method findFragmentByWhoMethod = null; +// static{ +// try { +// dispatchRetainNonConfigurationInstanceMethod = LocalActivityManager.class.getDeclaredMethod("dispatchRetainNonConfigurationInstance"); +// dispatchRetainNonConfigurationInstanceMethod.setAccessible(true); +// onActivityResultMethod = Activity.class.getDeclaredMethod("onActivityResult",int.class,int.class,Intent.class); +// onActivityResultMethod.setAccessible(true); +// noteStateNotSavedMethod = Class.forName("android.support.v4.app.FragmentManagerImpl"). +// getDeclaredMethod("noteStateNotSaved"); +// noteStateNotSavedMethod.setAccessible(true); +// findFragmentByWhoMethod = Class.forName("android.support.v4.app.FragmentManagerImpl"). +// getDeclaredMethod("findFragmentByWho",String.class); +// findFragmentByWhoMethod.setAccessible(true); +// } catch (Throwable e) { +// e.printStackTrace(); +// } +// +// } + + + public void startChildActivity(ViewGroup container, String key, Intent intent){ + //移除内容部分全部的View + container.removeAllViews(); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + + Activity contentActivity = mLocalActivityManager.getActivity(key); + if(contentActivity!=null) { + container.addView( + mLocalActivityManager.getActivity(key) + .getWindow().getDecorView(), + new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT)); + mLocalActivityManager.switchToChildActivity(key); + }else{ + execStartChildActivityInternal(container, key, intent); + } + } + + private void performLaunchChildActivity(ViewGroup container,String key,Intent intent ){ + if(intent==null){ + Log.e("ActivityGroupDelegate","intent is null stop performLaunchChildActivity"); + return ; + } + mLocalActivityManager.startActivity(key,intent); + container.addView( + mLocalActivityManager.getActivity(key) + .getWindow().getDecorView(), + new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT)); + } + + public void execStartChildActivityInternal(ViewGroup container,String key, Intent intent){ + String packageName = null; + String componentName = null ; + Context context = container.getContext(); + if (intent.getComponent() != null) { + packageName = intent.getComponent().getPackageName(); + componentName = intent.getComponent().getClassName(); + } else { + ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(intent, 0); + if (resolveInfo != null && resolveInfo.activityInfo != null) { + packageName = resolveInfo.activityInfo.packageName; + componentName = resolveInfo.activityInfo.name; + } + } + if (componentName == null){ + Log.e("ActivityGroupDelegate","can not find componentName"); + } + if (!StringUtils.equals(context.getPackageName(), packageName)) { + Log.e("ActivityGroupDelegate","childActivity can not be external Activity"); + } + + String bundleName = AtlasBundleInfoManager.instance().getBundleForComponet(componentName); + if(!TextUtils.isEmpty(bundleName)){ + BundleImpl impl = (BundleImpl) Atlas.getInstance().getBundle(bundleName); + if(impl!=null&&impl.checkValidate()) { + performLaunchChildActivity(container,key,intent); + }else { + if(ActivityTaskMgr.getInstance().peekTopActivity()!=null && Looper.getMainLooper().getThread().getId()==Thread.currentThread().getId()) { + asyncStartActivity(container,key,bundleName,intent); + }else{ + performLaunchChildActivity(container,key,intent); + } + } + }else{ + // Try to get class from system Classloader + try { + Class clazz = null; + clazz = Framework.getSystemClassLoader().loadClass(componentName); + if (clazz != null) { + performLaunchChildActivity(container,key,intent); + } + } catch (ClassNotFoundException e) { + Log.e("ActivityGroupDelegate","",e); + } + } + + } + + private void asyncStartActivity(final ViewGroup container,final String key,final String bundleName,final Intent intent){ + final Activity current = ActivityTaskMgr.getInstance().peekTopActivity(); + final Dialog dialog = current!=null ? RuntimeVariables.alertDialogUntilBundleProcessed(current,bundleName) : null; + if(current!=null && dialog==null){ + throw new RuntimeException("alertDialogUntilBundleProcessed can not return null"); + } + final int currentActivitySize = ActivityTaskMgr.getInstance().sizeOfActivityStack(); + final BundleUtil.CancelableTask successTask = new BundleUtil.CancelableTask(new Runnable() { + @Override + public void run() { + if (current == ActivityTaskMgr.getInstance().peekTopActivity() || currentActivitySize==ActivityTaskMgr.getInstance().sizeOfActivityStack()+1) { + performLaunchChildActivity(container,key,intent); + } + + if (dialog != null && current != null && !current.isFinishing()) { + try { + if(dialog.isShowing()) + dialog.dismiss(); + }catch (Throwable e){} + } + } + }); + final BundleUtil.CancelableTask failedTask = new BundleUtil.CancelableTask(new Runnable() { + @Override + public void run() { + if (current == ActivityTaskMgr.getInstance().peekTopActivity()) { + + } + + if (dialog != null && current != null && !current.isFinishing()) { + try { + if(dialog.isShowing()) + dialog.dismiss(); + }catch(Throwable e){} + } + } + }); + + if(dialog!=null) { + dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { + @Override + public void onDismiss(DialogInterface dialog) { + successTask.cancel(); + failedTask.cancel(); + } + }); + if(Atlas.getInstance().getBundle(bundleName)==null || Build.VERSION.SDK_INT<22) { + if (dialog != null && current != null && !current.isFinishing() && !dialog.isShowing()) { + try { + dialog.show(); + } catch (Throwable e) { + } + } + } + BundleUtil.checkBundleStateAsync(bundleName, successTask, failedTask); + } + } +} diff --git a/baselib/activitygroupcompat/src/main/java/com/taobao/android/LocalActivityManager.java b/baselib/activitygroupcompat/src/main/java/com/taobao/android/LocalActivityManager.java new file mode 100644 index 0000000..e3b46d3 --- /dev/null +++ b/baselib/activitygroupcompat/src/main/java/com/taobao/android/LocalActivityManager.java @@ -0,0 +1,790 @@ +/* + * Copyright (C) 2006 The Android Open Source Project + * + * 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.taobao.android; + +import android.app.Activity; +import android.content.ActivityNotFoundException; +import android.content.Intent; +import android.content.pm.ActivityInfo; +import android.content.pm.PackageManager; +import android.os.Binder; +import android.os.Build; +import android.os.Bundle; +import android.os.IBinder; +import android.taobao.atlas.hack.AndroidHack; +import android.taobao.atlas.hack.AtlasHacks; +import android.taobao.atlas.hack.Hack; +import android.taobao.atlas.runtime.RuntimeVariables; +import android.util.Log; +import android.view.Window; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class LocalActivityManager { + private static final String TAG = "LocalActivityManager"; + private static final boolean localLOGV = false; + + // Internal token for an Activity being managed by LocalActivityManager. + private static class LocalActivityRecord extends Binder { + LocalActivityRecord(String _id, Intent _intent) { + id = _id; + intent = _intent; + } + + final String id; // Unique name of this record. + Intent intent; // Which activity to run here. + ActivityInfo activityInfo; // Package manager info about activity. + Activity activity; // Currently instantiated activity. + Window window; // Activity's top-level window. + Bundle instanceState; // Last retrieved freeze state. + int curState = RESTORED; // Current state the activity is in. + } + + static final int RESTORED = 0; // State restored, but no startActivity(). + static final int INITIALIZING = 1; // Ready to launch (after startActivity()). + static final int CREATED = 2; // Created, not started or resumed. + static final int STARTED = 3; // Created and started, not resumed. + static final int RESUMED = 4; // Created started and resumed. + static final int DESTROYED = 5; // No longer with us. + + /** Thread our activities are running in. */ + private final Object mActivityThread; + /** The containing activity that owns the activities we create. */ + private final Activity mParent; + + /** The activity that is currently resumed. */ + private LocalActivityRecord mResumed; + /** id -> record of all known activities. */ + private final Map mActivities + = new HashMap(); + /** array of all known activities for easy iterating. */ + private final ArrayList mActivityArray + = new ArrayList(); + + /** True if only one activity can be resumed at a time */ + private boolean mSingleMode; + + /** Set to true once we find out the container is finishing. */ + private boolean mFinishing; + + /** Current state the owner (ActivityGroup) is in */ + private int mCurState = INITIALIZING; + + private Hack.HackedClass NonConfigurationInstances; + private Hack.HackedMethod ActivityThread_startActivityNow; + private Hack.HackedMethod ActivityThread_performRestartActivity; + private Hack.HackedMethod ActivityThread_performDestroyActivity; + private Hack.HackedMethod Activity_performSaveInstanceState; + + private Hack.HackedMethod ActivityThread_performResumeActivity; + private Hack.HackedMethod ActivityThread_performStopActivity; + private Hack.HackedMethod ActivityThread_performPauseActivity; + + private Hack.HackedMethod Activity_onStart; + private Hack.HackedMethod Activity_onStop; + + + /** + * Create a new LocalActivityManager for holding activities running within + * the given parent. + * + * @param parent the host of the embedded activities + * @param singleMode True if the LocalActivityManger should keep a maximum + * of one activity resumed + */ + public LocalActivityManager(Activity parent, boolean singleMode) throws Throwable{ + defineAndVerify(); + mActivityThread = AndroidHack.getActivityThread(); + mParent = parent; + mSingleMode = singleMode; + } + + private void defineAndVerify() throws Hack.HackDeclaration.HackAssertionException{ + NonConfigurationInstances = Hack.into("android.app.Activity$NonConfigurationInstances"); + ActivityThread_startActivityNow = AtlasHacks.ActivityThread.method("startActivityNow",Activity.class,String.class, + Intent.class,ActivityInfo.class, IBinder.class,Bundle.class,NonConfigurationInstances.getmClass()); + ActivityThread_performRestartActivity = AtlasHacks.ActivityThread.method("performRestartActivity",IBinder.class); + ActivityThread_performDestroyActivity = AtlasHacks.ActivityThread.method("performDestroyActivity",IBinder.class,boolean.class); + Activity_performSaveInstanceState = Hack.into(Activity.class).method("performSaveInstanceState",Bundle.class); + Activity_onStart = Hack.into(Activity.class).method("onStart"); + Activity_onStop = Hack.into(Activity.class).method("onStop"); + if(Build.VERSION.SDK_INT<=23) { + ActivityThread_performResumeActivity = AtlasHacks.ActivityThread.method("performResumeActivity", + IBinder.class,boolean.class); + ActivityThread_performStopActivity = AtlasHacks.ActivityThread.method("performStopActivity", + IBinder.class,boolean.class); + ActivityThread_performPauseActivity = AtlasHacks.ActivityThread.method("performPauseActivity", + IBinder.class,boolean.class,boolean.class); + }else{ + ActivityThread_performResumeActivity = AtlasHacks.ActivityThread.method("performResumeActivity", + IBinder.class,boolean.class,String.class); + ActivityThread_performStopActivity = AtlasHacks.ActivityThread.method("performStopActivity", + IBinder.class,boolean.class,String.class); + ActivityThread_performPauseActivity = AtlasHacks.ActivityThread.method("performPauseActivity", + IBinder.class,boolean.class,boolean.class,String.class); + } + } + + private void moveToState(LocalActivityRecord r, int desiredState) { + if (r.curState == RESTORED || r.curState == DESTROYED) { + // startActivity() has not yet been called, so nothing to do. + return; + } + + if (r.curState == INITIALIZING) { + // We need to have always created the activity. + if (localLOGV) Log.v(TAG, r.id + ": starting " + r.intent); + if (r.activityInfo == null) { + r.activityInfo = r.intent.resolveActivityInfo( + RuntimeVariables.androidApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES); + } + try { + r.activity = (Activity) ActivityThread_startActivityNow.invoke(mActivityThread, + mParent, r.id, r.intent, r.activityInfo, r, r.instanceState, null); + }catch(InvocationTargetException e){ + throw new RuntimeException(e.getTargetException()); + } + if (r.activity == null) { + return; + } + r.window = r.activity.getWindow(); + r.instanceState = null; + r.curState = STARTED; + + if (desiredState == RESUMED) { + if (localLOGV) Log.v(TAG, r.id + ": resuming"); +// mActivityThread.performResumeActivity(r, true, "moveToState-INITIALIZING"); + try { + if(ActivityThread_performResumeActivity.getMethod().getParameterTypes().length==2){ + ActivityThread_performResumeActivity.invoke(mActivityThread,r,true); + }else{ + ActivityThread_performResumeActivity.invoke(mActivityThread,r,true,"moveToState-INITIALIZING"); + } + }catch (InvocationTargetException e){ + throw new RuntimeException(e.getTargetException()); + } + r.curState = RESUMED; + } + + // Don't do anything more here. There is an important case: + // if this is being done as part of onCreate() of the group, then + // the launching of the activity gets its state a little ahead + // of our own (it is now STARTED, while we are only CREATED). + // If we just leave things as-is, we'll deal with it as the + // group's state catches up. + return; + } + + switch (r.curState) { + case CREATED: + if (desiredState == STARTED) { + if (localLOGV) Log.v(TAG, r.id + ": restarting"); + try { + ActivityThread_performRestartActivity.invoke(mActivityThread, r); + }catch (InvocationTargetException e){ + throw new RuntimeException(e.getTargetException()); + } + r.curState = STARTED; + } + if (desiredState == RESUMED) { + if (localLOGV) Log.v(TAG, r.id + ": restarting and resuming"); + try { + ActivityThread_performRestartActivity.invoke(mActivityThread, r); + if(ActivityThread_performResumeActivity.getMethod().getParameterTypes().length==2){ + ActivityThread_performResumeActivity.invoke(mActivityThread,r,true); + }else{ + ActivityThread_performResumeActivity.invoke(mActivityThread,r,true,"moveToState-CREATED"); + } + }catch (InvocationTargetException e){ + throw new RuntimeException(e.getTargetException()); + } +// mActivityThread.performResumeActivity(r, true, "moveToState-CREATED"); + r.curState = RESUMED; + } + return; + + case STARTED: + if (desiredState == RESUMED) { + // Need to resume it... + if (localLOGV) Log.v(TAG, r.id + ": resuming"); +// mActivityThread.performResumeActivity(r, true, "moveToState-STARTED"); + try { + if(ActivityThread_performResumeActivity.getMethod().getParameterTypes().length==2){ + ActivityThread_performResumeActivity.invoke(mActivityThread,r,true); + }else{ + ActivityThread_performResumeActivity.invoke(mActivityThread,r,true,"moveToState-STARTED"); + } + }catch (InvocationTargetException e){ + throw new RuntimeException(e.getTargetException()); + } + r.instanceState = null; + r.curState = RESUMED; + } + if (desiredState == CREATED) { + if (localLOGV) Log.v(TAG, r.id + ": stopping"); +// mActivityThread.performStopActivity(r, false, "moveToState-STARTED"); + try { + if(ActivityThread_performStopActivity.getMethod().getParameterTypes().length==2){ + ActivityThread_performStopActivity.invoke(mActivityThread,r,false); + }else{ + ActivityThread_performStopActivity.invoke(mActivityThread,r,false,"moveToState-STARTED"); + } + }catch (InvocationTargetException e){ + throw new RuntimeException(e.getTargetException()); + } + r.curState = CREATED; + } + return; + + case RESUMED: + if (desiredState == STARTED) { + if (localLOGV) Log.v(TAG, r.id + ": pausing"); + performPause(r, mFinishing); + r.curState = STARTED; + } + if (desiredState == CREATED) { + if (localLOGV) Log.v(TAG, r.id + ": pausing"); + performPause(r, mFinishing); + if (localLOGV) Log.v(TAG, r.id + ": stopping"); +// mActivityThread.performStopActivity(r, false, "moveToState-RESUMED"); + try { + if(ActivityThread_performStopActivity.getMethod().getParameterTypes().length==2){ + ActivityThread_performStopActivity.invoke(mActivityThread,r,false); + }else{ + ActivityThread_performStopActivity.invoke(mActivityThread,r,false,"moveToState-RESUMED"); + } + }catch (InvocationTargetException e){ + throw new RuntimeException(e.getTargetException()); + } + r.curState = CREATED; + } + return; + } + } + + private void performPause(LocalActivityRecord r, boolean finishing) { + final boolean needState = r.instanceState == null; +// final Bundle instanceState = mActivityThread.performPauseActivity( +// r, finishing, needState, "performPause"); + Bundle instanceState = null; + try { + if(ActivityThread_performPauseActivity.getMethod().getParameterTypes().length==3){ + instanceState = (Bundle) ActivityThread_performPauseActivity.invoke(mActivityThread,r,finishing,needState); + }else{ + instanceState = (Bundle) ActivityThread_performPauseActivity.invoke(mActivityThread,r,finishing,needState,"moveToState-RESUMED"); + } + }catch (InvocationTargetException e){ + throw new RuntimeException(e.getTargetException()); + } + if (needState) { + r.instanceState = instanceState; + } + } + + /** + * Start a new activity running in the group. Every activity you start + * must have a unique string ID associated with it -- this is used to keep + * track of the activity, so that if you later call startActivity() again + * on it the same activity object will be retained. + * + *

When there had previously been an activity started under this id, + * it may either be destroyed and a new one started, or the current + * one re-used, based on these conditions, in order:

+ * + *
    + *
  • If the Intent maps to a different activity component than is + * currently running, the current activity is finished and a new one + * started. + *
  • If the current activity uses a non-multiple launch mode (such + * as singleTop), or the Intent has the + * {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag set, then the current + * activity will remain running and its + * {@link Activity#onNewIntent(Intent) Activity.onNewIntent()} method + * called. + *
  • If the new Intent is the same (excluding extras) as the previous + * one, and the new Intent does not have the + * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP} set, then the current activity + * will remain running as-is. + *
  • Otherwise, the current activity will be finished and a new + * one started. + *
+ * + *

If the given Intent can not be resolved to an available Activity, + * this method throws {@link ActivityNotFoundException}. + * + *

Warning: There is an issue where, if the Intent does not + * include an explicit component, we can restore the state for a different + * activity class than was previously running when the state was saved (if + * the set of available activities changes between those points). + * + * @param id Unique identifier of the activity to be started + * @param intent The Intent describing the activity to be started + * + * @return Returns the window of the activity. The caller needs to take + * care of adding this window to a view hierarchy, and likewise dealing + * with removing the old window if the activity has changed. + * + * @throws ActivityNotFoundException + */ + public Window startActivity(String id, Intent intent) { + if (mCurState == INITIALIZING) { + throw new IllegalStateException( + "Activities can't be added until the containing group has been created."); + } + + boolean adding = false; + boolean sameIntent = false; + + ActivityInfo aInfo = null; + + // Already have information about the new activity id? + LocalActivityRecord r = mActivities.get(id); + if (r == null) { + // Need to create it... + r = new LocalActivityRecord(id, intent); + adding = true; + } else if (r.intent != null) { + sameIntent = r.intent.filterEquals(intent); + if (sameIntent) { + // We are starting the same activity. + aInfo = r.activityInfo; + } + } + if (aInfo == null) { + aInfo = r.intent.resolveActivityInfo( + RuntimeVariables.androidApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES); + if (aInfo == null) { + // Throw an exception. + throw new ActivityNotFoundException( + "No Activity found to handle " + intent); + } + } + + // Pause the currently running activity if there is one and only a single + // activity is allowed to be running at a time. + if (mSingleMode) { + LocalActivityRecord old = mResumed; + + // If there was a previous activity, and it is not the current + // activity, we need to stop it. + if (old != null && old != r && mCurState == RESUMED) { + moveToState(old, STARTED); + } + } + + if (adding) { + // It's a brand new world. + mActivities.put(id, r); + mActivityArray.add(r); + } else if (r.activityInfo != null) { + // If the new activity is the same as the current one, then + // we may be able to reuse it. + if (aInfo == r.activityInfo || + (aInfo.name.equals(r.activityInfo.name) && + aInfo.packageName.equals(r.activityInfo.packageName))) { + if (aInfo.launchMode != ActivityInfo.LAUNCH_MULTIPLE || + (intent.getFlags()&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0) { + // The activity wants onNewIntent() called. + intent.setExtrasClassLoader(r.activity.getClassLoader()); + //TODO callActivityOnNewIntent use reflect + //callActivityOnNewIntent(r.activity, intent); + r.intent = intent; + moveToState(r, mCurState); + if (mSingleMode) { + mResumed = r; + } + return r.window; + } + if (sameIntent && + (intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_TOP) == 0) { + // We are showing the same thing, so this activity is + // just resumed and stays as-is. + r.intent = intent; + moveToState(r, mCurState); + if (mSingleMode) { + mResumed = r; + } + return r.window; + } + } + + // The new activity is different than the current one, or it + // is a multiple launch activity, so we need to destroy what + // is currently there. + performDestroy(r, true); + } + + r.intent = intent; + r.curState = INITIALIZING; + r.activityInfo = aInfo; + + moveToState(r, mCurState); + + // When in single mode keep track of the current activity + if (mSingleMode) { + mResumed = r; + } + return r.window; + } + + private Window performDestroy(LocalActivityRecord r, boolean finish) { + Window win; + win = r.window; + if (r.curState == RESUMED && !finish) { + performPause(r, finish); + } + if (localLOGV) Log.v(TAG, r.id + ": destroying"); + try { + ActivityThread_performDestroyActivity.invoke(mActivityThread, r,finish); + }catch (InvocationTargetException e){ + throw new RuntimeException(e.getTargetException()); + } + r.activity = null; + r.window = null; + if (finish) { + r.instanceState = null; + } + r.curState = DESTROYED; + return win; + } + + /** + * Destroy the activity associated with a particular id. This activity + * will go through the normal lifecycle events and fine onDestroy(), and + * then the id removed from the group. + * + * @param id Unique identifier of the activity to be destroyed + * @param finish If true, this activity will be finished, so its id and + * all state are removed from the group. + * + * @return Returns the window that was used to display the activity, or + * null if there was none. + */ + public Window destroyActivity(String id, boolean finish) { + LocalActivityRecord r = mActivities.get(id); + Window win = null; + if (r != null) { + win = performDestroy(r, finish); + if (finish) { + mActivities.remove(id); + mActivityArray.remove(r); + } + } + return win; + } + + /** + * Retrieve the Activity that is currently running. + * + * @return the currently running (resumed) Activity, or null if there is + * not one + * + * @see #startActivity + * @see #getCurrentId + */ + public Activity getCurrentActivity() { + return mResumed != null ? mResumed.activity : null; + } + + /** + * Retrieve the ID of the activity that is currently running. + * + * @return the ID of the currently running (resumed) Activity, or null if + * there is not one + * + * @see #startActivity + * @see #getCurrentActivity + */ + public String getCurrentId() { + return mResumed != null ? mResumed.id : null; + } + + /** + * Return the Activity object associated with a string ID. + * + * @see #startActivity + * + * @return the associated Activity object, or null if the id is unknown or + * its activity is not currently instantiated + */ + public Activity getActivity(String id) { + LocalActivityRecord r = mActivities.get(id); + return r != null ? r.activity : null; + } + + /** + * Restore a state that was previously returned by {@link #saveInstanceState}. This + * adds to the activity group information about all activity IDs that had + * previously been saved, even if they have not been started yet, so if the + * user later navigates to them the correct state will be restored. + * + *

Note: This does not change the current running activity, or + * start whatever activity was previously running when the state was saved. + * That is up to the client to do, in whatever way it thinks is best. + * + * @param state a previously saved state; does nothing if this is null + * + * @see #saveInstanceState + */ + public void dispatchCreate(Bundle state) { + if (state != null) { + for (String id : state.keySet()) { + try { + final Bundle astate = state.getBundle(id); + LocalActivityRecord r = mActivities.get(id); + if (r != null) { + r.instanceState = astate; + } else { + r = new LocalActivityRecord(id, null); + r.instanceState = astate; + mActivities.put(id, r); + mActivityArray.add(r); + } + } catch (Exception e) { + // Recover from -all- app errors. + Log.e(TAG, "Exception thrown when restoring LocalActivityManager state", e); + } + } + } + + mCurState = CREATED; + } + + /** + * Retrieve the state of all activities known by the group. For + * activities that have previously run and are now stopped or finished, the + * last saved state is used. For the current running activity, its + * {@link Activity#onSaveInstanceState} is called to retrieve its current state. + * + * @return a Bundle holding the newly created state of all known activities + * + * @see #dispatchCreate + */ + public Bundle saveInstanceState() { + Bundle state = null; + + // FIXME: child activities will freeze as part of onPaused. Do we + // need to do this here? + final int N = mActivityArray.size(); + for (int i=0; i dispatchRetainNonConfigurationInstance() { + HashMap instanceMap = null; + + final int N = mActivityArray.size(); + for (int i=0; i(); + } + instanceMap.put(r.id, instance); + } + } + } + return instanceMap; + } + + /** + * Remove all activities from this LocalActivityManager, performing an + * {@link Activity#onDestroy} on any that are currently instantiated. + */ + public void removeAllActivities() { + dispatchDestroy(true); + } + + /** + * Called by the container activity in its {@link Activity#onDestroy} so + * that LocalActivityManager can perform the corresponding action on the + * activities it holds. + * + * @see Activity#onDestroy + */ + public void dispatchDestroy(boolean finishing) { + final int N = mActivityArray.size(); + for (int i=0; i + ActivityGroupDelegateCompat + diff --git a/baselib/imageloader/build.gradle b/baselib/imageloader/build.gradle index 20be3a7..cbde468 100644 --- a/baselib/imageloader/build.gradle +++ b/baselib/imageloader/build.gradle @@ -1,13 +1,14 @@ apply plugin: 'com.android.library' android { - compileSdkVersion 26 + compileSdkVersion rootProject.ext.android.compileSdkVersion + buildToolsVersion rootProject.ext.android.buildToolsVersion defaultConfig { - minSdkVersion 15 - targetSdkVersion 26 + minSdkVersion rootProject.ext.android.minSdkVersion + targetSdkVersion rootProject.ext.android.targetSdkVersion versionCode 1 versionName "1.0" @@ -21,15 +22,15 @@ android { proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } +// compileOptions { +// sourceCompatibility JavaVersion.VERSION_1_8 +// targetCompatibility JavaVersion.VERSION_1_8 +// } } dependencies { - implementation fileTree(include: ['*.jar'], dir: 'libs') - provided 'com.android.support:support-annotations:27.0.2' + compile fileTree(include: ['*.jar'], dir: 'libs') + provided rootProject.ext.dependencies["annotations"] provided(rootProject.ext.dependencies["appcompat-v7"]) { exclude module: 'support-annotations' exclude module: 'support-v4' @@ -37,9 +38,7 @@ dependencies { provided(rootProject.ext.dependencies["support-v4"]) { exclude module: 'support-annotations' } - testImplementation 'junit:junit:4.12' - androidTestImplementation 'com.android.support.test:runner:1.0.1' - androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' - api rootProject.ext.dependencies["glide"] + testCompile 'junit:junit:4.12' + compile rootProject.ext.dependencies["glide"] // implementation project(':uikit') } diff --git a/baselib/imageloader/src/main/java/com/dhc/lib/imageload/glideloader/CustomCachingGlideModule.java b/baselib/imageloader/src/main/java/com/dhc/lib/imageload/glideloader/CustomCachingGlideModule.java index de14c4e..44d7d01 100644 --- a/baselib/imageloader/src/main/java/com/dhc/lib/imageload/glideloader/CustomCachingGlideModule.java +++ b/baselib/imageloader/src/main/java/com/dhc/lib/imageload/glideloader/CustomCachingGlideModule.java @@ -5,6 +5,7 @@ import com.bumptech.glide.Glide; import com.bumptech.glide.GlideBuilder; import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool; +import com.bumptech.glide.load.engine.cache.DiskCache; import com.bumptech.glide.load.engine.cache.DiskLruCacheWrapper; import com.bumptech.glide.load.engine.cache.LruResourceCache; import com.bumptech.glide.load.engine.cache.MemorySizeCalculator; @@ -22,11 +23,14 @@ public class CustomCachingGlideModule implements GlideModule { public static final int IMAGE_DISK_CACHE_MAX_SIZE = 100 * 1024 * 1024;//图片缓存文件最大值为100Mb @Override - public void applyOptions(Context context, GlideBuilder builder) { - builder.setDiskCache(() -> { - File cacheFile = new File(FileUtil.getCacheDirectory(context), "Glide");//缓存路径 - cacheFile= FileUtil.makeDirs(cacheFile); - return DiskLruCacheWrapper.get(cacheFile, IMAGE_DISK_CACHE_MAX_SIZE); + public void applyOptions(final Context context, GlideBuilder builder) { + builder.setDiskCache(new DiskCache.Factory() { + @Override + public DiskCache build() { + File cacheFile = new File(FileUtil.getCacheDirectory(context), "Glide");//缓存路径 + cacheFile = FileUtil.makeDirs(cacheFile); + return DiskLruCacheWrapper.get(cacheFile, IMAGE_DISK_CACHE_MAX_SIZE); + } }); //设置图片格式,默认是RGB565格式,不支持透明 // builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888); diff --git a/baselib/library/build.gradle b/baselib/library/build.gradle index 54ea477..abaefb7 100644 --- a/baselib/library/build.gradle +++ b/baselib/library/build.gradle @@ -43,71 +43,75 @@ android { aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } +// compileOptions { +// sourceCompatibility JavaVersion.VERSION_1_8 +// targetCompatibility JavaVersion.VERSION_1_8 +// } +// compileOptions { +// targetCompatibility 1.8 +// sourceCompatibility 1.8 +// } } dependencies { - api fileTree(include: ['*.jar'], dir: 'libs') - androidTestApi('com.android.support.test.espresso:espresso-core:3.0.1', { - exclude group: 'com.android.support', module: 'support-annotations' - }) + compile fileTree(include: ['*.jar'], dir: 'libs') +// androidTestCompile('com.android.support.test.espresso:espresso-core:3.0.1', { +// exclude group: 'com.android.support', module: 'support-annotations' +// }) //test - testApi rootProject.ext.dependencies["junit"] - api rootProject.ext.dependencies["fragmentation"] + testCompile rootProject.ext.dependencies["junit"] + compile rootProject.ext.dependencies["fragmentation"] //rx - api rootProject.ext.dependencies["rxjava"] - api(rootProject.ext.dependencies["rxandroid"]) { + compile rootProject.ext.dependencies["rxjava"] + compile(rootProject.ext.dependencies["rxandroid"]) { exclude module: 'rxjava' } - api(rootProject.ext.dependencies["rxlifecycle"]) { + compile(rootProject.ext.dependencies["rxlifecycle"]) { exclude module: 'rxjava' } - api(rootProject.ext.dependencies["rxlifecycle-android"]) { + compile(rootProject.ext.dependencies["rxlifecycle-android"]) { exclude module: 'rxjava' } - api(rootProject.ext.dependencies["rxlifecycle-components"]) { + compile(rootProject.ext.dependencies["rxlifecycle-components"]) { exclude module: 'rxjava' } //network - api rootProject.ext.dependencies["gson"] - api(rootProject.ext.dependencies["retrofit"]) { + compile rootProject.ext.dependencies["gson"] + compile(rootProject.ext.dependencies["retrofit"]) { exclude module: 'okhttp' } - api(rootProject.ext.dependencies["retrofit-converter-gson"]) { + compile(rootProject.ext.dependencies["retrofit-converter-gson"]) { exclude module: 'gson' } - api(rootProject.ext.dependencies["retrofit-adapter-rxjava"]) { + compile(rootProject.ext.dependencies["retrofit-adapter-rxjava"]) { exclude module: 'rxjava' } - api rootProject.ext.dependencies["okhttp3"] - api rootProject.ext.dependencies["okhttp3-logging-interceptor"] - api rootProject.ext.dependencies["glide-okhttp3-integration"] + compile rootProject.ext.dependencies["okhttp3"] + compile rootProject.ext.dependencies["okhttp3-logging-interceptor"] + compile rootProject.ext.dependencies["glide-okhttp3-integration"] //other - api rootProject.ext.dependencies["rxpermissions"] - api rootProject.ext.dependencies["Jolyglot-Gson"] - api rootProject.ext.dependencies["multidex"] - api rootProject.ext.dependencies["RxCache"] + compile rootProject.ext.dependencies["rxpermissions"] + compile rootProject.ext.dependencies["Jolyglot-Gson"] +// compile rootProject.ext.dependencies["multidex"] + compile rootProject.ext.dependencies["RxCache"] // //db // compile files('libs/ormlite-android-4.49.jar') // compile files('libs/ormlite-core-4.49.jar') //canary - debugApi rootProject.ext.dependencies["blockcanary-debug"] - releaseApi rootProject.ext.dependencies["blockcanary-release"] + debugCompile rootProject.ext.dependencies["blockcanary-debug"] + releaseCompile rootProject.ext.dependencies["blockcanary-release"] //Cookie - api rootProject.ext.dependencies["PersistentCookieJar"] + compile rootProject.ext.dependencies["PersistentCookieJar"] //di - api rootProject.ext.dependencies["dagger"] - api rootProject.ext.dependencies["arouter-api"] + compile rootProject.ext.dependencies["dagger"] + compile rootProject.ext.dependencies["arouter-api"] // compile rootProject.ext.dependencies["retrofit-converter-jackson"] - compileOnly rootProject.ext.dependencies["javax.annotation"] + provided rootProject.ext.dependencies["javax.annotation"] //dagger2的apt注解 annotationProcessor rootProject.ext.dependencies["dagger-compiler"] //阿里的Arouter的apt注解 annotationProcessor rootProject.ext.dependencies["arouter-compiler"] - api project(':imageloader') - api project(':uikit') + compile project(':imageloader') + compile project(':uikit') } diff --git a/baselib/library/src/main/java/com/dhc/library/base/BaseApplication.java b/baselib/library/src/main/java/com/dhc/library/base/BaseApplication.java index 5465b1e..c667f6f 100644 --- a/baselib/library/src/main/java/com/dhc/library/base/BaseApplication.java +++ b/baselib/library/src/main/java/com/dhc/library/base/BaseApplication.java @@ -1,10 +1,10 @@ package com.dhc.library.base; +import android.annotation.SuppressLint; import android.app.Activity; import android.app.Application; import android.os.Bundle; -import android.support.multidex.MultiDexApplication; import com.alibaba.android.arouter.launcher.ARouter; import com.dhc.lib.imageload.ImageLoaderManager; @@ -28,7 +28,7 @@ * 创建时间 2017/3/23 18:03 * 描述 基类app */ -public class BaseApplication extends MultiDexApplication implements AccountProvider { +public class BaseApplication extends Application implements AccountProvider { protected static BaseApplication instance; @@ -51,22 +51,22 @@ public void onCreate() { ARouter.openDebug(); // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险) } ARouter.init(instance); // 尽可能早,推荐在Application中初始化 - Fragmentation.builder() - // 设置 栈视图 模式为 悬浮球模式 SHAKE: 摇一摇唤出 NONE:隐藏 - .stackViewMode(Fragmentation.BUBBLE) - // ture时,遇到异常:"Can not perform this action after onSaveInstanceState!"时,会抛出 - // false时,不会抛出,会捕获,可以在handleException()里监听到 - .debug(AppUtil.isDebug()) - // 线上环境时,可能会遇到上述异常,此时debug=false,不会抛出该异常(避免crash),会捕获 - // 建议在回调处上传至我们的Crash检测服务器 - .handleException(new ExceptionHandler() { - @Override - public void onException(Exception e) { - // 以Bugtags为例子: 手动把捕获到的 Exception 传到 Bugtags 后台。 - // Bugtags.sendException(e); - } - }) - .install(); +// Fragmentation.builder() +// // 设置 栈视图 模式为 悬浮球模式 SHAKE: 摇一摇唤出 NONE:隐藏 +// .stackViewMode(Fragmentation.BUBBLE) +// // ture时,遇到异常:"Can not perform this action after onSaveInstanceState!"时,会抛出 +// // false时,不会抛出,会捕获,可以在handleException()里监听到 +// .debug(AppUtil.isDebug()) +// // 线上环境时,可能会遇到上述异常,此时debug=false,不会抛出该异常(避免crash),会捕获 +// // 建议在回调处上传至我们的Crash检测服务器 +// .handleException(new ExceptionHandler() { +// @Override +// public void onException(Exception e) { +// // 以Bugtags为例子: 手动把捕获到的 Exception 传到 Bugtags 后台。 +// // Bugtags.sendException(e); +// } +// }) +// .install(); //添加一个intentsetvice服务来初始化一些服务 InitializeService.start(this); diff --git a/baselib/library/src/main/java/com/dhc/library/utils/ToolbarUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/ToolbarUtil.java index ed0e333..5d1b21f 100644 --- a/baselib/library/src/main/java/com/dhc/library/utils/ToolbarUtil.java +++ b/baselib/library/src/main/java/com/dhc/library/utils/ToolbarUtil.java @@ -74,7 +74,7 @@ public void addOptionButton(List mOptionsButtons) { throw new RuntimeException( " toolbar must be in your layout and find it "); Toolbar.LayoutParams layoutParams; - for (OptionsButton button : mOptionsButtons) { + for (final OptionsButton button : mOptionsButtons) { if (button.iconId != 0 && button.rightString == null) { layoutParams = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT, Gravity.RIGHT | Gravity.CENTER); rightImageView = new ImageView(mActivity); diff --git a/baselib/library/src/main/java/com/dhc/library/utils/rx/RxUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/rx/RxUtil.java index 0c28ba3..45141d0 100644 --- a/baselib/library/src/main/java/com/dhc/library/utils/rx/RxUtil.java +++ b/baselib/library/src/main/java/com/dhc/library/utils/rx/RxUtil.java @@ -35,7 +35,7 @@ public static FlowableTransformer rxSchedulerHelpe * @param 返回数据data实际的 数据 * @return 返回数据data实际的 数据 */ - public static FlowableTransformer rxSchedulerHelper(int count,long delay) { //compose简化线程 + public static FlowableTransformer rxSchedulerHelper(final int count, final long delay) { //compose简化线程 return new FlowableTransformer() { @Override public Flowable apply(Flowable upstream) { diff --git a/baselib/library/src/main/java/com/dhc/library/utils/string/Base64Utils.java b/baselib/library/src/main/java/com/dhc/library/utils/string/Base64Utils.java index 66c1838..db886fe 100644 --- a/baselib/library/src/main/java/com/dhc/library/utils/string/Base64Utils.java +++ b/baselib/library/src/main/java/com/dhc/library/utils/string/Base64Utils.java @@ -11,6 +11,8 @@ import io.reactivex.Flowable; import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.functions.Consumer; +import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.ResourceSubscriber; @@ -197,13 +199,16 @@ public static String encodeBase64File(String path) throws Exception { public static void Base64ToBitmap(String url, ResourceSubscriber resourceSubscriber) { - Flowable.just(url).map(s -> { - byte[] decode = Base64.decode(s.split(",")[1], Base64.DEFAULT); - Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length); - return bitmap; + Flowable.just(url).map(new Function() { + @Override + public Object apply(String s) throws Exception { + byte[] decode = Base64.decode(s.split(",")[1], Base64.DEFAULT); + Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length); + return bitmap; + } }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) - .subscribe(resourceSubscriber); + .subscribe((Consumer) resourceSubscriber); } diff --git a/baselib/uikit/build.gradle b/baselib/uikit/build.gradle index 15be490..cb7d72c 100644 --- a/baselib/uikit/build.gradle +++ b/baselib/uikit/build.gradle @@ -44,57 +44,57 @@ android { aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } - retrolambda { - javaVersion JavaVersion.VERSION_1_7 - } +// compileOptions { +// sourceCompatibility JavaVersion.VERSION_1_8 +// targetCompatibility JavaVersion.VERSION_1_8 +// } +// retrolambda { +// javaVersion JavaVersion.VERSION_1_7 +// } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') - androidTestApi('com.android.support.test.espresso:espresso-core:3.0.1', { - exclude group: 'com.android.support', module: 'support-annotations' - }) +// androidTestCompile('com.android.support.test.espresso:espresso-core:3.0.1', { +// exclude group: 'com.android.support', module: 'support-annotations' +// }) //test - testApi rootProject.ext.dependencies["junit"] + testCompile rootProject.ext.dependencies["junit"] //ui - api(rootProject.ext.dependencies["appcompat-v7"]) { + compile(rootProject.ext.dependencies["appcompat-v7"]) { exclude module: 'support-annotations' exclude module: 'support-v4' } - api(rootProject.ext.dependencies["support-v4"]) { + compile(rootProject.ext.dependencies["support-v4"]) { exclude module: 'support-annotations' } - api(rootProject.ext.dependencies["design"]) { + compile(rootProject.ext.dependencies["design"]) { exclude module: 'support-annotations' } - api rootProject.ext.dependencies["recyclerview-v7"] - api rootProject.ext.dependencies["palette-v7"] - api(rootProject.ext.dependencies["cardview-v7"]) { + compile rootProject.ext.dependencies["recyclerview-v7"] + compile rootProject.ext.dependencies["palette-v7"] + compile(rootProject.ext.dependencies["cardview-v7"]) { exclude module: 'support-annotations' } - api rootProject.ext.dependencies["percent"] - api 'com.android.support.constraint:constraint-layout:1.0.2' - api rootProject.ext.dependencies["marqueelibrary"] - api( rootProject.ext.dependencies["vlayout"]) { + compile rootProject.ext.dependencies["percent"] + compile 'com.android.support.constraint:constraint-layout:1.0.2' + compile rootProject.ext.dependencies["marqueelibrary"] + compile(rootProject.ext.dependencies["vlayout"]) { transitive = true } - api rootProject.ext.dependencies["zxing"] - api rootProject.ext.dependencies["banner"] - api rootProject.ext.dependencies["ultra-ptr"] - api rootProject.ext.dependencies["flowlayout"] - api rootProject.ext.dependencies["photoview"] - api rootProject.ext.dependencies["PickerView"] - api rootProject.ext.dependencies["switchbutton"] - api rootProject.ext.dependencies["countdownview"] - api rootProject.ext.dependencies["MagicIndicator"] - api rootProject.ext.dependencies["FlycoDialog_Lib"] - api rootProject.ext.dependencies["glide-transformations"] - api rootProject.ext.dependencies["zxing-android-embedded"] - api rootProject.ext.dependencies["circular-progress-button-v7"] - api rootProject.ext.dependencies["BaseRecyclerViewAdapterHelper"] + compile rootProject.ext.dependencies["zxing"] + compile rootProject.ext.dependencies["banner"] + compile rootProject.ext.dependencies["ultra-ptr"] + compile rootProject.ext.dependencies["flowlayout"] + compile rootProject.ext.dependencies["photoview"] + compile rootProject.ext.dependencies["PickerView"] + compile rootProject.ext.dependencies["switchbutton"] + compile rootProject.ext.dependencies["countdownview"] + compile rootProject.ext.dependencies["MagicIndicator"] + compile rootProject.ext.dependencies["FlycoDialog_Lib"] + compile rootProject.ext.dependencies["glide-transformations"] + compile rootProject.ext.dependencies["zxing-android-embedded"] + compile rootProject.ext.dependencies["circular-progress-button-v7"] + compile rootProject.ext.dependencies["BaseRecyclerViewAdapterHelper"] } diff --git a/build.gradle b/build.gradle index f9d3ad0..8297990 100644 --- a/build.gradle +++ b/build.gradle @@ -2,11 +2,24 @@ apply from: "version.gradle" buildscript { repositories { - google() jcenter() + mavenLocal() + maven { + // url "http://mvnrepo.alibaba-inc.com/mvn/repository" + url "http://maven.aliyun.com/nexus/content/groups/public" + } + maven { + url 'https://maven.google.com/' + name 'Google' + } + } + configurations.all { + resolutionStrategy.cacheDynamicVersionsFor 0, 'seconds' + resolutionStrategy.cacheChangingModulesFor 0, 'seconds' } dependencies { - classpath 'com.android.tools.build:gradle:3.0.1' +// classpath 'com.android.tools.build:gradle:3.0.1' + classpath "com.taobao.android:atlasplugin:2.3.3.rc41" classpath 'me.tatarka:gradle-retrolambda:3.2.5' // classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' // classpath 'com.novoda:bintray-release:0.3.4' @@ -15,12 +28,33 @@ buildscript { } } +/*阿里 atlas */ +ext { + lib_atlas_core = "com.taobao.android:atlas_core:5.0.7.55@aar" + lib_atlas_update = "com.taobao.android:atlasupdate:1.1.4.14@aar" +} + +subprojects { + repositories { + jcenter() + maven { +// url "http://mvnrepo.alibaba-inc.com/mvn/repository" + url "http://maven.aliyun.com/nexus/content/groups/public" + } + } +} + + +/*阿里 atlas */ allprojects { repositories { jcenter() mavenCentral() maven { url "https://jitpack.io" } - google() + maven { + url 'https://maven.google.com/' + name 'Google' + } } tasks.withType(Javadoc) { options.addStringOption('Xdoclint:none', '-quiet') diff --git a/girls/build.gradle b/girls/build.gradle index 4296967..9de51c5 100644 --- a/girls/build.gradle +++ b/girls/build.gradle @@ -2,8 +2,23 @@ if (isApp.toBoolean()) { apply plugin: 'com.android.application' } else { apply plugin: 'com.android.library' + apply plugin: 'com.taobao.atlas' } //apply plugin: 'com.novoda.bintray-release'//添加 +group = 'com.dhc.flyabbit' +version = '1.0.0' + +atlas { + bundleConfig { + awbBundle true + } + buildTypes { + debug { + baseApFile project.rootProject.file('app/build/outputs/apk/app-debug.ap') + } + } +} + android { compileSdkVersion rootProject.ext.android.compileSdkVersion buildToolsVersion rootProject.ext.android.buildToolsVersion @@ -17,12 +32,13 @@ android { main { if (isApp.toBoolean()) { manifest.srcFile 'src/main/debug/AndroidManifest.xml' - } else { + } + else { manifest.srcFile 'src/main/release/AndroidManifest.xml' java { exclude 'src/main/debug/**' - exclude '**/debug/**.java' - exclude 'src/main/**/res/layout/activity_debug.xml' +// exclude '**/debug/**.java' +// exclude 'src/main/**/res/layout/activity_debug.xml' } } } @@ -53,10 +69,10 @@ android { abortOnError false } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } +// compileOptions { +// sourceCompatibility JavaVersion.VERSION_1_8 +// targetCompatibility JavaVersion.VERSION_1_8 +// } aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false } @@ -70,8 +86,9 @@ dependencies { testCompile rootProject.ext.dependencies["junit"] - api project(':library') + compile project(':library') + provided rootProject.ext.lib_atlas_core //dagger2的apt注解 annotationProcessor rootProject.ext.dependencies["dagger-compiler"] diff --git a/girls/bundleBaseInfoFile.json b/girls/bundleBaseInfoFile.json new file mode 100644 index 0000000..4a0b9df --- /dev/null +++ b/girls/bundleBaseInfoFile.json @@ -0,0 +1,4 @@ +{ + "name": "第一个bundle", + "dependency": ["com.dhc.flyabbit.gank"] +} \ No newline at end of file diff --git a/girls/src/main/java/com/dhc/flyabbit/gank/debug/GirlsDebugActivity.java b/girls/src/main/java/com/dhc/flyabbit/gank/debug/GirlsDebugActivity.java index 1581eff..a811c03 100644 --- a/girls/src/main/java/com/dhc/flyabbit/gank/debug/GirlsDebugActivity.java +++ b/girls/src/main/java/com/dhc/flyabbit/gank/debug/GirlsDebugActivity.java @@ -2,6 +2,7 @@ import android.os.Bundle; +import com.dhc.flyabbit.gank.R; import com.dhc.flyabbit.gank.ui.GankFragment; import com.dhc.library.base.XDaggerActivity; diff --git a/girls/src/main/java/com/dhc/flyabbit/gank/ui/adapter/GirlAdapter.java b/girls/src/main/java/com/dhc/flyabbit/gank/ui/adapter/GirlAdapter.java index e8cd0f5..c59a06d 100644 --- a/girls/src/main/java/com/dhc/flyabbit/gank/ui/adapter/GirlAdapter.java +++ b/girls/src/main/java/com/dhc/flyabbit/gank/ui/adapter/GirlAdapter.java @@ -29,7 +29,7 @@ public GirlAdapter(@Nullable List data) { @Override - protected void convert(BaseViewHolder helper, GankItemBean item) { + protected void convert(final BaseViewHolder helper, final GankItemBean item) { //存在记录的高度时先Layout再异步加载图片 if (item.getHeight() > 0) { ViewGroup.LayoutParams layoutParams = helper.getView(R.id.iv_girl).getLayoutParams(); diff --git a/girls/src/main/release/AndroidManifest.xml b/girls/src/main/release/AndroidManifest.xml index 7d8a934..e091b5d 100644 --- a/girls/src/main/release/AndroidManifest.xml +++ b/girls/src/main/release/AndroidManifest.xml @@ -8,7 +8,7 @@ android:label="@string/app_name" android:supportsRtl="true" > - + diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 280aa33..85e5f78 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Wed Feb 28 10:32:29 CST 2018 +#Mon Mar 05 13:16:23 CST 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip diff --git a/home/build.gradle b/home/build.gradle index b8516c1..7eee144 100644 --- a/home/build.gradle +++ b/home/build.gradle @@ -2,7 +2,24 @@ if (isApp.toBoolean()) { apply plugin: 'com.android.application' } else { apply plugin: 'com.android.library' + apply plugin: 'com.taobao.atlas' } + +group = 'com.dhc.flyabbit' +version = '1.0.0' + +atlas { + bundleConfig { + awbBundle true + } + buildTypes { + debug { + baseApFile project.rootProject.file('app/build/outputs/apk/app-debug.ap') + } + } +} + + //apply plugin: 'com.novoda.bintray-release'//添加 android { compileSdkVersion rootProject.ext.android.compileSdkVersion @@ -21,8 +38,8 @@ android { manifest.srcFile 'src/main/release/AndroidManifest.xml' java { exclude 'src/main/debug/**' - exclude '**/debug/**.java' - exclude 'src/main/**/res/layout/activity_debug.xml' +// exclude '**/debug/**.java' +// exclude 'src/main/**/res/layout/activity_debug.xml' } } } @@ -53,10 +70,10 @@ android { abortOnError false } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } +// compileOptions { +// sourceCompatibility JavaVersion.VERSION_1_8 +// targetCompatibility JavaVersion.VERSION_1_8 +// } aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false } @@ -70,7 +87,9 @@ dependencies { testCompile rootProject.ext.dependencies["junit"] - api project(':library') + provided rootProject.ext.lib_atlas_core + + compile project(':library') //dagger2的apt注解 annotationProcessor rootProject.ext.dependencies["dagger-compiler"] diff --git a/home/src/main/release/AndroidManifest.xml b/home/src/main/release/AndroidManifest.xml index d76a37b..7a5a388 100644 --- a/home/src/main/release/AndroidManifest.xml +++ b/home/src/main/release/AndroidManifest.xml @@ -1,3 +1,4 @@ + - + diff --git a/my/build.gradle b/my/build.gradle index 8bc3fd7..46e3e2d 100644 --- a/my/build.gradle +++ b/my/build.gradle @@ -2,8 +2,25 @@ if (isApp.toBoolean()) { apply plugin: 'com.android.application' } else { apply plugin: 'com.android.library' + apply plugin: 'com.taobao.atlas' } + +group = 'com.dhc.flyabbit' +version = '1.0.0' + apply plugin: 'me.tatarka.retrolambda' + +atlas { + bundleConfig { + awbBundle true + } + buildTypes { + debug { + baseApFile project.rootProject.file('app/build/outputs/apk/app-debug.ap') + } + } +} + //apply plugin: 'com.novoda.bintray-release'//添加 android { compileSdkVersion rootProject.ext.android.compileSdkVersion @@ -22,8 +39,8 @@ android { manifest.srcFile 'src/main/release/AndroidManifest.xml' java { exclude 'src/main/debug/**' - exclude '**/debug/**.java' - exclude 'src/main/**/res/layout/activity_debug.xml' +// exclude '**/debug/**.java' +// exclude 'src/main/**/res/layout/activity_debug.xml' } } } @@ -54,9 +71,9 @@ android { abortOnError false } - retrolambda { - javaVersion JavaVersion.VERSION_1_7 - } +// retrolambda { +// javaVersion JavaVersion.VERSION_1_7 +// } aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false dexOptions { @@ -83,6 +100,8 @@ dependencies { //阿里的Arouter的注解 annotationProcessor rootProject.ext.dependencies["arouter-compiler"] + + provided rootProject.ext.lib_atlas_core } diff --git a/my/src/main/release/AndroidManifest.xml b/my/src/main/release/AndroidManifest.xml index 5215995..fa6721d 100644 --- a/my/src/main/release/AndroidManifest.xml +++ b/my/src/main/release/AndroidManifest.xml @@ -8,7 +8,7 @@ android:label="@string/app_name" android:supportsRtl="true" > - + diff --git a/settings.gradle b/settings.gradle index 3624fa7..eac0301 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,7 +1,7 @@ -include ':app', ':library', ':imageloader', ':uikit',':home', ':my', ':girls' +include ':app', ':library', ':imageloader', ':uikit', ':home', ':my', ':girls', ':activitygroupcompat' -project(':library').projectDir = new File('baselib\\library') -//project(':businesslib').projectDir = new File('baselib/businesslib') +project(':library').projectDir = new File('baselib/library') +project(':activitygroupcompat').projectDir = new File('baselib/activitygroupcompat') project(':imageloader').projectDir = new File('baselib/imageloader') project(':uikit').projectDir = new File('baselib/uikit') diff --git a/version.gradle b/version.gradle index d0c3cd4..b4bd25c 100644 --- a/version.gradle +++ b/version.gradle @@ -10,7 +10,7 @@ ext { versionCode : 1, versionName : '.1.0', - VSupportSdk : '26.+', + VSupportSdk : '27.0.2', VJunit : '4.12', VRxlifecycle : "2.0.1", From bb39b6fdf47a89c1101b039c9cec0819d0454bc6 Mon Sep 17 00:00:00 2001 From: denghc Date: Wed, 7 Mar 2018 17:45:11 +0800 Subject: [PATCH 2/5] =?UTF-8?q?=E6=B7=BB=E5=8A=A0atlas=E5=AE=9E=E8=B7=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- girls/build.gradle | 2 +- home/build.gradle | 2 +- my/build.gradle | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/girls/build.gradle b/girls/build.gradle index 9de51c5..f9148b6 100644 --- a/girls/build.gradle +++ b/girls/build.gradle @@ -86,7 +86,7 @@ dependencies { testCompile rootProject.ext.dependencies["junit"] - compile project(':library') + providedCompile project(':library') provided rootProject.ext.lib_atlas_core //dagger2的apt注解 diff --git a/home/build.gradle b/home/build.gradle index 7eee144..0d6bc7e 100644 --- a/home/build.gradle +++ b/home/build.gradle @@ -89,7 +89,7 @@ dependencies { provided rootProject.ext.lib_atlas_core - compile project(':library') + providedCompile project(':library') //dagger2的apt注解 annotationProcessor rootProject.ext.dependencies["dagger-compiler"] diff --git a/my/build.gradle b/my/build.gradle index 46e3e2d..b08fef8 100644 --- a/my/build.gradle +++ b/my/build.gradle @@ -93,7 +93,7 @@ dependencies { testCompile rootProject.ext.dependencies["junit"] - compile project(':library') + providedCompile project(':library') //dagger2的apt注解 annotationProcessor rootProject.ext.dependencies["dagger-compiler"] From a920252d95a46ec5583c72bc3b853eca807d5015 Mon Sep 17 00:00:00 2001 From: denghc Date: Wed, 21 Mar 2018 18:42:51 +0800 Subject: [PATCH 3/5] add photoView&as remote bundle ,dynamic loading --- app/build.gradle | 3 + .../com/dhc/flyabbit/DownLoadManager.java | 94 +++++++++++++++++++ .../main/java/com/dhc/flyabbit/app/App.java | 75 +++++++++++++-- .../di/component/HActivityComponent.java | 3 +- .../modle/DownLoadlRemoteDataService.java | 30 ++++++ .../com/dhc/flyabbit/modle/IDownLoadApi.java | 21 +++++ .../flyabbit/presenter/DownLoadPresenter.java | 63 +++++++++++++ .../presenter/contract/IDownLoadContract.java | 37 ++++++++ baselib/library/build.gradle | 6 +- .../library/ExampleInstrumentedTest.java | 87 ++++++++++++++++- .../com/fanyu/library/ExampleUnitTest.java | 85 ++++++++++++++++- girls/build.gradle | 3 + .../presenter/contract/IGirlContract.java | 6 +- .../dhc/flyabbit/gank/ui/GirlFragment.java | 8 +- photoview/.gitignore | 1 + photoview/build.gradle | 51 ++++++++++ photoview/proguard-rules.pro | 21 +++++ photoview/push_dexpatch_out.sh | 9 ++ .../filyabbit/ExampleInstrumentedTest.java | 26 +++++ photoview/src/main/AndroidManifest.xml | 17 ++++ .../java/com/dhc/filyabbit/ImgActivity.java | 54 +++++++++++ .../src/main/res/layout/activity_img.xml | 14 +++ photoview/src/main/res/values/strings.xml | 3 + .../com/dhc/filyabbit/ExampleUnitTest.java | 17 ++++ settings.gradle | 2 +- 25 files changed, 712 insertions(+), 24 deletions(-) create mode 100644 app/src/main/java/com/dhc/flyabbit/DownLoadManager.java create mode 100644 app/src/main/java/com/dhc/flyabbit/modle/DownLoadlRemoteDataService.java create mode 100644 app/src/main/java/com/dhc/flyabbit/modle/IDownLoadApi.java create mode 100644 app/src/main/java/com/dhc/flyabbit/presenter/DownLoadPresenter.java create mode 100644 app/src/main/java/com/dhc/flyabbit/presenter/contract/IDownLoadContract.java create mode 100644 photoview/.gitignore create mode 100644 photoview/build.gradle create mode 100644 photoview/proguard-rules.pro create mode 100644 photoview/push_dexpatch_out.sh create mode 100644 photoview/src/androidTest/java/com/dhc/filyabbit/ExampleInstrumentedTest.java create mode 100644 photoview/src/main/AndroidManifest.xml create mode 100644 photoview/src/main/java/com/dhc/filyabbit/ImgActivity.java create mode 100644 photoview/src/main/res/layout/activity_img.xml create mode 100644 photoview/src/main/res/values/strings.xml create mode 100644 photoview/src/test/java/com/dhc/filyabbit/ExampleUnitTest.java diff --git a/app/build.gradle b/app/build.gradle index 5c3cfea..633f6ac 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -105,6 +105,7 @@ atlas { autoStartBundles = ['com.dhc.flyabbit.gank'] //自启动bundle配置 autoStartBundles = ['com.dhc.flyabbit.home'] //自启动bundle配置 autoStartBundles = ['com.dhc.flyabbit.my'] //自启动bundle配置 + outOfApkBundles = ['photoview'] // outOfApkBundles = ['remotebundle'] // preLaunch = 'com.taobao.demo.DemoPreLaunch' classInject false @@ -170,7 +171,9 @@ dependencies { bundleCompile project(':my') bundleCompile project(':home') bundleCompile project(':girls') + bundleCompile project(':photoview') compile project(':library') + // providedCompile project(':girls') } compile project(':activitygroupcompat') diff --git a/app/src/main/java/com/dhc/flyabbit/DownLoadManager.java b/app/src/main/java/com/dhc/flyabbit/DownLoadManager.java new file mode 100644 index 0000000..eb43ed6 --- /dev/null +++ b/app/src/main/java/com/dhc/flyabbit/DownLoadManager.java @@ -0,0 +1,94 @@ +package com.dhc.flyabbit; + +import android.content.Context; +import android.util.Log; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import okhttp3.ResponseBody; + + +public class DownLoadManager { + + private static final String TAG = "DownLoadManager"; + + private static String APK_CONTENTTYPE = "application/vnd.android.package-archive"; + + private static String PNG_CONTENTTYPE = "image/png"; + + private static String JPG_CONTENTTYPE = "image/jpg"; + + private static String fileSuffix = ""; + + public static boolean writeResponseBodyToDisk(Context context, ResponseBody body, String fileName) { + + Log.d(TAG, "contentType:>>>>" + body.contentType().toString()); + + String type = body.contentType().toString(); + + if (type.equals(APK_CONTENTTYPE)) { + + fileSuffix = ".apk"; + } else if (type.equals(PNG_CONTENTTYPE)) { + fileSuffix = ".png"; + } + + // 其他类型同上 自己判断加入..... + + String path = context.getExternalCacheDir().getAbsolutePath(); + + Log.d(TAG, "path:>>>>" + path); + + try { + File futureStudioIconFile = new File(path,fileName); + + InputStream inputStream = null; + OutputStream outputStream = null; + + try { + byte[] fileReader = new byte[4096]; + + long fileSize = body.contentLength(); + long fileSizeDownloaded = 0; + + inputStream = body.byteStream(); + outputStream = new FileOutputStream(futureStudioIconFile); + + while (true) { + int read = inputStream.read(fileReader); + + if (read == -1) { + break; + } + + outputStream.write(fileReader, 0, read); + + fileSizeDownloaded += read; + + Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize); + } + + outputStream.flush(); + + + return true; + } catch (IOException e) { + return false; + } finally { + if (inputStream != null) { + inputStream.close(); + } + + if (outputStream != null) { + outputStream.close(); + } + } + } catch (IOException e) { + return false; + } + } +} \ No newline at end of file diff --git a/app/src/main/java/com/dhc/flyabbit/app/App.java b/app/src/main/java/com/dhc/flyabbit/app/App.java index 72e4f51..b260f6d 100644 --- a/app/src/main/java/com/dhc/flyabbit/app/App.java +++ b/app/src/main/java/com/dhc/flyabbit/app/App.java @@ -5,12 +5,11 @@ import android.content.Intent; import android.content.pm.PackageInfo; import android.content.res.Configuration; +import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatDelegate; import android.taobao.atlas.bundleInfo.AtlasBundleInfoManager; import android.taobao.atlas.framework.Atlas; -import android.taobao.atlas.framework.BundleImpl; -import android.taobao.atlas.framework.BundleInstaller; import android.taobao.atlas.runtime.ActivityTaskMgr; import android.taobao.atlas.runtime.ClassNotFoundInterceptorCallback; import android.text.TextUtils; @@ -18,21 +17,31 @@ import com.alibaba.android.arouter.facade.annotation.Autowired; import com.alibaba.android.arouter.launcher.ARouter; +import com.dhc.flyabbit.di.component.DaggerHActivityComponent; +import com.dhc.flyabbit.presenter.DownLoadPresenter; +import com.dhc.flyabbit.presenter.contract.IDownLoadContract; +import com.dhc.library.base.BaseApplication; import com.dhc.library.utils.ApplicationLike; import com.dhc.library.utils.AsLibUtil; -import com.dhc.library.base.BaseApplication; +import com.flyco.animation.BounceEnter.BounceTopEnter; +import com.flyco.animation.SlideExit.SlideBottomExit; +import com.flyco.dialog.listener.OnBtnClickL; +import com.flyco.dialog.widget.NormalDialog; import com.squareup.leakcanary.LeakCanary; +import com.trello.rxlifecycle2.LifecycleTransformer; import org.osgi.framework.BundleException; import java.io.File; +import javax.inject.Inject; + /** * 创建者:邓浩宸 * 时间 :2017/3/21 10:51 * 描述 :app 初始化 */ -public class App extends BaseApplication { +public class App extends BaseApplication implements IDownLoadContract.IView { @Autowired(name = "/home/application1") ApplicationLike mApplicationLikeMoudle1; @@ -44,7 +53,8 @@ public static synchronized BaseApplication getInstance() { return instance; } - + @Inject + DownLoadPresenter downLoadPresenter; static { AppCompatDelegate.setDefaultNightMode( AppCompatDelegate.MODE_NIGHT_NO); @@ -61,7 +71,12 @@ public void onCreate() { if (mApplicationLikeMoudle3!=null) AsLibUtil.addAsLIbChild(mApplicationLikeMoudle3); AsLibUtil.doCreateAsLibrary(this); - + DaggerHActivityComponent.builder() + .appComponent(BaseApplication.getAppComponent()) + .build().inject(this); + if (downLoadPresenter != null) + downLoadPresenter.attachView(this); +// https://bundle-1253245619.cos.ap-guangzhou.myqcloud.com/libcom_dhc_filyabbit.so Atlas.getInstance().setClassNotFoundInterceptorCallback(new ClassNotFoundInterceptorCallback() { @Override public Intent returnIntent(Intent intent) { @@ -79,6 +94,34 @@ public Intent returnIntent(Intent intent) { path = remoteBundleFile.getAbsolutePath(); }else { Toast.makeText(activity, " 远程bundle不存在,请确定 : " + remoteBundleFile.getAbsolutePath() , Toast.LENGTH_LONG).show(); + if (("lib"+bundleName.replace(".", "_") + ".so").equals("libcom_dhc_filyabbit.so")) { + final NormalDialog dialog = new NormalDialog(activity); + dialog.content("图片查看器是在服务器下载的,是否下载?")// + .style(NormalDialog.STYLE_TWO)// + .titleTextSize(23)// + .btnText("残忍拒绝", "下载插件")// + .btnTextColor(Color.parseColor("#D4D4D4"), Color.parseColor("#383838"))// + .btnTextSize(16f, 16f)// + .showAnim(new BounceTopEnter())// + .dismissAnim(new SlideBottomExit())// + .show(); + dialog.setOnBtnClickL( + new OnBtnClickL() { + @Override + public void onBtnClick() { + dialog.dismiss(); + } + }, + new OnBtnClickL() { + @Override + public void onBtnClick() { + dialog.superDismiss(); + downLoadPresenter.download(" https://bundle-1253245619.cos.ap-guangzhou.myqcloud.com/libcom_dhc_filyabbit.so", "libcom_dhc_filyabbit.so"); + } + }); + dialog.show(); + + } return intent; } @@ -131,4 +174,24 @@ public void onConfigurationChanged(Configuration newConfig) { AsLibUtil. onConfigurationChanged(this, newConfig); } + @Override + public LifecycleTransformer bindLifecycle() { + return null; + } + + @Override + public Context getAContext() { + return this; + } + + @Override + public void showContent(Boolean downLoad) { + Toast.makeText(this, "下载成功", Toast + .LENGTH_LONG).show(); + } + + @Override + public void showError(String code, String msg) { + + } } diff --git a/app/src/main/java/com/dhc/flyabbit/di/component/HActivityComponent.java b/app/src/main/java/com/dhc/flyabbit/di/component/HActivityComponent.java index 62f399f..cf9d296 100644 --- a/app/src/main/java/com/dhc/flyabbit/di/component/HActivityComponent.java +++ b/app/src/main/java/com/dhc/flyabbit/di/component/HActivityComponent.java @@ -1,5 +1,6 @@ package com.dhc.flyabbit.di.component; +import com.dhc.flyabbit.app.App; import com.dhc.library.di.ActivityScope; import com.dhc.library.di.component.AppComponent; import com.dhc.library.di.module.ActivityModule; @@ -16,7 +17,7 @@ public interface HActivityComponent { -// void inject(WelcomeActivity WelcomeActivity); + void inject(App app); // // void inject(HomeActivity homeActivity); diff --git a/app/src/main/java/com/dhc/flyabbit/modle/DownLoadlRemoteDataService.java b/app/src/main/java/com/dhc/flyabbit/modle/DownLoadlRemoteDataService.java new file mode 100644 index 0000000..d8afd9d --- /dev/null +++ b/app/src/main/java/com/dhc/flyabbit/modle/DownLoadlRemoteDataService.java @@ -0,0 +1,30 @@ +package com.dhc.flyabbit.modle; + +import com.dhc.flyabbit.presenter.contract.IDownLoadContract; +import com.dhc.library.data.HttpHelper; +import javax.inject.Inject; +import io.reactivex.Flowable; +import okhttp3.ResponseBody; + +/** + * 创建者 邓浩宸 + * 创建时间 2016/12/9 14:17 + * 描述 TODO + */ + +public class DownLoadlRemoteDataService implements IDownLoadContract.IModle { + + private HttpHelper mHttpHelper; + public static final int NUM_OF_PAGE = 20; + @Inject + public DownLoadlRemoteDataService(HttpHelper httpHelper) { + this.mHttpHelper = httpHelper; + } + + + + @Override + public Flowable download( String url) { + return mHttpHelper.createApi(IDownLoadApi.class).download(url); + } +} diff --git a/app/src/main/java/com/dhc/flyabbit/modle/IDownLoadApi.java b/app/src/main/java/com/dhc/flyabbit/modle/IDownLoadApi.java new file mode 100644 index 0000000..a84aac5 --- /dev/null +++ b/app/src/main/java/com/dhc/flyabbit/modle/IDownLoadApi.java @@ -0,0 +1,21 @@ +package com.dhc.flyabbit.modle; + +import io.reactivex.Flowable; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Streaming; +import retrofit2.http.Url; + +/** + * 创建者 邓浩宸 + * 创建时间 2018/3/21 17:07 + * 描述 ${TODO} + */ + +public interface IDownLoadApi { + + + @GET + @Streaming + Flowable download( @Url String url); +} diff --git a/app/src/main/java/com/dhc/flyabbit/presenter/DownLoadPresenter.java b/app/src/main/java/com/dhc/flyabbit/presenter/DownLoadPresenter.java new file mode 100644 index 0000000..ac061b0 --- /dev/null +++ b/app/src/main/java/com/dhc/flyabbit/presenter/DownLoadPresenter.java @@ -0,0 +1,63 @@ +package com.dhc.flyabbit.presenter; + + +import com.dhc.flyabbit.DownLoadManager; +import com.dhc.flyabbit.modle.DownLoadlRemoteDataService; +import com.dhc.flyabbit.presenter.contract.IDownLoadContract; +import com.dhc.library.base.XPresenter; +import com.dhc.library.data.net.NetError; + +import javax.inject.Inject; + +import io.reactivex.Flowable; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.functions.Function; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.subscribers.ResourceSubscriber; +import okhttp3.ResponseBody; + +/** + * 创建者 邓浩宸 + * 创建时间 2016/12/9 14:17 + * 描述 妹纸 + */ + +public class DownLoadPresenter extends XPresenter implements IDownLoadContract.IPresenter { + private DownLoadlRemoteDataService mDownLoadlRemoteDataService; + + @Inject + public DownLoadPresenter(DownLoadlRemoteDataService downLoadlRemoteDataService) { + mDownLoadlRemoteDataService = downLoadlRemoteDataService; + } + + + @Override + public void download(String url, final String fileName) { + mDownLoadlRemoteDataService.download(url) + .map(new Function() { + @Override + public Boolean apply(ResponseBody responseBodyResponse) throws Exception { + return DownLoadManager.writeResponseBodyToDisk(getV().getAContext(), + responseBodyResponse,fileName); + } + }) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(new ResourceSubscriber() { + @Override + public void onNext(Boolean aBoolean) { + getV().showContent(aBoolean); + } + + @Override + public void onError(Throwable t) { + getV().showError("-1",t.getMessage()); + } + + @Override + public void onComplete() { + + } + }); + } +} diff --git a/app/src/main/java/com/dhc/flyabbit/presenter/contract/IDownLoadContract.java b/app/src/main/java/com/dhc/flyabbit/presenter/contract/IDownLoadContract.java new file mode 100644 index 0000000..9bb6e06 --- /dev/null +++ b/app/src/main/java/com/dhc/flyabbit/presenter/contract/IDownLoadContract.java @@ -0,0 +1,37 @@ +package com.dhc.flyabbit.presenter.contract; + +import com.dhc.library.base.IBaseModle; +import com.dhc.library.base.IBasePresenter; +import com.dhc.library.base.IBaseView; +import io.reactivex.Flowable; +import okhttp3.ResponseBody; + +/** + * 创建者:邓浩宸 + * 时间 :2018/3/21 17:10 + * 描述 :TODO 请描述该类职责 + */ +public interface IDownLoadContract { + + interface IView extends IBaseView { + + void showContent(Boolean downLoad); + + + void showError(String code, String msg); + } + + interface IPresenter extends IBasePresenter { + + void download( String url,String fileName); + + } + + interface IModle extends IBaseModle { + + + Flowable download( String url); + + } + +} diff --git a/baselib/library/build.gradle b/baselib/library/build.gradle index abaefb7..3744207 100644 --- a/baselib/library/build.gradle +++ b/baselib/library/build.gradle @@ -55,9 +55,9 @@ android { dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') -// androidTestCompile('com.android.support.test.espresso:espresso-core:3.0.1', { -// exclude group: 'com.android.support', module: 'support-annotations' -// }) + androidTestCompile('com.android.support.test.espresso:espresso-core:3.0.1', { + exclude group: 'com.android.support', module: 'support-annotations' + }) //test testCompile rootProject.ext.dependencies["junit"] compile rootProject.ext.dependencies["fragmentation"] diff --git a/baselib/library/src/androidTest/java/com/fanyu/library/ExampleInstrumentedTest.java b/baselib/library/src/androidTest/java/com/fanyu/library/ExampleInstrumentedTest.java index ca5ed42..cb1e7a6 100644 --- a/baselib/library/src/androidTest/java/com/fanyu/library/ExampleInstrumentedTest.java +++ b/baselib/library/src/androidTest/java/com/fanyu/library/ExampleInstrumentedTest.java @@ -3,9 +3,25 @@ import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; +import android.util.Log; import org.junit.Test; import org.junit.runner.RunWith; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; + +import io.reactivex.BackpressureStrategy; +import io.reactivex.Flowable; +import io.reactivex.FlowableEmitter; +import io.reactivex.FlowableOnSubscribe; +import io.reactivex.Observable; +import io.reactivex.ObservableEmitter; +import io.reactivex.ObservableOnSubscribe; +import io.reactivex.Observer; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.Disposable; +import io.reactivex.functions.Function; +import io.reactivex.schedulers.Schedulers; import static org.junit.Assert.*; @@ -16,11 +32,76 @@ */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { + private String TAG="1111"; + @Test public void useAppContext() throws Exception { - // Context of the app under test. - Context appContext = InstrumentationRegistry.getTargetContext(); + Flowable.create(new FlowableOnSubscribe() { + @Override + public void subscribe(FlowableEmitter e) throws Exception { + Log.e(TAG, "===create: " + Thread.currentThread().getName()); + e.onNext("1"); + } + }, BackpressureStrategy.ERROR) + .subscribeOn(AndroidSchedulers.mainThread()) + .observeOn(Schedulers.io()) + .map(new Function() { + @Override + public Integer apply(String s) throws Exception { + Log.e(TAG, "===String -> Integer: " + Thread.currentThread().getName()); + return Integer.valueOf(s); + } + }) + .observeOn(AndroidSchedulers.mainThread()) + .flatMap(new Function>() { + @Override + public Flowable apply(final Integer integer) throws Exception { + Log.e(TAG, "===Integer->Observable: " + Thread.currentThread().getName()); + return Flowable.create(new FlowableOnSubscribe() { + @Override + public void subscribe(FlowableEmitter e) throws Exception { + Log.e(TAG, "===Observable call: " + Thread.currentThread().getName()); + for (int i = 0; i < integer; i++) { + e.onNext(i + ""); + } + e.onComplete(); + } + },BackpressureStrategy.ERROR); + } + + }) + .observeOn(Schedulers.io()) + .map(new Function() { + @Override + public Long apply(String s) throws Exception { + Log.e(TAG, "===String->Long: " + Thread.currentThread().getName()); + return Long.parseLong(s); + } + + }) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(new Subscriber() { + + @Override + public void onSubscribe(Subscription s) { + + } + + @Override + public void onNext(Long aLong) { + Log.e(TAG, "===onNext: " + Thread.currentThread().getName()); + } + + @Override + public void onError(Throwable e) { + + } + + @Override + public void onComplete() { - assertEquals("com.kairu.library.test", appContext.getPackageName()); + } + }); } } diff --git a/baselib/library/src/test/java/com/fanyu/library/ExampleUnitTest.java b/baselib/library/src/test/java/com/fanyu/library/ExampleUnitTest.java index ab6a4a1..af48f1a 100644 --- a/baselib/library/src/test/java/com/fanyu/library/ExampleUnitTest.java +++ b/baselib/library/src/test/java/com/fanyu/library/ExampleUnitTest.java @@ -1,8 +1,18 @@ package com.fanyu.library; +import android.util.Log; + import org.junit.Test; -import static com.dhc.library.utils.ArithmeticUtil.randomCommon; +import io.reactivex.Observable; +import io.reactivex.ObservableEmitter; +import io.reactivex.ObservableOnSubscribe; +import io.reactivex.Observer; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.Disposable; +import io.reactivex.functions.Function; +import io.reactivex.schedulers.Schedulers; + import static org.junit.Assert.assertEquals; /** @@ -11,6 +21,8 @@ * @see Testing documentation */ public class ExampleUnitTest { + private String TAG="1111"; + @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); @@ -20,10 +32,73 @@ public void addition_isCorrect() throws Exception { @Test public void randomTest() { - int[] ints = randomCommon(0, 9, 1); - for (int i = 0; i < ints.length; i++) { - System.out.print(ints[i]); - } + Observable.create(new ObservableOnSubscribe() { + @Override + public void subscribe(ObservableEmitter e) throws Exception { + Log.e(TAG, "===create: " + Thread.currentThread().getName()); + e.onNext("1"); + } + + }).subscribeOn(AndroidSchedulers.mainThread()) + .observeOn(Schedulers.io()) + .map(new Function() { + @Override + public Integer apply(String s) throws Exception { + Log.e(TAG, "===String -> Integer: " + Thread.currentThread().getName()); + return Integer.valueOf(s); + } + }) + .observeOn(AndroidSchedulers.mainThread()) + .flatMap(new Function>() { + @Override + public Observable apply(final Integer integer) throws Exception { + Log.e(TAG, "===Integer->Observable: " + Thread.currentThread().getName()); + return Observable.create(new ObservableOnSubscribe() { + @Override + public void subscribe(ObservableEmitter e) throws Exception { + Log.e(TAG, "===Observable call: " + Thread.currentThread().getName()); + for (int i = 0; i < integer; i++) { + e.onNext(i + ""); + } + e.onComplete(); + } + }); + } + + }) + .observeOn(Schedulers.io()) + .map(new Function() { + @Override + public Long apply(String s) throws Exception { + Log.e(TAG, "===String->Long: " + Thread.currentThread().getName()); + return Long.parseLong(s); + } + + }) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(new Observer() { + @Override + public void onSubscribe(Disposable d) { + + } + + @Override + public void onNext(Long aLong) { + Log.e(TAG, "===onNext: " + Thread.currentThread().getName()); + } + + @Override + public void onError(Throwable e) { + + } + + @Override + public void onComplete() { + + } + }); + } } \ No newline at end of file diff --git a/girls/build.gradle b/girls/build.gradle index f9148b6..30cb1b1 100644 --- a/girls/build.gradle +++ b/girls/build.gradle @@ -94,6 +94,9 @@ dependencies { //阿里的Arouter的注解 annotationProcessor rootProject.ext.dependencies["arouter-compiler"] + + providedCompile project(':photoview') +// compile project(':photoview') } //这是上传jcenter使用,不用关心 diff --git a/girls/src/main/java/com/dhc/flyabbit/gank/presenter/contract/IGirlContract.java b/girls/src/main/java/com/dhc/flyabbit/gank/presenter/contract/IGirlContract.java index 9367271..425eee6 100644 --- a/girls/src/main/java/com/dhc/flyabbit/gank/presenter/contract/IGirlContract.java +++ b/girls/src/main/java/com/dhc/flyabbit/gank/presenter/contract/IGirlContract.java @@ -11,9 +11,9 @@ import io.reactivex.Flowable; /** - * 创建者:yqlee - * 时间 :2017-04-25 下午 5:40 - * 描述 :爱公益契约类 + * 创建者:邓浩宸 + * 时间 :2018/3/21 17:10 + * 描述 : */ public interface IGirlContract { diff --git a/girls/src/main/java/com/dhc/flyabbit/gank/ui/GirlFragment.java b/girls/src/main/java/com/dhc/flyabbit/gank/ui/GirlFragment.java index bdd37a7..5b41e05 100644 --- a/girls/src/main/java/com/dhc/flyabbit/gank/ui/GirlFragment.java +++ b/girls/src/main/java/com/dhc/flyabbit/gank/ui/GirlFragment.java @@ -1,5 +1,6 @@ package com.dhc.flyabbit.gank.ui; +import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; @@ -46,7 +47,6 @@ protected int getLayoutId() { @Override protected void initEventAndData(View view) { initView(); - mList = new ArrayList<>(); mAdapter = new GirlAdapter(mList); mStaggeredGridLayoutManager = new StaggeredGridLayoutManager(SPAN_COUNT, StaggeredGridLayoutManager.VERTICAL); @@ -65,7 +65,11 @@ public void onRefresh() { mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() { @Override public void onItemClick(BaseQuickAdapter adapter, View view, int position) { - //// TODO: 2017/8/28 查看图片 + GankItemBean gankItemBean= (GankItemBean) adapter.getData().get(position); + Intent intent = new Intent(); + intent.putExtra("url",gankItemBean.getUrl()); + intent.setClassName(_mActivity, "com.dhc.filyabbit.ImgActivity"); + startActivity(intent); } }); mPresenter.getGirlData(); diff --git a/photoview/.gitignore b/photoview/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/photoview/.gitignore @@ -0,0 +1 @@ +/build diff --git a/photoview/build.gradle b/photoview/build.gradle new file mode 100644 index 0000000..730650e --- /dev/null +++ b/photoview/build.gradle @@ -0,0 +1,51 @@ +apply plugin: 'com.android.library' +apply plugin: 'com.taobao.atlas' + +atlas.bundleConfig.awbBundle = true + +group = 'com.dhc.flyabbit' + +version = '1.0.0' +android { + compileSdkVersion rootProject.ext.android.compileSdkVersion + buildToolsVersion rootProject.ext.android.buildToolsVersion + + + defaultConfig { + minSdkVersion rootProject.ext.android.minSdkVersion + targetSdkVersion rootProject.ext.android.targetSdkVersion + javaCompileOptions { + annotationProcessorOptions { + arguments = [moduleName: project.getName()] + } + } + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + +} + +dependencies { + compile fileTree(include: ['*.jar'], dir: 'libs') + compile 'com.bm.photoview:library:1.4.1' + androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { + exclude group: 'com.android.support', module: 'support-annotations' + }) + + testCompile rootProject.ext.dependencies["junit"] + + providedCompile project(':library') + + //dagger2的apt注解 + annotationProcessor rootProject.ext.dependencies["dagger-compiler"] + + //阿里的Arouter的注解 + annotationProcessor rootProject.ext.dependencies["arouter-compiler"] + +// provided rootProject.ext.lib_atlas_core +} diff --git a/photoview/proguard-rules.pro b/photoview/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/photoview/proguard-rules.pro @@ -0,0 +1,21 @@ +# 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 diff --git a/photoview/push_dexpatch_out.sh b/photoview/push_dexpatch_out.sh new file mode 100644 index 0000000..977d5f7 --- /dev/null +++ b/photoview/push_dexpatch_out.sh @@ -0,0 +1,9 @@ +#!/bin/sh + +adb shell rm -rf /sdcard/Android/data/com.taobao.demo/cache +adb shell mkdir /sdcard/Android/data/com.taobao.demo/cache +adb push build/outputs/tpatch-debug/dexpatch-1.0.0.json /sdcard/Android/data/com.taobao.demo/cache/ +adb push build/outputs/tpatch-debug/1.0.0@1.0.0.tpatch /sdcard/Android/data/com.taobao.demo/cache/ + + +adb push libcom_dhc_filyabbit.so /sdcard/Android/data/com.dhc.flyabbit/cache/libcom_dhc_filyabbit.so \ No newline at end of file diff --git a/photoview/src/androidTest/java/com/dhc/filyabbit/ExampleInstrumentedTest.java b/photoview/src/androidTest/java/com/dhc/filyabbit/ExampleInstrumentedTest.java new file mode 100644 index 0000000..58195ac --- /dev/null +++ b/photoview/src/androidTest/java/com/dhc/filyabbit/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package com.dhc.filyabbit; + +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 Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() throws Exception { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getTargetContext(); + + assertEquals("com.dhc.filyabbit.test", appContext.getPackageName()); + } +} diff --git a/photoview/src/main/AndroidManifest.xml b/photoview/src/main/AndroidManifest.xml new file mode 100644 index 0000000..6efdc84 --- /dev/null +++ b/photoview/src/main/AndroidManifest.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + diff --git a/photoview/src/main/java/com/dhc/filyabbit/ImgActivity.java b/photoview/src/main/java/com/dhc/filyabbit/ImgActivity.java new file mode 100644 index 0000000..e9fe29f --- /dev/null +++ b/photoview/src/main/java/com/dhc/filyabbit/ImgActivity.java @@ -0,0 +1,54 @@ +package com.dhc.filyabbit; + +import android.app.Activity; +import android.os.Bundle; +import android.view.View; +import android.widget.Toast; + +import com.bm.library.PhotoView; +import com.dhc.lib.imageload.ImageLoaderManager; + + +/** + * Created by liuheng on 2015/6/21. + */ +public class ImgActivity extends Activity { + + + PhotoView mPhotoView; + String url ; + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_img); + url= getIntent().getStringExtra("url"); + mPhotoView = (PhotoView) findViewById(R.id.img1); + mPhotoView.enable(); + + mPhotoView.setOnLongClickListener(new View.OnLongClickListener() { + @Override + public boolean onLongClick(View v) { + Toast.makeText(ImgActivity.this, "长按了", Toast.LENGTH_SHORT).show(); + return false; + } + }); + +// 使用ImageLoader +// ImaggeLoaderConfiguration configuration = ImageLoaderConfiguration +// .createDefault(this); +// ImageLoader.getInstance().init(configuration); +// ImageLoader.etInstance().displayImage(url, (ImageView) findViewById(R.id.img1)); + + ImageLoaderManager.getInstance().showImage(ImageLoaderManager.getDefaultOptions + (mPhotoView,url)); + +// 使用Glide加载的gif图片同样支持缩放功能 +// Glide.with(this) +// .load(gif) +// .crossFade() +// .placeholder(R.mipmap.bbb) +// .into(((PhotoView) findViewById(R.id.img1))); + +// ImageLoaderManager.getInstance(). + } +} diff --git a/photoview/src/main/res/layout/activity_img.xml b/photoview/src/main/res/layout/activity_img.xml new file mode 100644 index 0000000..45165fa --- /dev/null +++ b/photoview/src/main/res/layout/activity_img.xml @@ -0,0 +1,14 @@ + + + + + \ No newline at end of file diff --git a/photoview/src/main/res/values/strings.xml b/photoview/src/main/res/values/strings.xml new file mode 100644 index 0000000..5d70a34 --- /dev/null +++ b/photoview/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + photovIew + diff --git a/photoview/src/test/java/com/dhc/filyabbit/ExampleUnitTest.java b/photoview/src/test/java/com/dhc/filyabbit/ExampleUnitTest.java new file mode 100644 index 0000000..e7a5958 --- /dev/null +++ b/photoview/src/test/java/com/dhc/filyabbit/ExampleUnitTest.java @@ -0,0 +1,17 @@ +package com.dhc.filyabbit; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Example local unit test, which will execute on the development machine (host). + * + * @see Testing documentation + */ +public class ExampleUnitTest { + @Test + public void addition_isCorrect() throws Exception { + assertEquals(4, 2 + 2); + } +} \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index eac0301..2405a86 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,4 +1,4 @@ -include ':app', ':library', ':imageloader', ':uikit', ':home', ':my', ':girls', ':activitygroupcompat' +include ':app', ':library', ':imageloader', ':uikit', ':home', ':my', ':girls', ':activitygroupcompat', ':photoview' project(':library').projectDir = new File('baselib/library') From ce38397f635ba0e123242acd794c64ed1ef1dd27 Mon Sep 17 00:00:00 2001 From: denghc Date: Thu, 29 Mar 2018 20:21:46 +0800 Subject: [PATCH 4/5] Merge remote-tracking branch 'remotes/origin/master' into feature-atlas # Conflicts: # app/build.gradle # app/src/main/java/com/dhc/flyabbit/app/App.java # app/src/main/java/com/dhc/flyabbit/ui/MainFragment.java # baselib/library/build.gradle # baselib/library/src/main/java/com/dhc/library/base/BaseApplication.java # baselib/library/src/main/java/com/dhc/library/utils/string/Base64Utils.java # baselib/uikit/build.gradle # build.gradle # girls/build.gradle # home/build.gradle # my/build.gradle # settings.gradle --- app/build.gradle | 28 +- .../main/java/com/dhc/flyabbit/app/App.java | 16 +- .../com/dhc/flyabbit/ui/MainFragment.java | 6 +- baselib/library/.gitignore | 2 - baselib/library/build.gradle | 117 --- baselib/library/gradle.properties | 18 - baselib/library/proguard-rules.pro | 76 -- .../library/ExampleInstrumentedTest.java | 107 -- baselib/library/src/main/AndroidManifest.xml | 16 - .../com/dhc/library/base/BaseActivity.java | 231 ----- .../com/dhc/library/base/BaseApplication.java | 114 -- .../java/com/dhc/library/base/BaseBean.java | 9 - .../library/base/BaseChildApplication.java | 86 -- .../com/dhc/library/base/BaseFragment.java | 397 ------- .../com/dhc/library/base/BaseSubscriber.java | 139 --- .../java/com/dhc/library/base/IBaseModle.java | 10 - .../com/dhc/library/base/IBasePresenter.java | 13 - .../java/com/dhc/library/base/IBaseView.java | 18 - .../dhc/library/base/InitializeService.java | 48 - .../java/com/dhc/library/base/VDelegate.java | 24 - .../com/dhc/library/base/VDelegateBase.java | 64 -- .../com/dhc/library/base/XDaggerActivity.java | 62 -- .../com/dhc/library/base/XDaggerFragment.java | 52 - .../library/base/XDataBindingActivity.java | 28 - .../library/base/XDataBindingFragment.java | 27 - .../java/com/dhc/library/base/XPresenter.java | 28 - .../dhc/library/component/CrashHandler.java | 77 -- .../java/com/dhc/library/data/DBHelper.java | 36 - .../java/com/dhc/library/data/HttpHelper.java | 204 ---- .../com/dhc/library/data/IDataHelper.java | 128 --- .../java/com/dhc/library/data/SPHelper.java | 329 ------ .../com/dhc/library/data/account/Account.java | 15 - .../library/data/account/AccountManager.java | 102 -- .../library/data/account/AccountProvider.java | 5 - .../library/data/account/AuthPreferences.java | 61 -- .../com/dhc/library/data/cache/ICache.java | 18 - .../dhc/library/data/cache/MemoryCache.java | 74 -- .../com/dhc/library/data/net/ApiResponse.java | 18 - .../library/data/net/CacheInterceptor.java | 58 -- .../dhc/library/data/net/CallInterceptor.java | 40 - .../com/dhc/library/data/net/NetError.java | 58 -- .../data/net/ProgressCancelListener.java | 12 - .../data/net/ProgressDialogHandler.java | 76 -- .../library/data/net/RetryWhenHandler.java | 61 -- .../data/net/StringConverterFactory.java | 52 - .../library/data/net/SubscriberListener.java | 25 - .../library/data/net/TokenInterceptor.java | 49 - .../com/dhc/library/di/ActivityScope.java | 18 - .../java/com/dhc/library/di/ContextLife.java | 20 - .../com/dhc/library/di/FragmentScope.java | 17 - .../library/di/component/AppComponent.java | 41 - .../dhc/library/di/module/ActivityModule.java | 28 - .../com/dhc/library/di/module/AppModule.java | 42 - .../com/dhc/library/di/module/DataModule.java | 79 -- .../dhc/library/di/module/FragmentModule.java | 31 - .../library/framework/IDaggerListener.java | 14 - .../framework/OnBackToFirstListener.java | 5 - .../library/framework/OnShowHomeListener.java | 12 - .../library/framework/anim/BelowAnimator.java | 49 - .../dhc/library/framework/anim/OAnimator.java | 49 - .../library/utils/AppBlockCanaryContext.java | 154 --- .../com/dhc/library/utils/AppContext.java | 28 - .../com/dhc/library/utils/AppManager.java | 119 --- .../java/com/dhc/library/utils/AppUtil.java | 203 ---- .../dhc/library/utils/ApplicationLike.java | 21 - .../com/dhc/library/utils/ArithmeticUtil.java | 278 ----- .../java/com/dhc/library/utils/AsLibUtil.java | 58 -- .../java/com/dhc/library/utils/BaseUtils.java | 119 --- .../com/dhc/library/utils/ClipboardUtil.java | 19 - .../java/com/dhc/library/utils/ColorUtil.java | 34 - .../com/dhc/library/utils/ImageSaveUtils.java | 58 -- .../com/dhc/library/utils/MaterialColor.java | 23 - .../com/dhc/library/utils/SpannableUtils.java | 677 ------------ .../com/dhc/library/utils/UploadUtil.java | 97 -- .../library/utils/file/AttachmentStore.java | 348 ------- .../com/dhc/library/utils/file/FileUtil.java | 653 ------------ .../library/utils/media/BitmapDecoder.java | 275 ----- .../dhc/library/utils/media/BitmapUtil.java | 162 --- .../dhc/library/utils/media/ImageUtil.java | 469 --------- .../library/utils/media/SampleSizeUtil.java | 136 --- .../utils/rx/BaseSubscriberListener.java | 79 -- .../java/com/dhc/library/utils/rx/RxUtil.java | 88 -- .../utils/storage/ExternalStorage.java | 194 ---- .../library/utils/storage/StorageType.java | 54 - .../library/utils/storage/StorageUtil.java | 124 --- .../dhc/library/utils/string/Base64Utils.java | 0 .../com/dhc/library/utils/string/HexDump.java | 172 --- .../com/dhc/library/utils/string/MD5.java | 57 - .../dhc/library/utils/string/SHA256Util.java | 65 -- .../dhc/library/utils/string/StringUtil.java | 483 --------- .../library/utils/string/UUIDGenerator.java | 31 - .../com/dhc/library/utils/sys/DateUtil.java | 663 ------------ .../dhc/library/utils/sys/DensityUtils.java | 173 ---- .../dhc/library/utils/sys/NetworkUtil.java | 975 ------------------ .../com/dhc/library/utils/sys/ScreenUtil.java | 173 ---- .../com/dhc/library/utils/sys/TimeUtil.java | 313 ------ baselib/library/src/main/res/anim/fade_in.xml | 26 - .../library/src/main/res/anim/fade_out.xml | 26 - .../src/main/res/anim/login_in_below.xml | 27 - .../src/main/res/anim/login_out_below.xml | 8 - baselib/library/src/main/res/anim/no_anim.xml | 4 - baselib/library/src/main/res/anim/not.xml | 24 - .../src/main/res/anim/pop_exit_no_anim.xml | 7 - .../src/main/res/anim/step_in_right.xml | 27 - .../src/main/res/anim/step_out_right.xml | 27 - .../main/res/layout/layout_library_base.xml | 20 - .../main/res/mipmap-xxhdpi/ic_noconnect.png | Bin 14898 -> 0 bytes .../main/res/mipmap-xxhdpi/ic_pagenofound.png | Bin 3812 -> 0 bytes .../library/src/main/res/values/styles.xml | 38 - .../com/fanyu/library/ExampleUnitTest.java | 104 -- baselib/uikit/build.gradle | 50 +- businesslib/businessComponent/build.gradle | 14 +- girls/build.gradle | 6 +- .../dhc/flyabbit/gank/ui/GankFragment.java | 3 +- home/build.gradle | 26 +- my/build.gradle | 32 +- photoview/build.gradle | 3 +- settings.gradle | 6 +- 118 files changed, 97 insertions(+), 11595 deletions(-) delete mode 100644 baselib/library/.gitignore delete mode 100644 baselib/library/build.gradle delete mode 100644 baselib/library/gradle.properties delete mode 100644 baselib/library/proguard-rules.pro delete mode 100644 baselib/library/src/androidTest/java/com/fanyu/library/ExampleInstrumentedTest.java delete mode 100644 baselib/library/src/main/AndroidManifest.xml delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/BaseActivity.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/BaseApplication.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/BaseBean.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/BaseChildApplication.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/BaseFragment.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/BaseSubscriber.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/IBaseModle.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/IBasePresenter.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/IBaseView.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/InitializeService.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/VDelegate.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/VDelegateBase.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/XDaggerActivity.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/XDaggerFragment.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/XDataBindingActivity.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/XDataBindingFragment.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/base/XPresenter.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/component/CrashHandler.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/DBHelper.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/HttpHelper.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/IDataHelper.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/SPHelper.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/account/Account.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/account/AccountManager.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/account/AccountProvider.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/account/AuthPreferences.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/cache/ICache.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/cache/MemoryCache.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/net/ApiResponse.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/net/CacheInterceptor.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/net/CallInterceptor.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/net/NetError.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/net/ProgressCancelListener.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/net/ProgressDialogHandler.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/net/RetryWhenHandler.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/net/StringConverterFactory.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/net/SubscriberListener.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/data/net/TokenInterceptor.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/di/ActivityScope.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/di/ContextLife.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/di/FragmentScope.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/di/component/AppComponent.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/di/module/ActivityModule.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/di/module/AppModule.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/di/module/DataModule.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/di/module/FragmentModule.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/framework/IDaggerListener.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/framework/OnBackToFirstListener.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/framework/OnShowHomeListener.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/framework/anim/BelowAnimator.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/framework/anim/OAnimator.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/AppBlockCanaryContext.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/AppContext.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/AppManager.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/AppUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/ApplicationLike.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/ArithmeticUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/AsLibUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/BaseUtils.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/ClipboardUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/ColorUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/ImageSaveUtils.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/MaterialColor.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/SpannableUtils.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/UploadUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/file/AttachmentStore.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/file/FileUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/media/BitmapDecoder.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/media/BitmapUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/media/ImageUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/media/SampleSizeUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/rx/BaseSubscriberListener.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/rx/RxUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/storage/ExternalStorage.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/storage/StorageType.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/storage/StorageUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/string/Base64Utils.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/string/HexDump.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/string/MD5.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/string/SHA256Util.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/string/StringUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/string/UUIDGenerator.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/sys/DateUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/sys/DensityUtils.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/sys/NetworkUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/sys/ScreenUtil.java delete mode 100644 baselib/library/src/main/java/com/dhc/library/utils/sys/TimeUtil.java delete mode 100644 baselib/library/src/main/res/anim/fade_in.xml delete mode 100644 baselib/library/src/main/res/anim/fade_out.xml delete mode 100644 baselib/library/src/main/res/anim/login_in_below.xml delete mode 100644 baselib/library/src/main/res/anim/login_out_below.xml delete mode 100644 baselib/library/src/main/res/anim/no_anim.xml delete mode 100644 baselib/library/src/main/res/anim/not.xml delete mode 100644 baselib/library/src/main/res/anim/pop_exit_no_anim.xml delete mode 100644 baselib/library/src/main/res/anim/step_in_right.xml delete mode 100644 baselib/library/src/main/res/anim/step_out_right.xml delete mode 100644 baselib/library/src/main/res/layout/layout_library_base.xml delete mode 100644 baselib/library/src/main/res/mipmap-xxhdpi/ic_noconnect.png delete mode 100644 baselib/library/src/main/res/mipmap-xxhdpi/ic_pagenofound.png delete mode 100644 baselib/library/src/main/res/values/styles.xml delete mode 100644 baselib/library/src/test/java/com/fanyu/library/ExampleUnitTest.java diff --git a/app/build.gradle b/app/build.gradle index 95f906a..25e71f7 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -69,13 +69,13 @@ android { // } - compileOptions { - - sourceCompatibility JavaVersion.VERSION_1_8 - - targetCompatibility JavaVersion.VERSION_1_8 - - } +// compileOptions { +// +// sourceCompatibility JavaVersion.VERSION_1_8 +// +// targetCompatibility JavaVersion.VERSION_1_8 +// +// } dexOptions { jumboMode true //jenkins上使用有问题 @@ -138,19 +138,17 @@ atlas { dependencies { - implementation fileTree(dir: 'libs', include: ['*.jar']) - androidTestImplementation 'com.android.support.test:runner:1.0.1' - androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' - testImplementation rootProject.ext.dependencies["junit"] + compile fileTree(include: ['*.jar'], dir: 'libs') + testCompile rootProject.ext.dependencies["junit"] provided rootProject.ext.dependencies["javax.annotation"] - debugImplementation rootProject.ext.dependencies["canary-debug"] - testImplementation rootProject.ext.dependencies["canary-test"] - releaseImplementation rootProject.ext.dependencies["canary-release"] + debugCompile rootProject.ext.dependencies["canary-debug"] + testCompile rootProject.ext.dependencies["canary-test"] + releaseCompile rootProject.ext.dependencies["canary-release"] //dagger2的apt注解 annotationProcessor rootProject.ext.dependencies["dagger-compiler"] //阿里的Arouter的注解 annotationProcessor rootProject.ext.dependencies["arouter-compiler"] - implementation project(':businessComponent') + compile project(':businessComponent') bundleCompile project(':my') bundleCompile project(':home') diff --git a/app/src/main/java/com/dhc/flyabbit/app/App.java b/app/src/main/java/com/dhc/flyabbit/app/App.java index b0006b4..9eabf76 100644 --- a/app/src/main/java/com/dhc/flyabbit/app/App.java +++ b/app/src/main/java/com/dhc/flyabbit/app/App.java @@ -17,12 +17,23 @@ import com.alibaba.android.arouter.facade.annotation.Autowired; import com.alibaba.android.arouter.launcher.ARouter; +import com.dhc.businesscomponent.Constants; +import com.dhc.businesscomponent.data.LoginInfoBean; +import com.dhc.flyabbit.presenter.DownLoadPresenter; +import com.dhc.flyabbit.presenter.contract.IDownLoadContract; +import com.dhc.lib.imageload.ImageLoaderManager; +import com.dhc.library.base.BaseApplication; +import com.dhc.library.data.IDataHelper; +import com.dhc.library.data.account.AccountProvider; +import com.dhc.library.utils.AppUtil; import com.dhc.library.utils.ApplicationLike; import com.dhc.library.utils.AsLibUtil; +import com.dhc.timberhelper.TimberInitHelper; import com.flyco.animation.BounceEnter.BounceTopEnter; import com.flyco.animation.SlideExit.SlideBottomExit; import com.flyco.dialog.listener.OnBtnClickL; import com.flyco.dialog.widget.NormalDialog; +import com.google.gson.GsonBuilder; import com.squareup.leakcanary.LeakCanary; import com.trello.rxlifecycle2.LifecycleTransformer; @@ -37,7 +48,7 @@ * 时间 :2017/3/21 10:51 * 描述 :app 初始化 */ -public class App extends BaseApplication implements IDownLoadContract.IView ,AccountProvider{ +public class App extends BaseApplication implements IDownLoadContract.IView ,AccountProvider { @Autowired(name = "/home/application1") ApplicationLike mApplicationLikeMoudle1; @@ -67,9 +78,6 @@ public void onCreate() { if (mApplicationLikeMoudle3!=null) AsLibUtil.addAsLIbChild(mApplicationLikeMoudle3); AsLibUtil.doCreateAsLibrary(this); - DaggerHActivityComponent.builder() - .appComponent(BaseApplication.getAppComponent()) - .build().inject(this); if (downLoadPresenter != null) downLoadPresenter.attachView(this); // https://bundle-1253245619.cos.ap-guangzhou.myqcloud.com/libcom_dhc_filyabbit.so diff --git a/app/src/main/java/com/dhc/flyabbit/ui/MainFragment.java b/app/src/main/java/com/dhc/flyabbit/ui/MainFragment.java index bd29d81..b26ffd1 100644 --- a/app/src/main/java/com/dhc/flyabbit/ui/MainFragment.java +++ b/app/src/main/java/com/dhc/flyabbit/ui/MainFragment.java @@ -1,14 +1,12 @@ package com.dhc.flyabbit.ui; +import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import com.alibaba.android.arouter.facade.annotation.Route; import com.dhc.flyabbit.R; -import com.dhc.flyabbit.gank.ui.GankFragment; -import com.dhc.flyabbit.home.ui.HomeFragment; -import com.dhc.flyabbit.my.MyFragment; import com.dhc.lib.widget.bottombar.BottomBar; import com.dhc.lib.widget.bottombar.BottomBarTab; import com.dhc.library.base.XDaggerFragment; @@ -16,7 +14,7 @@ import com.dhc.library.framework.OnBackToFirstListener; import com.taobao.android.ActivityGroupDelegate; - +import javax.annotation.Nullable; /** diff --git a/baselib/library/.gitignore b/baselib/library/.gitignore deleted file mode 100644 index a774788..0000000 --- a/baselib/library/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/build - diff --git a/baselib/library/build.gradle b/baselib/library/build.gradle deleted file mode 100644 index 3744207..0000000 --- a/baselib/library/build.gradle +++ /dev/null @@ -1,117 +0,0 @@ -apply plugin: 'com.android.library' -android { - - compileSdkVersion rootProject.ext.android.compileSdkVersion - buildToolsVersion rootProject.ext.android.buildToolsVersion - - defaultConfig { - minSdkVersion rootProject.ext.android.minSdkVersion - targetSdkVersion rootProject.ext.android.targetSdkVersion - javaCompileOptions { - annotationProcessorOptions { - arguments = [moduleName: project.getName()] - } - } - ndk { - abiFilters "armeabi-v7a" - abiFilters "x86" - } - } - - buildTypes { - - debug { - debuggable true - minifyEnabled false - buildConfigField "boolean", "IS_DEBUG", "true" - } - release { - //混淆 - minifyEnabled false - //加载默认混淆配置文件 - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - } - } - - lintOptions { - abortOnError false - } - - dataBinding { - enabled = true - } - aaptOptions.cruncherEnabled = false - aaptOptions.useNewCruncher = false - -// compileOptions { -// sourceCompatibility JavaVersion.VERSION_1_8 -// targetCompatibility JavaVersion.VERSION_1_8 -// } -// compileOptions { -// targetCompatibility 1.8 -// sourceCompatibility 1.8 -// } -} - -dependencies { - compile fileTree(include: ['*.jar'], dir: 'libs') - androidTestCompile('com.android.support.test.espresso:espresso-core:3.0.1', { - exclude group: 'com.android.support', module: 'support-annotations' - }) - //test - testCompile rootProject.ext.dependencies["junit"] - compile rootProject.ext.dependencies["fragmentation"] - //rx - compile rootProject.ext.dependencies["rxjava"] - compile(rootProject.ext.dependencies["rxandroid"]) { - exclude module: 'rxjava' - } - compile(rootProject.ext.dependencies["rxlifecycle"]) { - exclude module: 'rxjava' - } - compile(rootProject.ext.dependencies["rxlifecycle-android"]) { - exclude module: 'rxjava' - } - compile(rootProject.ext.dependencies["rxlifecycle-components"]) { - exclude module: 'rxjava' - } - //network - compile rootProject.ext.dependencies["gson"] - compile(rootProject.ext.dependencies["retrofit"]) { - exclude module: 'okhttp' - } - compile(rootProject.ext.dependencies["retrofit-converter-gson"]) { - exclude module: 'gson' - } - compile(rootProject.ext.dependencies["retrofit-adapter-rxjava"]) { - exclude module: 'rxjava' - } - - compile rootProject.ext.dependencies["okhttp3"] - compile rootProject.ext.dependencies["okhttp3-logging-interceptor"] - compile rootProject.ext.dependencies["glide-okhttp3-integration"] - //other - compile rootProject.ext.dependencies["rxpermissions"] - compile rootProject.ext.dependencies["Jolyglot-Gson"] -// compile rootProject.ext.dependencies["multidex"] - compile rootProject.ext.dependencies["RxCache"] - // //db - // compile files('libs/ormlite-android-4.49.jar') - // compile files('libs/ormlite-core-4.49.jar') - //canary - debugCompile rootProject.ext.dependencies["blockcanary-debug"] - releaseCompile rootProject.ext.dependencies["blockcanary-release"] - //Cookie - compile rootProject.ext.dependencies["PersistentCookieJar"] - //di - compile rootProject.ext.dependencies["dagger"] - compile rootProject.ext.dependencies["arouter-api"] - // compile rootProject.ext.dependencies["retrofit-converter-jackson"] - provided rootProject.ext.dependencies["javax.annotation"] - //dagger2的apt注解 - annotationProcessor rootProject.ext.dependencies["dagger-compiler"] - //阿里的Arouter的apt注解 - annotationProcessor rootProject.ext.dependencies["arouter-compiler"] - compile project(':imageloader') - compile project(':uikit') -} diff --git a/baselib/library/gradle.properties b/baselib/library/gradle.properties deleted file mode 100644 index c48b41d..0000000 --- a/baselib/library/gradle.properties +++ /dev/null @@ -1,18 +0,0 @@ -MAVEN_URL= http://krtool.kairutech.cn:8081/nexus/content/repositories/KrAndroidLib/ -MAVEN_SNAPSHOT_URL = http://krtool.kairutech.cn:8081/nexus/content/repositories/KrAndroidLib-snapshot/ -#对应maven的groupId值 -GROUP=com.fanyu.lib -#登录nexus oss的用户名 -NEXUS_USERNAME=haochen -#登录nexus oss的密码 -NEXUS_PASSWORD=123456 -# groupid -GROUP_ID =com.fanyu.lib -# type -TYPE = aar -# description -DESCRIPTION = dependences lib -#artifactId -ARTIFACT_ID = krlibrary -#archives file -ARCHIVES_FILE = library.aar \ No newline at end of file diff --git a/baselib/library/proguard-rules.pro b/baselib/library/proguard-rules.pro deleted file mode 100644 index 013f05d..0000000 --- a/baselib/library/proguard-rules.pro +++ /dev/null @@ -1,76 +0,0 @@ -## Proguard -# -#-basedirectory proguard-pro -# -#-include proguard-normal.pro -# -#-include proguard-self.pro -# -# -#-include proguard-avi-loading.pro -# -##-include proguard-butterknife.pro -# -#-include proguard-canary-debug.pro -# -#-include proguard-canary-release.pro -# -#-include proguard-constraint-layout.pro -# -#-include proguard-design.pro -# -#-include proguard-glide.pro -# -#-include proguard-google-gson.pro -# -#-include proguard-okhttp3-logging-interceptor.pro -# -#-include proguard-okhttp3.pro -# -#-include proguard-proguard-design.pro -# -#-include proguard-recyclerview-v7.pro -# -#-include proguard-retrofit-adapter-rxjava.pro -# -#-include proguard-retrofit-converter-gson.pro -# -#-include proguard-retrofit.pro -# -#-include proguard-rxandroid.pro -# -#-include proguard-rxjava.pro -# -#-include proguard-rxlifecycle.pro -# -#-include proguard-rxlifecycle-components.pro -# -#-include proguard-rxlifecycle.pro -# -#-include proguard-rxpermissions.pro -# -#-include proguard-support-v4.pro -# -#-include proguard-support-v7-appcompat.pro -# -#-include proguard-banner.pro -# -#-include proguard-rolambda.pro -# -#-include proguard-flyco.pro -# -#-include proguard-okio.pro -# -#-include proguard-rxcache.pro -# -#-include proguard-arouter.pro -# -#-include proguard-databinding.pro -# -#-include proguard-vlayout.pro -# -# -## ------------------------------- 自定义区 ------------------------------- -# -# -## ------------------------------- 自定义区 end ------------------------------- \ No newline at end of file diff --git a/baselib/library/src/androidTest/java/com/fanyu/library/ExampleInstrumentedTest.java b/baselib/library/src/androidTest/java/com/fanyu/library/ExampleInstrumentedTest.java deleted file mode 100644 index cb1e7a6..0000000 --- a/baselib/library/src/androidTest/java/com/fanyu/library/ExampleInstrumentedTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.fanyu.library; - -import android.content.Context; -import android.support.test.InstrumentationRegistry; -import android.support.test.runner.AndroidJUnit4; -import android.util.Log; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.reactivestreams.Subscriber; -import org.reactivestreams.Subscription; - -import io.reactivex.BackpressureStrategy; -import io.reactivex.Flowable; -import io.reactivex.FlowableEmitter; -import io.reactivex.FlowableOnSubscribe; -import io.reactivex.Observable; -import io.reactivex.ObservableEmitter; -import io.reactivex.ObservableOnSubscribe; -import io.reactivex.Observer; -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.Disposable; -import io.reactivex.functions.Function; -import io.reactivex.schedulers.Schedulers; - -import static org.junit.Assert.*; - -/** - * Instrumentation test, which will execute on an Android device. - * - * @see Testing documentation - */ -@RunWith(AndroidJUnit4.class) -public class ExampleInstrumentedTest { - private String TAG="1111"; - - @Test - public void useAppContext() throws Exception { - Flowable.create(new FlowableOnSubscribe() { - @Override - public void subscribe(FlowableEmitter e) throws Exception { - Log.e(TAG, "===create: " + Thread.currentThread().getName()); - e.onNext("1"); - } - }, BackpressureStrategy.ERROR) - .subscribeOn(AndroidSchedulers.mainThread()) - .observeOn(Schedulers.io()) - .map(new Function() { - @Override - public Integer apply(String s) throws Exception { - Log.e(TAG, "===String -> Integer: " + Thread.currentThread().getName()); - return Integer.valueOf(s); - } - }) - .observeOn(AndroidSchedulers.mainThread()) - .flatMap(new Function>() { - @Override - public Flowable apply(final Integer integer) throws Exception { - Log.e(TAG, "===Integer->Observable: " + Thread.currentThread().getName()); - return Flowable.create(new FlowableOnSubscribe() { - @Override - public void subscribe(FlowableEmitter e) throws Exception { - Log.e(TAG, "===Observable call: " + Thread.currentThread().getName()); - for (int i = 0; i < integer; i++) { - e.onNext(i + ""); - } - e.onComplete(); - } - },BackpressureStrategy.ERROR); - } - - }) - .observeOn(Schedulers.io()) - .map(new Function() { - @Override - public Long apply(String s) throws Exception { - Log.e(TAG, "===String->Long: " + Thread.currentThread().getName()); - return Long.parseLong(s); - } - - }) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(new Subscriber() { - - @Override - public void onSubscribe(Subscription s) { - - } - - @Override - public void onNext(Long aLong) { - Log.e(TAG, "===onNext: " + Thread.currentThread().getName()); - } - - @Override - public void onError(Throwable e) { - - } - - @Override - public void onComplete() { - - } - }); - } -} diff --git a/baselib/library/src/main/AndroidManifest.xml b/baselib/library/src/main/AndroidManifest.xml deleted file mode 100644 index e9912cc..0000000 --- a/baselib/library/src/main/AndroidManifest.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/baselib/library/src/main/java/com/dhc/library/base/BaseActivity.java b/baselib/library/src/main/java/com/dhc/library/base/BaseActivity.java deleted file mode 100644 index 1e01613..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/BaseActivity.java +++ /dev/null @@ -1,231 +0,0 @@ -package com.dhc.library.base; - -import android.content.Context; -import android.content.Intent; -import android.os.Build; -import android.os.Bundle; -import android.support.annotation.CallSuper; -import android.support.annotation.CheckResult; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.v7.widget.Toolbar; -import android.util.Log; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; - -import com.dhc.library.R; -import com.dhc.library.framework.IDaggerListener; -import com.trello.rxlifecycle2.LifecycleProvider; -import com.trello.rxlifecycle2.LifecycleTransformer; -import com.trello.rxlifecycle2.RxLifecycle; -import com.trello.rxlifecycle2.android.ActivityEvent; -import com.trello.rxlifecycle2.android.RxLifecycleAndroid; -import io.reactivex.Observable; -import io.reactivex.subjects.BehaviorSubject; -import me.yokeyword.fragmentation.SupportActivity; - -/** - * 创建者:邓浩宸 - * 时间 :2016/11/15 16:08 - * 描述 :无MVP的activity基类 - */ -public abstract class BaseActivity extends SupportActivity implements LifecycleProvider ,IDaggerListener { - protected Context mContext; -// private Toolbar toolbar; -// private ToolbarUtil mToolbarUtil; - private static final String TAG = BaseActivity.class.getSimpleName(); - private final BehaviorSubject lifecycleSubject = BehaviorSubject.create();//重写RxLife控制生命周期 - - protected T $(int resId) { - return (T) super.findViewById(resId); - } - - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - initInject(savedInstanceState); - super.onCreate(savedInstanceState); - lifecycleSubject.onNext(ActivityEvent.CREATE); - if (getLayout() > 0) { - setContentView(getLayout()); - } - mContext = this; - Log.i(TAG,"activity: " + getClass().getSimpleName() + " onCreate()"); - initEventAndData(savedInstanceState); - } - - protected void setToolBar(Toolbar toolbar, String title) { - toolbar.setTitle(title); - setSupportActionBar(toolbar); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - getSupportActionBar().setDisplayShowHomeEnabled(true); - toolbar.setNavigationOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - onBackPressedSupport(); - } - }); - } - -// /** -// * 设置标题栏 -// * -// * @param toolBarId -// * @param options -// */ -// public void setToolBar(int toolBarId, ToolBarOptions options) { -// setToolBar(toolBarId, options, false); -// } - - - -// public void setTitle(String title) { -// if (mToolbarUtil != null) -// mToolbarUtil.setTitle(title); -// } - - -// /** -// * 获取titile对象 -// * -// * @return -// */ -// public Toolbar getToolBar() { -// return toolbar; -// } - -// public int getToolBarHeight() { -// if (toolbar != null) { -// return toolbar.getHeight(); -// } -// -// return 0; -// } - - @Override - protected void onDestroy() { - lifecycleSubject.onNext(ActivityEvent.DESTROY); - super.onDestroy(); - Log.i(TAG,"activity: " + getClass().getSimpleName() + " onDestroy()"); - } - - /** - * 重新加载本页面 - */ - public final void reload() { - reload(false); - } - - /** - * 重新加载 - * - * @param isNeedAnim 是否是需要动画 - */ - public final void reload(boolean isNeedAnim) { - if (isNeedAnim) { - getWindow().setWindowAnimations(R.style.WindowAnimationFadeInOut); - recreate(); - } else { - Intent intent = getIntent(); - overridePendingTransition(0, 0); - intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); - finish(); - overridePendingTransition(R.anim.fade_in,0); - startActivity(intent); - } - } - @Override - public boolean onCreateOptionsMenu(Menu menu) { - if (-1 != getMenuId()) - getMenuInflater().inflate(getMenuId(), menu); - return true; - } - - public int getMenuId() { - return -1; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - return super.onOptionsItemSelected(item); - } - - /** - * 该方法回调时机为,Activity回退栈内Fragment的数量 小于等于1 时,默认finish Activity - * 请尽量复写该方法,避免复写onBackPress(),以保证SupportFragment内的onBackPressedSupport()回退事件正常执行 - */ - @Override - public void onBackPressedSupport() { - super.onBackPressedSupport(); - } - - protected boolean isCompatible(int apiLevel) { - return Build.VERSION.SDK_INT >= apiLevel; - } - - protected abstract int getLayout(); - - protected abstract void initEventAndData(Bundle savedInstanceState); - - - - /**------------------------ Rxlife用于管理Rxjava的生命周期的 ------------------------*/ - /** - * ------------------------ start ------------------------ - */ - - @Override - @NonNull - @CheckResult - public final Observable lifecycle() { - return lifecycleSubject.hide(); - } - - @Override - @NonNull - @CheckResult - public final LifecycleTransformer bindUntilEvent(@NonNull ActivityEvent event) { - return RxLifecycle.bindUntilEvent(lifecycleSubject, event); - } - - @Override - @NonNull - @CheckResult - public final LifecycleTransformer bindToLifecycle() { - return RxLifecycleAndroid.bindActivity(lifecycleSubject); - } - - - @Override - @CallSuper - protected void onStart() { - super.onStart(); - lifecycleSubject.onNext(ActivityEvent.START); - } - - @Override - @CallSuper - protected void onResume() { - super.onResume(); - lifecycleSubject.onNext(ActivityEvent.RESUME); - } - - @Override - @CallSuper - protected void onPause() { - lifecycleSubject.onNext(ActivityEvent.PAUSE); - super.onPause(); - } - - @Override - @CallSuper - protected void onStop() { - lifecycleSubject.onNext(ActivityEvent.STOP); - super.onStop(); - } - - - /**------------------------ Rxlife用于管理Rxjava的生命周期的 ------------------------*/ - /**------------------------ end ------------------------*/ -} diff --git a/baselib/library/src/main/java/com/dhc/library/base/BaseApplication.java b/baselib/library/src/main/java/com/dhc/library/base/BaseApplication.java deleted file mode 100644 index e434c13..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/BaseApplication.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.dhc.library.base; - - -import android.annotation.SuppressLint; -import android.app.Activity; -import android.app.Application; -import android.os.Bundle; - -import com.alibaba.android.arouter.launcher.ARouter; -import com.dhc.library.data.IDataHelper; -import com.dhc.library.di.component.AppComponent; -import com.dhc.library.di.component.DaggerAppComponent; -import com.dhc.library.di.module.AppModule; -import com.dhc.library.di.module.DataModule; -import com.dhc.library.utils.AppContext; -import com.dhc.library.utils.AppManager; -import com.dhc.library.utils.AppUtil; -import com.dhc.library.utils.sys.ScreenUtil; - -import me.yokeyword.fragmentation.Fragmentation; -import me.yokeyword.fragmentation.helper.ExceptionHandler; - -/** - * 创建者 邓浩宸 - * 创建时间 2017/3/23 18:03 - * 描述 基类app - */ -public class BaseApplication extends Application { - - protected static BaseApplication instance; - - - @Override - public void onCreate() { - super.onCreate(); - instance=this; - //保存appcotext的实例 - AppContext.init(this); - AppUtil.syncIsDebug(this.getApplicationContext());//判断是否是debug模式 - // init tools - ScreenUtil.init(this); - if (AppUtil.isDebug()) { - ARouter.openLog(); // 打印日志 - ARouter.openDebug(); // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险) - } - ARouter.init(instance); // 尽可能早,推荐在Application中初始化 - Fragmentation.builder() - .stackViewMode(Fragmentation.BUBBLE) - .debug(AppUtil.isDebug()) // 线上环境时,可能会遇到上述异常,此时debug=false,不会抛出该异常(避免crash),会捕获建议在回调处上传至我们的Crash检测服务器 - .handleException(new ExceptionHandler() { - @Override - public void onException(Exception e) { - // 以Bugtags为例子: 手动把捕获到的 Exception 传到 Bugtags 后台。 - // Bugtags.sendException(e); - } - }).install(); - //添加一个intentsetvice服务来初始化一些服务 - InitializeService.start(this); - - registerActivityLifecycleCallbacks(new SwitchBackgroundCallbacks()); - } - - public AppComponent getAppComponent() { - return DaggerAppComponent.builder() - .dataModule(new DataModule(getNetConfig())) - .appModule(new AppModule(instance)) - .build(); - - } - - public IDataHelper.NetConfig getNetConfig() { - return null; - } - - - private class SwitchBackgroundCallbacks implements Application.ActivityLifecycleCallbacks { - - @Override - public void onActivityCreated(Activity activity, Bundle bundle) { - AppManager.getInstance().addActivity(activity); - } - - @Override - public void onActivityStarted(Activity activity) { - - } - - @Override - public void onActivityResumed(Activity activity) { - - } - - @Override - public void onActivityPaused(Activity activity) { - - } - - @Override - public void onActivityStopped(Activity activity) { - - } - - @Override - public void onActivitySaveInstanceState(Activity activity, Bundle bundle) { - - } - - @Override - public void onActivityDestroyed(Activity activity) { - AppManager.getInstance().removeActivity(activity); - } - } - -} diff --git a/baselib/library/src/main/java/com/dhc/library/base/BaseBean.java b/baselib/library/src/main/java/com/dhc/library/base/BaseBean.java deleted file mode 100644 index 7fcd45b..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/BaseBean.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.dhc.library.base; - -/** - * 创建者 邓浩宸 - * 创建时间 2017/3/15 16:12 - * 描述 数据类的基类 - */ -public class BaseBean { -} diff --git a/baselib/library/src/main/java/com/dhc/library/base/BaseChildApplication.java b/baselib/library/src/main/java/com/dhc/library/base/BaseChildApplication.java deleted file mode 100644 index df9169c..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/BaseChildApplication.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.dhc.library.base; - -import android.app.Application; -import android.content.Context; -import android.content.res.Configuration; -import android.util.Log; - -import com.dhc.library.utils.ApplicationLike; - - - -/** - * 创建者:邓浩宸 - * 时间 :2017/3/23 18:04 - * 描述 :该Application只能放在子moudle中使用,用于moudle隔离 - */ - -public class BaseChildApplication extends BaseApplication implements ApplicationLike { - - private static final String TAG = BaseChildApplication.class.getSimpleName(); - - @Override - public void onCreate() { - super.onCreate(); - onCreateAsLibrary(this); - } - - @Override - public void onLowMemory() { - super.onLowMemory(); - onLowMemoryAsLibrary(this); - } - - @Override - public void onTrimMemory(int level) { - super.onTrimMemory(level); - onTrimMemoryAsLibrary(this, level); - } - - @Override - public void onTerminate() { - super.onTerminate(); - onTerminate(this); - } - - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - onConfigurationChanged(this, newConfig); - } - - @Override - public void onTerminate(Application application) { - Log.i(TAG,this.getClass().getName()+"onTerminate"); - } - - @Override - public void onCreateAsLibrary(Application application) { - Log.i(TAG,this.getClass().getName()+"onCreateAsLibrary"); - } - - @Override - public void onLowMemoryAsLibrary(Application application) { - Log.i(TAG,this.getClass().getName()+"onLowMemoryAsLibrary"); - } - - @Override - public void onTrimMemoryAsLibrary(Application application, int level) { - Log.i(TAG,this.getClass().getName()+"onTrimMemoryAsLibrary"); - } - - @Override - public void onConfigurationChanged(Application application, Configuration configuration) { - Log.i(TAG,this.getClass().getName()+"onConfigurationChanged"); - } - - /** - * arouter定义的启动之前的初始化(可以忽略) - */ - @Override - public void init(Context context) { - - } - - -} diff --git a/baselib/library/src/main/java/com/dhc/library/base/BaseFragment.java b/baselib/library/src/main/java/com/dhc/library/base/BaseFragment.java deleted file mode 100644 index 290d91f..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/BaseFragment.java +++ /dev/null @@ -1,397 +0,0 @@ -package com.dhc.library.base; - -import android.app.Activity; -import android.content.Context; -import android.os.Bundle; -import android.os.Handler; -import android.support.annotation.CheckResult; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.v7.widget.Toolbar; -import android.text.TextUtils; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.inputmethod.InputMethodManager; - -import com.dhc.library.framework.IDaggerListener; -import com.trello.rxlifecycle2.LifecycleProvider; -import com.trello.rxlifecycle2.LifecycleTransformer; -import com.trello.rxlifecycle2.RxLifecycle; -import com.trello.rxlifecycle2.android.FragmentEvent; -import com.trello.rxlifecycle2.android.RxLifecycleAndroid; - -import io.reactivex.Observable; -import io.reactivex.subjects.BehaviorSubject; -import me.yokeyword.fragmentation.SupportFragment; -import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator; -import me.yokeyword.fragmentation.anim.FragmentAnimator; - - -/** - * 创建者:邓浩宸 - * 时间 :2016/11/15 16:08 - * 描述 :无MVP的Fragment基类 - */ -public abstract class BaseFragment extends SupportFragment implements LifecycleProvider, IDaggerListener { - private static final Handler handler = new Handler(); - private static final String TAG = BaseFragment.class.getSimpleName(); -// private Toolbar toolbar; - protected View mView; - private boolean isInited = false; - //_mActivity在SupportFragment中已经在onAttach中绑定了activity可以直接使用 - protected Context mContext; -// private ToolbarUtil mToolbarUtil; - - - /** - * activity与frament绑定时调用 - */ - @Override - public void onAttach(Context context) { - mContext = context; - super.onAttach(context); - } - -// public ToolbarUtil getToolbarUtil() { -// return mToolbarUtil; -// } - - - public final Handler getHandler() { - return handler; - } - - /** - * 替代findviewbyid - * - * @param resId - * @param - * @return - */ - protected T $(int resId) { - return (T) mView.findViewById(resId); - } - - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - super.onCreateView(inflater, container, savedInstanceState); - lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW); - int layoutId = getLayoutId(); - if (layoutId > 0) - mView = inflater.inflate(layoutId, null); - initInject(savedInstanceState); - return mView; - } - - /** - * 默认为横向切换动画 - * - * @return - */ - @Override - public FragmentAnimator onCreateFragmentAnimator() { - return new DefaultHorizontalAnimator(); - } - - /** - * viem 创建的回调 - * - * @param view - * @param savedInstanceState - */ - @Override - public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - if (!useLazy()) { - isInited = true; - initEventAndData(view); - } - Log.i(TAG,this.getClass().getName()+"onViewCreated"); - } - - - @Override - public void onLazyInitView(@Nullable Bundle savedInstanceState) { - super.onLazyInitView(savedInstanceState); - if (useLazy()) { - isInited = true; - initEventAndData(mView); - Log.i(TAG,this.getClass().getName()+"onLazyInitView"); - } - } - - -// /** -// * 设置标题栏 -// * -// * @param toolBarId -// * @param options -// */ -// public void setToolBar(int toolBarId, ToolBarOptions options) { -// setToolBar(toolBarId, options, false); -// } - -// /** -// * 设置标题栏 -// * -// * @param toolBarId -// * @param options -// */ -// public void setToolBar(int toolBarId, ToolBarOptions options, boolean haveLine) { -// toolbar = (Toolbar) mView.findViewById(toolBarId); -// if (options == null) { -// throw new RuntimeException( -// " options is null "); -// } -// mToolbarUtil = new ToolbarUtil(_mActivity, toolbar, haveLine); -// if (!TextUtils.isEmpty(options.titleString)) { -// mToolbarUtil.setTitle(options.titleString); -// -// } else if (options.titleId != 0) { -// mToolbarUtil.setTitle(getContext().getText(options.titleId)); -// } -// if (options.mOptionsButtons != null && options.mOptionsButtons.size() > 0) { -// mToolbarUtil.addOptionButton(options.mOptionsButtons); -// } -// -// if (options.logoId != 0) { -// toolbar.setLogo(options.logoId); -// } -// if (options.isNeedNavigate) { -// toolbar.setNavigationIcon(options.navigateId); -// toolbar.setNavigationOnClickListener(new View.OnClickListener() { -// @Override -// public void onClick(View v) { -// doYouWantTodo(); -// pop(); -// } -// }); -// } -// } - - protected void doYouWantTodo() { - - } - -// public void setTitle(String title) { -// if (mToolbarUtil != null) -// mToolbarUtil.setTitle(title); -// } - - public boolean useLazy() { - return true; - } - - /** - * 延时弹出键盘 - * - * @param focus 键盘的焦点项 - */ - protected void showKeyboardDelayed(View focus) { - final View viewToFocus = focus; - if (focus != null) { - focus.requestFocus(); - } - - getHandler().postDelayed(new Runnable() { - @Override - public void run() { - if (viewToFocus == null || viewToFocus.isFocused()) { - showKeyboard(true); - } - } - }, 300); - } - - protected void showKeyboard(boolean isShow) { - Activity activity = getActivity(); - if (activity == null) { - return; - } - - InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); - if (imm == null) { - return; - } - - if (isShow) { - if (activity.getCurrentFocus() == null) { - imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); - } else { - imm.showSoftInput(activity.getCurrentFocus(), 0); - } - } else { - if (activity.getCurrentFocus() != null) { - imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), - InputMethodManager.HIDE_NOT_ALWAYS); - } - - } - } - - /** - * 判断软键盘是否弹出 - */ - public boolean isSHowKeyboard() { - if (_mActivity == null || getView() == null) - return false; - InputMethodManager imm = (InputMethodManager) _mActivity.getSystemService(mContext.INPUT_METHOD_SERVICE); - if (imm.hideSoftInputFromWindow(getView().getWindowToken(), 0)) { - imm.showSoftInput(getView(), 0); - return true; - //软键盘已弹出 - } else { - return false; - //软键盘未弹出 - } - } - -// /** -// * 获取titile对象 -// * -// * @return -// */ -// public Toolbar getToolBar() { -// return toolbar; -// } -// -// public int getToolBarHeight() { -// if (toolbar != null) { -// return toolbar.getHeight(); -// } -// -// return 0; -// } - - /** - * 当Fragment状态改变时调用 - * - * @param hidden - */ - @Override - public void onHiddenChanged(boolean hidden) { - super.onHiddenChanged(hidden); - // if (!isInited && !hidden) { - // isInited = true; - // if (mView != null) - // initEventAndData(mView); - // } - } - - - protected abstract int getLayoutId(); - - protected abstract void initEventAndData(View view); - - @Override - public boolean onBackPressedSupport() { - return super.onBackPressedSupport(); - } - - @Override - public void onSupportVisible() { - super.onSupportVisible(); - // todo,当该Fragment对用户可见时 - } - - @Override - public void onSupportInvisible() { - super.onSupportInvisible(); - // todo,当该Fragment对用户不可见时 - } - - /**------------------------ Rxlife用于管理Rxjava的生命周期的 ------------------------*/ - /** - * ------------------------ end ------------------------ - */ - - private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); - - @Override - @NonNull - @CheckResult - public final Observable lifecycle() { - return lifecycleSubject.hide(); - } - - @Override - @NonNull - @CheckResult - public final LifecycleTransformer bindUntilEvent(@NonNull FragmentEvent event) { - return RxLifecycle.bindUntilEvent(lifecycleSubject, event); - } - - @Override - @NonNull - @CheckResult - public final LifecycleTransformer bindToLifecycle() { - return RxLifecycleAndroid.bindFragment(lifecycleSubject); - } - - @Override - public void onAttach(android.app.Activity activity) { - super.onAttach(activity); - lifecycleSubject.onNext(FragmentEvent.ATTACH); - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - lifecycleSubject.onNext(FragmentEvent.CREATE); - } - - - @Override - public void onStart() { - super.onStart(); - lifecycleSubject.onNext(FragmentEvent.START); - } - - @Override - public void onResume() { - super.onResume(); - lifecycleSubject.onNext(FragmentEvent.RESUME); - } - - @Override - public void onPause() { - lifecycleSubject.onNext(FragmentEvent.PAUSE); - super.onPause(); - } - - @Override - public void onStop() { - lifecycleSubject.onNext(FragmentEvent.STOP); - super.onStop(); - } - - @Override - public void onDestroyView() { - lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW); - super.onDestroyView(); - mView = null; - mContext = null; - Log.i(TAG,this.getClass().getName()+"onDestroyView"); - - } - - @Override - public void onDestroy() { - lifecycleSubject.onNext(FragmentEvent.DESTROY); - super.onDestroy(); - } - - @Override - public void onDetach() { - lifecycleSubject.onNext(FragmentEvent.DETACH); - super.onDetach(); - } - /**------------------------ Rxlife用于管理Rxjava的生命周期的 ------------------------*/ - /**------------------------ end ------------------------*/ - - -} diff --git a/baselib/library/src/main/java/com/dhc/library/base/BaseSubscriber.java b/baselib/library/src/main/java/com/dhc/library/base/BaseSubscriber.java deleted file mode 100644 index 8cf7e08..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/BaseSubscriber.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.dhc.library.base; - -import android.content.Context; -import android.util.Log; - -import com.dhc.library.data.net.ApiResponse; -import com.dhc.library.data.net.NetError; -import com.dhc.library.data.net.ProgressCancelListener; -import com.dhc.library.data.net.SubscriberListener; - -import io.reactivex.subscribers.ResourceSubscriber; - - -/** - * 创建者:邓浩宸 - * 时间 :2017/6/20 12:16 - * 描述 :用于在Http请求开始时,自动显示一个ProgressDialog - * 在Http请求结束是,关闭ProgressDialog - * 调用者自己对请求数据进行处理 - */ -public class BaseSubscriber extends ResourceSubscriber implements ProgressCancelListener { - - private static final String TAG = "BaseSubscriber"; - protected SubscriberListener mSubscriberOnNextListener; -// private ProgressDialogHandler mHandler; - Context aContext; - - /** - * 该构造会出现一个自动弹出和消失的dialog,一般使用与通用情况,特殊情况请自行处理,也可以通过{@link SubscriberListener#isShowLoading()} - * - * @param mSubscriberOnNextListener - * @param aContext - */ - public BaseSubscriber(SubscriberListener mSubscriberOnNextListener, Context aContext) { - this.mSubscriberOnNextListener = mSubscriberOnNextListener; -// mHandler = new ProgressDialogHandler(aContext, this, false); - this.aContext = aContext; - } - - /** - * 使用该构造方法没有LoadingDialog - * - * @param mSubscriberOnNextListener - */ - public BaseSubscriber(SubscriberListener mSubscriberOnNextListener) { - this.mSubscriberOnNextListener = mSubscriberOnNextListener; - } - - @Override - protected void onStart() { - super.onStart(); - if (mSubscriberOnNextListener != null && mSubscriberOnNextListener.isShowLoading()) -// showProgressDialog(); - onBegin(); - } - - /** - * 订阅开始时调用 - * 显示ProgressDialog - */ - public void onBegin() { - Log.i(TAG, "onBegin"); - if (mSubscriberOnNextListener != null) { - mSubscriberOnNextListener.onBegin(); - } - } - -// private void showProgressDialog() { -// if (mHandler != null) { -// mHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget(); -// } -// } - -// private void dismissProgressDialog() { -// if (mHandler != null) { -// mHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget(); -// mHandler = null; -// } -// } - - /** - * 对错误进行统一处理 - * 隐藏ProgressDialog - * - * @param e - */ - @Override - public void onError(Throwable e) { - Log.i(TAG, "onError:" + e.toString()); - if (mSubscriberOnNextListener != null) { - mSubscriberOnNextListener.onError(e); - } - onComplete(); - } - - /** - * 完成,隐藏ProgressDialog - */ - @Override - public void onComplete() { - Log.i(TAG, "onCompleted"); - if (mSubscriberOnNextListener != null && mSubscriberOnNextListener.isShowLoading()) -// dismissProgressDialog(); - if (mSubscriberOnNextListener != null) { - mSubscriberOnNextListener.onCompleted(); - } - if (!this.isDisposed()) { - this.dispose(); - } - } - - - /** - * 将onNext方法中的返回结果交给Activity或Fragment自己处理,可以根据实际情况再封装 - * - * @param response 创建Subscriber时的泛型类型 - */ - @Override - public void onNext(T response) { - Log.i(TAG, "onNext"); - if (mSubscriberOnNextListener != null) { - if (response!=null) { - mSubscriberOnNextListener.onSuccess(response); - } - else { - mSubscriberOnNextListener.onFail(new NetError("数据为空",NetError.NoDataError)); - } - } - } - - - @Override - public void onCancelProgress() { - if (isDisposed()) - this.dispose(); -// if (mHandler != null) -// mHandler = null; - } -} \ No newline at end of file diff --git a/baselib/library/src/main/java/com/dhc/library/base/IBaseModle.java b/baselib/library/src/main/java/com/dhc/library/base/IBaseModle.java deleted file mode 100644 index 4efc27a..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/IBaseModle.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.dhc.library.base; - -/** - * 创建者 邓浩宸 - * 创建时间 2017/3/14 11:43 - * 描述 ${Modle请求数据的基类} - */ - -public interface IBaseModle { -} diff --git a/baselib/library/src/main/java/com/dhc/library/base/IBasePresenter.java b/baselib/library/src/main/java/com/dhc/library/base/IBasePresenter.java deleted file mode 100644 index 5b1479d..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/IBasePresenter.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.dhc.library.base; - -/** - * 创建者:邓浩宸 - * 时间 :2016/11/15 16:07 - * 描述 :Presenter基类 - */ -public interface IBasePresenter{ - - void attachView(V view); - - void detachView(); -} diff --git a/baselib/library/src/main/java/com/dhc/library/base/IBaseView.java b/baselib/library/src/main/java/com/dhc/library/base/IBaseView.java deleted file mode 100644 index 91feca7..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/IBaseView.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.dhc.library.base; - -import android.content.Context; - -import com.trello.rxlifecycle2.LifecycleTransformer; - -/** - * 创建者:邓浩宸 - * 时间 :2016/11/15 16:07 - * 描述 :View的基类 - */ -public interface IBaseView { - - LifecycleTransformer bindLifecycle() ; - - Context getAContext() ; - -} diff --git a/baselib/library/src/main/java/com/dhc/library/base/InitializeService.java b/baselib/library/src/main/java/com/dhc/library/base/InitializeService.java deleted file mode 100644 index 6056c2e..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/InitializeService.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.dhc.library.base; - -import android.app.IntentService; -import android.content.Context; -import android.content.Intent; - - - -/** - * 创建者:邓浩宸 - * 时间 :2017/5/23 12:52 - * 描述 :初始化的服务 - */ -public class InitializeService extends IntentService { - - private static final String ACTION_INIT_WHEN_APP_CREATE = "com.dhc.library.base.action.INIT"; - - public InitializeService() { - super("InitializeService"); - } - - public static void start(Context context) { - Intent intent = new Intent(context, InitializeService.class); - intent.setAction(ACTION_INIT_WHEN_APP_CREATE); - context.startService(intent); - } - - @Override - protected void onHandleIntent(Intent intent) { - if (intent != null) { - final String action = intent.getAction(); - if (ACTION_INIT_WHEN_APP_CREATE.equals(action)) { - performInit(); - } - } - } - - private void performInit() { - //log日志 -// if (AppUtil.isDebug()) { -// ARouter.openLog(); // 打印日志 -// ARouter.openDebug(); // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险) -// } -// ARouter.init(this.getApplication()); // 尽可能早,推荐在Application中初始化 - //初始化过度绘制检测 - //BlockCanary.install(this, new AppBlockCanaryContext()).start(); - } -} \ No newline at end of file diff --git a/baselib/library/src/main/java/com/dhc/library/base/VDelegate.java b/baselib/library/src/main/java/com/dhc/library/base/VDelegate.java deleted file mode 100644 index d2921be..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/VDelegate.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.dhc.library.base; - -import android.view.View; - - -/** - * 创建者:邓浩宸 - * 时间 :2017/3/28 16:44 - * 描述 :View的代理 - */ -public interface VDelegate { - void resume(); - - void pause(); - - void destory(); - - void visible(boolean flag, View view); - void gone(boolean flag, View view); - void inVisible(View view); - - void toastShort(String msg); - void toastLong(String msg); -} diff --git a/baselib/library/src/main/java/com/dhc/library/base/VDelegateBase.java b/baselib/library/src/main/java/com/dhc/library/base/VDelegateBase.java deleted file mode 100644 index 2c4228e..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/VDelegateBase.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.dhc.library.base; - -import android.content.Context; -import android.view.View; -import android.widget.Toast; - -/** - * 创建者:邓浩宸 - * 时间 :2017/3/28 16:44 - * 描述 :View的基础代理 - */ -public class VDelegateBase implements VDelegate { - - private Context context; - - private VDelegateBase(Context context) { - this.context = context; - } - - public static VDelegate create(Context context) { - return new VDelegateBase(context); - } - - - @Override - public void resume() { - - } - - @Override - public void pause() { - - } - - @Override - public void destory() { - - } - - @Override - public void visible(boolean flag, View view) { - if (flag) view.setVisibility(View.VISIBLE); - } - - @Override - public void gone(boolean flag, View view) { - if (flag) view.setVisibility(View.GONE); - } - - @Override - public void inVisible(View view) { - view.setVisibility(View.INVISIBLE); - } - - @Override - public void toastShort(String msg) { - Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); - } - - @Override - public void toastLong(String msg) { - Toast.makeText(context, msg, Toast.LENGTH_LONG).show(); - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/base/XDaggerActivity.java b/baselib/library/src/main/java/com/dhc/library/base/XDaggerActivity.java deleted file mode 100644 index 979e495..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/XDaggerActivity.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.dhc.library.base; - -import android.content.Context; -import android.os.Bundle; -import android.support.annotation.Nullable; - -import com.dhc.library.di.module.ActivityModule; -import com.trello.rxlifecycle2.LifecycleTransformer; - -import javax.inject.Inject; - - -/** - * 创建者:邓浩宸 - * 时间 :2016/11/15 16:06 - * 描述 :MVP activity基类 - */ -public abstract class XDaggerActivity extends BaseActivity implements IBaseView { - @Inject - protected T mPresenter; - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - - if (mPresenter != null) - mPresenter.attachView(this); - super.onCreate(savedInstanceState); - - } - - @Override - protected void onResume() { - super.onResume(); - } - - - - @Override - public LifecycleTransformer bindLifecycle() { - return this.bindToLifecycle(); - } - - - @Override - public Context getAContext() { - return this; - } - - - - protected ActivityModule getActivityModule() { - return new ActivityModule(this); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - if (mPresenter != null) - mPresenter.detachView(); - } - -} \ No newline at end of file diff --git a/baselib/library/src/main/java/com/dhc/library/base/XDaggerFragment.java b/baselib/library/src/main/java/com/dhc/library/base/XDaggerFragment.java deleted file mode 100644 index 642b145..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/XDaggerFragment.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.dhc.library.base; - -import android.content.Context; -import android.os.Bundle; -import android.support.annotation.Nullable; -import android.view.View; - -import com.dhc.library.di.module.FragmentModule; -import com.trello.rxlifecycle2.LifecycleTransformer; - -import javax.inject.Inject; - -/** - * 创建者:邓浩宸 - * 时间 :2016/11/15 16:07 - * 描述 :MVP Fragment基类 - */ -public abstract class XDaggerFragment extends BaseFragment implements IBaseView{ - - @Inject - protected T mPresenter; - public boolean isShowView=false; - protected FragmentModule getFragmentModule() { - return new FragmentModule(this); - } - - - @Override - public LifecycleTransformer bindLifecycle() { - return this.bindToLifecycle(); - } - @Override - public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { - if (mPresenter != null) { - isShowView = true; - mPresenter.attachView(this); - } - super.onViewCreated(view, savedInstanceState); - } - - @Override - public Context getAContext() { - return _mActivity; - } - - @Override - public void onDestroy() { - super.onDestroy(); - if (mPresenter != null) - mPresenter.detachView(); - } -} \ No newline at end of file diff --git a/baselib/library/src/main/java/com/dhc/library/base/XDataBindingActivity.java b/baselib/library/src/main/java/com/dhc/library/base/XDataBindingActivity.java deleted file mode 100644 index 95d344e..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/XDataBindingActivity.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.dhc.library.base; - -import android.databinding.DataBindingUtil; -import android.databinding.ViewDataBinding; -import android.os.Bundle; -import android.support.annotation.Nullable; -import android.view.View; - -/** - * 创建者 邓浩宸 - * 创建时间 2017/9/18 11:02 - * 描述 Databinding和Dagger2使用的Activity - */ - -public abstract class XDataBindingActivity

extends XDaggerActivity

{ - - - public B mViewBinding; - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - View rootView = getLayoutInflater().inflate(this.getLayout(), null, false); - mViewBinding = DataBindingUtil.bind(rootView); - super.onCreate(savedInstanceState); - } - - -} diff --git a/baselib/library/src/main/java/com/dhc/library/base/XDataBindingFragment.java b/baselib/library/src/main/java/com/dhc/library/base/XDataBindingFragment.java deleted file mode 100644 index fcda7ce..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/XDataBindingFragment.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.dhc.library.base; - -import android.databinding.DataBindingUtil; -import android.databinding.ViewDataBinding; -import android.os.Bundle; -import android.support.annotation.Nullable; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -/** - * 创建者 邓浩宸 - * 创建时间 2017/9/18 11:23 - * 描述 Databinding和Dagger2使用的Fragment - */ - -public abstract class XDataBindingFragment

extends XDaggerFragment

{ - public B mViewBinding; - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - mViewBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false); - return super.onCreateView(inflater, container, savedInstanceState); - } - -} diff --git a/baselib/library/src/main/java/com/dhc/library/base/XPresenter.java b/baselib/library/src/main/java/com/dhc/library/base/XPresenter.java deleted file mode 100644 index 1a93d45..0000000 --- a/baselib/library/src/main/java/com/dhc/library/base/XPresenter.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.dhc.library.base; - -/** - * 创建者:邓浩宸 - * 时间 :2016/11/15 16:08 - * 描述 :用于绑定view和解绑view - */ -public class XPresenter implements IBasePresenter { - - private V mView; - - @Override - public void attachView(V view) { - this.mView = view; - } - - @Override - public void detachView() { - this.mView = null; - } - - protected V getV() { - if (mView == null) { - throw new IllegalStateException("v can not be null"); - } - return mView; - } -} \ No newline at end of file diff --git a/baselib/library/src/main/java/com/dhc/library/component/CrashHandler.java b/baselib/library/src/main/java/com/dhc/library/component/CrashHandler.java deleted file mode 100644 index afb99bc..0000000 --- a/baselib/library/src/main/java/com/dhc/library/component/CrashHandler.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.dhc.library.component; - -import android.content.Context; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.widget.Toast; - - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.io.Writer; - - -/** - * 创建者:邓浩宸 - * 时间 :2016/11/15 16:08 - * 描述 :收集系统崩溃的类 - */ -public class CrashHandler implements Thread.UncaughtExceptionHandler { - - private static Thread.UncaughtExceptionHandler defaultHandler = null; - - private Context context = null; - - private final String TAG = CrashHandler.class.getSimpleName(); - - public CrashHandler(Context context) { - this.context = context; - } - - /** - * 初始化,设置该CrashHandler为程序的默认处理器 - */ - public static void init(CrashHandler crashHandler) { - defaultHandler = Thread.getDefaultUncaughtExceptionHandler(); - Thread.setDefaultUncaughtExceptionHandler(crashHandler); - } - - @Override - public void uncaughtException(Thread thread, Throwable ex) { - // 调用系统错误机制 - defaultHandler.uncaughtException(thread, ex); - Toast.makeText(context,"抱歉,程序发生异常即将退出",Toast.LENGTH_SHORT).show(); -// App.getInstance().exitApp(); - android.os.Process.killProcess(android.os.Process.myPid()); - System.exit(0); - } - - /** - * 得到程序崩溃的详细信息 - */ - public String getCrashInfo(Throwable ex) { - Writer result = new StringWriter(); - PrintWriter printWriter = new PrintWriter(result); - ex.setStackTrace(ex.getStackTrace()); - ex.printStackTrace(printWriter); - return result.toString(); - } - - /** - * 收集程序崩溃的设备信息 - */ - public String collectCrashDeviceInfo() { - try { - PackageManager pm = context.getPackageManager(); - PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES); - String versionName = pi.versionName; - String model = android.os.Build.MODEL; - String androidVersion = android.os.Build.VERSION.RELEASE; - String manufacturer = android.os.Build.MANUFACTURER; - return versionName + " " + model + " " + androidVersion + " " + manufacturer; - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/DBHelper.java b/baselib/library/src/main/java/com/dhc/library/data/DBHelper.java deleted file mode 100644 index 78fc052..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/DBHelper.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.dhc.library.data; - -import android.arch.persistence.room.Room; -import android.arch.persistence.room.RoomDatabase; -import android.content.Context; - -import java.util.HashMap; - -/** - * 创建者 邓浩宸 - * 创建时间 2018/3/27 16:38 - * 描述 ${TODO} - */ - -public class DBHelper { - private HashMap mServiceMap; - public Context context; - - public DBHelper(Context context) { - //Map used to store db - mServiceMap = new HashMap<>(); - this.context = context; - } - - @SuppressWarnings("unchecked") - public S getApi(Class serviceClass, String dbName) { - if (mServiceMap.containsKey(dbName)) { - return (S) mServiceMap.get(dbName); - } else { - Object obj = Room.databaseBuilder(context, serviceClass, dbName).build(); - mServiceMap.put(dbName, obj); - return (S) obj; - } - } - -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/HttpHelper.java b/baselib/library/src/main/java/com/dhc/library/data/HttpHelper.java deleted file mode 100644 index f9a4034..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/HttpHelper.java +++ /dev/null @@ -1,204 +0,0 @@ -package com.dhc.library.data; - -import android.content.Context; -import android.text.TextUtils; - -import com.dhc.library.data.net.CacheInterceptor; -import com.dhc.library.data.net.CallInterceptor; -import com.dhc.library.data.net.StringConverterFactory; -import com.dhc.library.data.net.TokenInterceptor; -import com.dhc.library.utils.AppContext; -import com.dhc.library.utils.AppUtil; -import com.dhc.library.utils.file.FileUtil; -import com.franmontiel.persistentcookiejar.ClearableCookieJar; -import com.franmontiel.persistentcookiejar.PersistentCookieJar; -import com.franmontiel.persistentcookiejar.cache.SetCookieCache; -import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import java.io.File; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; - -import okhttp3.Cache; -import okhttp3.OkHttpClient; -import okhttp3.logging.HttpLoggingInterceptor; -import retrofit2.Retrofit; -import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; -import retrofit2.converter.gson.GsonConverterFactory; - - -/** - * 创建者:邓浩宸 - * 时间 :2016/11/15 15:59 - * 描述 :网络请求的辅助类 - */ -public class HttpHelper implements IDataHelper { - - private static final String TAG = HttpHelper.class.getSimpleName(); - - private static NetConfig netConfig = new NetConfig(); - - private HashMap mServiceMap; - - private static OkHttpClient okHttpClient = null; - - private static Retrofit retrofit = null; - - public Context context; - - private Gson gson; - - - public HttpHelper(Context context) { - //Map used to store RetrofitService - mServiceMap = new HashMap<>(); - this.context = context; - } - - public void initConfig(NetConfig netConfig) { - this.netConfig = netConfig; - } - - - @SuppressWarnings("unchecked") - @Override - public S getApi(Class serviceClass) { - if (mServiceMap.containsKey(serviceClass.getName())) { - return (S) mServiceMap.get(serviceClass.getName()); - } else { - Object obj = createApi(serviceClass); - mServiceMap.put(serviceClass.getName(), obj); - return (S) obj; - } - } - - @SuppressWarnings("unchecked") - @Override - public S getApi(Class serviceClass, OkHttpClient client) { - if (mServiceMap.containsKey(serviceClass.getName())) { - return (S) mServiceMap.get(serviceClass.getName()); - } else { - Object obj = createApi(serviceClass, client); - mServiceMap.put(serviceClass.getName(), obj); - return (S) obj; - } - } - - @Override - public S createApi(Class serviceClass) { - return createApi(serviceClass, getOkHttpClient()); - } - - - @Override - public S createApi(Class serviceClass, OkHttpClient client) { - String baseURL = netConfig.baseURL; - if (netConfig.isUseMultiBaseURL) { - try { - Field field1 = serviceClass.getField("baseURL"); - baseURL = (String) field1.get(serviceClass); - } catch (NoSuchFieldException e) { - e.printStackTrace(); - baseURL = netConfig.baseURL; - } catch (IllegalAccessException e) { - e.getMessage(); - e.printStackTrace(); - baseURL = netConfig.baseURL; - } - if(TextUtils.isEmpty(baseURL)) - throw new RuntimeException("baseUrl is null .please init by NetModule or apiService field BaseUrl"); - } - if (retrofit != null && retrofit.baseUrl().host() == baseURL) { - return retrofit.create(serviceClass); - } else { - return getRetrofit(baseURL).create(serviceClass); - } - } - - @Override - public OkHttpClient getClient() { - if (okHttpClient != null) { - return okHttpClient; - } else { - return getOkHttpClient(); - } - } - - public Gson getGson() { - if (gson == null) - gson = new GsonBuilder().create();//Gson解析 - return gson; - } - - /** - * 如果是需要返回String的数据是使用 - * - * @return Retrofit - */ - public Retrofit getRetrofit(String host) { - if (gson == null) - gson = getGson();//Gson解析 - if (okHttpClient == null) - okHttpClient = getOkHttpClient(); - - Retrofit.Builder builder = new Retrofit.Builder(); - builder.baseUrl(host);//baseurl路径 - builder.client(okHttpClient)//添加客户端 - .addConverterFactory(new StringConverterFactory())//添加Gson格式化工厂 - .addConverterFactory(GsonConverterFactory.create(gson));//添加Gson格式化工厂 - if (netConfig.isUseRx) { - builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());//call 适配器 - } - retrofit = builder.build(); - return retrofit; - } - - - public OkHttpClient getOkHttpClient() { - ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));//对cooke自动管理管理 - File cacheFile = new File(FileUtil.getCacheDirectory(context), "ApiCookie");//缓存路径 - cacheFile = FileUtil.makeDirs(cacheFile); - Cache cache = new Cache(cacheFile, 1024 * 1024 * 40);//设置缓存大小为40M - //缓存 - CacheInterceptor cacheInterceptor = new CacheInterceptor(context); - //token管理 - TokenInterceptor tokenInterceptor = new TokenInterceptor(); - OkHttpClient.Builder builder = - new OkHttpClient.Builder() - .cache(cache) - .addInterceptor(cacheInterceptor) - .addInterceptor(tokenInterceptor) - .addNetworkInterceptor(cacheInterceptor) - // .retryOnConnectionFailure(true) - .connectTimeout(netConfig.connectTimeoutMills != 0 ? netConfig.connectTimeoutMills : 15, TimeUnit.SECONDS) - .writeTimeout(15, TimeUnit.SECONDS)//写超时超时 - .readTimeout(netConfig.readTimeoutMills != 0 ? netConfig.readTimeoutMills : 15, TimeUnit.SECONDS)//读超时 - .cookieJar(netConfig.mCookieJar != null ? netConfig.mCookieJar : cookieJar); - if (AppUtil.isDebug()) {//如果当前是debug模式就开启日志过滤器 - HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); - builder.addInterceptor(loggingInterceptor); - } - //设置https相关 - if (netConfig.mHttpsCall != null) { - netConfig.mHttpsCall.configHttps(builder); - } - if (netConfig.call != null) { - builder.addInterceptor(new CallInterceptor(netConfig.call)); - } - if (netConfig.mInterceptors != null) { - for (int i = 0; i < netConfig.mInterceptors.length; i++) { - builder.addInterceptor(netConfig.mInterceptors[i]); - } - - } - //当前okHttpClient - okHttpClient = builder.build(); - - return okHttpClient; - } - -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/IDataHelper.java b/baselib/library/src/main/java/com/dhc/library/data/IDataHelper.java deleted file mode 100644 index dc67a73..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/IDataHelper.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.dhc.library.data; - -import okhttp3.CookieJar; -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.ResponseBody; - -/** - * 创建者 邓浩宸 - * 创建时间 2017/3/28 13:04 - * 描述 数据处理接口类 - */ -public interface IDataHelper { - - public interface RequestCall { - - Request onBeforeRequest(Request request, Interceptor.Chain chain); - - Response onAfterRequest(Response response, ResponseBody result, Interceptor.Chain chain); - } - - public interface HttpsCall { - - void configHttps(OkHttpClient.Builder builder); - - } - public static class NetConfig { - public Interceptor[] mInterceptors; - public CookieJar mCookieJar; - public RequestCall call; - public HttpsCall mHttpsCall; - public long connectTimeoutMills; - public long readTimeoutMills; - public boolean isHasLog; - public boolean isUseRx = true; - public String baseURL = ""; - public boolean isUseMultiBaseURL = true; - - /** - * add okhttp Interceptors - * @param configInterceptors - * @return - */ - public NetConfig configInterceptors(Interceptor[] configInterceptors) { - this.mInterceptors = configInterceptors; - return this; - } - - /** - * can use multi baseurl {@link com.dhc.library.data.HttpHelper#createApi(java.lang.Class,okhttp3.OkHttpClient)} - * @param isUseMultiBaseURL - * @return - */ - public NetConfig configisUseMultiBaseURL(boolean isUseMultiBaseURL) { - this.isUseMultiBaseURL = isUseMultiBaseURL; - return this; - } - - /** - * root baseurl {@link com.dhc.library.data.HttpHelper#createApi(java.lang.Class,okhttp3.OkHttpClient)} - * @param baseURL - * @return - */ - public NetConfig configBaseURL(String baseURL) { - this.baseURL = baseURL; - return this; - } - - /** - * config cookieManager - * @param mCookieJar - * @return - */ - public NetConfig configCookieJar(CookieJar mCookieJar) { - this.mCookieJar = mCookieJar; - return this; - } - - /** - * - * @param call - * @return - */ - public NetConfig configCall(RequestCall call) { - this.call = call; - return this; - } - - public NetConfig configConnectTimeoutMills(long connectTimeoutMills) { - this.connectTimeoutMills = connectTimeoutMills; - return this; - } - - public NetConfig configReadTimeoutMills(long readTimeoutMills) { - this.readTimeoutMills = readTimeoutMills; - return this; - } - - public NetConfig configLogEnable(boolean isHasLog) { - this.isHasLog = isHasLog; - return this; - } - - public NetConfig configIsUseRx(boolean isUseRx) { - this.isUseRx = isUseRx; - return this; - } - - public NetConfig configHttps(HttpsCall mHttpsCall) { - this.mHttpsCall = mHttpsCall; - return this; - } - } - - S getApi(Class serviceClass); - - S createApi(Class serviceClass); - - S getApi(Class serviceClass, OkHttpClient client); - - S createApi(Class serviceClass, OkHttpClient client); - - OkHttpClient getClient(); - - void initConfig(HttpHelper.NetConfig netConfig); -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/SPHelper.java b/baselib/library/src/main/java/com/dhc/library/data/SPHelper.java deleted file mode 100644 index 6950036..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/SPHelper.java +++ /dev/null @@ -1,329 +0,0 @@ -package com.dhc.library.data; - -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.io.StreamCorruptedException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Map; - -/** - * 创建者:邓浩宸 - * 时间 :2016/10/9 11:26 - * 描述 :SharedPreferences统一管理类 - */ -public class SPHelper { - /** - * 保存在手机里面的文件名 - */ - public static final String FILE_NAME = "share_data"; - public static final String VERSION_FILE_NAME = "version_file_name"; - - - /** - * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 - * - * @param context - * @param key - * @param object - */ - public static void put(Context context, String key, Object object) { - put(context, key, object, FILE_NAME); - } - - /** - * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 - * - * @param context - * @param key - * @param object - * @param fileName - */ - public static void put(Context context, String key, Object object, String fileName) { - - SharedPreferences sp = context.getSharedPreferences(fileName, - Context.MODE_PRIVATE); - SharedPreferences.Editor editor = sp.edit(); - - if (object instanceof String) { - editor.putString(key, (String) object); - } else if (object instanceof Integer) { - editor.putInt(key, (Integer) object); - } else if (object instanceof Boolean) { - editor.putBoolean(key, (Boolean) object); - } else if (object instanceof Float) { - editor.putFloat(key, (Float) object); - } else if (object instanceof Long) { - editor.putLong(key, (Long) object); - } else { - if (object == null) - return; - editor.putString(key, object.toString()); - } - SharedPreferencesCompat.apply(editor); - } - - public static Object get(Context context, String key, Object defaultObject) { - return get(context, key, defaultObject, FILE_NAME); - } - - /** - * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 - * - * @param context - * @param key - * @param defaultObject - * @return - */ - public static Object get(Context context, String key, Object defaultObject, String fileName) { - SharedPreferences sp = context.getSharedPreferences(fileName, - Context.MODE_PRIVATE); - - if (defaultObject instanceof String) { - return sp.getString(key, (String) defaultObject); - } else if (defaultObject instanceof Long) { - return sp.getLong(key, (Long) defaultObject); - } else if (defaultObject instanceof Boolean) { - return sp.getBoolean(key, (Boolean) defaultObject); - } else if (defaultObject instanceof Float) { - return sp.getFloat(key, (Float) defaultObject); - } else if (defaultObject instanceof Integer) { - return sp.getInt(key, (Integer) defaultObject); - } - return null; - } - - /** - * 移除某个key值已经对应的值 - * - * @param context - * @param key - */ - public static void remove(Context context, String key) { - SharedPreferences sp = context.getSharedPreferences(FILE_NAME, - Context.MODE_PRIVATE); - SharedPreferences.Editor editor = sp.edit(); - editor.remove(key); - SharedPreferencesCompat.apply(editor); - } - - /** - * 清除所有数据 - * - * @param context - */ - public static void clear(Context context) { - SharedPreferences sp = context.getSharedPreferences(FILE_NAME, - Context.MODE_PRIVATE); - SharedPreferences.Editor editor = sp.edit(); - editor.clear(); - SharedPreferencesCompat.apply(editor); - } - - /** - * 查询某个key是否已经存在 - * - * @param context - * @param key - * @return - */ - public static boolean contains(Context context, String key) { - SharedPreferences sp = context.getSharedPreferences(FILE_NAME, - Context.MODE_PRIVATE); - return sp.contains(key); - } - - /** - * 返回所有的键值对 - * - * @param context - * @return - */ - public static Map getAll(Context context) { - SharedPreferences sp = context.getSharedPreferences(FILE_NAME, - Context.MODE_PRIVATE); - return sp.getAll(); - } - - /** - * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类 - * - * @author zhy - */ - private static class SharedPreferencesCompat { - private static final Method sApplyMethod = findApplyMethod(); - - /** - * 反射查找apply的方法 - * - * @return - */ - @SuppressWarnings({"unchecked", "rawtypes"}) - private static Method findApplyMethod() { - try { - Class clz = SharedPreferences.Editor.class; - return clz.getMethod("apply"); - } catch (NoSuchMethodException e) { - } - return null; - } - - /** - * 如果找到则使用apply执行,否则使用commit - * - * @param editor - */ - public static void apply(SharedPreferences.Editor editor) { - try { - if (sApplyMethod != null) { - sApplyMethod.invoke(editor); - return; - } - } catch (IllegalArgumentException e) { - } catch (IllegalAccessException e) { - } catch (InvocationTargetException e) { - } - editor.commit(); - } - } - - - /** - * desc:保存对象 - * - * @param context - * @param key - * @param obj 要保存的对象,只能保存实现了serializable的对象 - * modified: - */ - public static void saveObject(Context context, String key, Object obj) { - try { - // 保存对象 - SharedPreferences.Editor sharedata = context.getSharedPreferences(FILE_NAME, 0).edit(); - //先将序列化结果写到byte缓存中,其实就分配一个内存空间 - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream os = new ObjectOutputStream(bos); - //将对象序列化写入byte缓存 - os.writeObject(obj); - //将序列化的数据转为16进制保存 - String bytesToHexString = bytesToHexString(bos.toByteArray()); - //保存该16进制数组 - sharedata.putString(key, bytesToHexString); - sharedata.commit(); - } catch (IOException e) { - e.printStackTrace(); - Log.e("", "保存obj失败"); - } - } - - /** - * desc:将数组转为16进制 - * - * @param bArray - * @return modified: - */ - public static String bytesToHexString(byte[] bArray) { - if (bArray == null) { - return null; - } - if (bArray.length == 0) { - return ""; - } - StringBuffer sb = new StringBuffer(bArray.length); - String sTemp; - for (int i = 0; i < bArray.length; i++) { - sTemp = Integer.toHexString(0xFF & bArray[i]); - if (sTemp.length() < 2) - sb.append(0); - sb.append(sTemp.toUpperCase()); - } - return sb.toString(); - } - - /** - * desc:获取保存的Object对象 - * - * @param context - * @param key - * @return modified: - */ - public static Object readObject(Context context, String key) { - try { - SharedPreferences sharedata = context.getSharedPreferences(FILE_NAME, 0); - if (sharedata.contains(key)) { - String string = sharedata.getString(key, ""); - if (TextUtils.isEmpty(string)) { - return null; - } else { - //将16进制的数据转为数组,准备反序列化 - byte[] stringToBytes = StringToBytes(string); - ByteArrayInputStream bis = new ByteArrayInputStream(stringToBytes); - ObjectInputStream is = new ObjectInputStream(bis); - //返回反序列化得到的对象 - Object readObject = is.readObject(); - return readObject; - } - } - } catch (StreamCorruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - //所有异常返回null - return null; - - } - - /** - * desc:将16进制的数据转为数组 - *

创建人:聂旭阳 , 2014-5-25 上午11:08:33

- * - * @param data - * @return modified: - */ - public static byte[] StringToBytes(String data) { - String hexString = data.toUpperCase().trim(); - if (hexString.length() % 2 != 0) { - return null; - } - byte[] retData = new byte[hexString.length() / 2]; - for (int i = 0; i < hexString.length(); i++) { - int int_ch; // 两位16进制数转化后的10进制数 - char hex_char1 = hexString.charAt(i); ////两位16进制数中的第一位(高位*16) - int int_ch1; - if (hex_char1 >= '0' && hex_char1 <= '9') - int_ch1 = (hex_char1 - 48) * 16; //// 0 的Ascll - 48 - else if (hex_char1 >= 'A' && hex_char1 <= 'F') - int_ch1 = (hex_char1 - 55) * 16; //// A 的Ascll - 65 - else - return null; - i++; - char hex_char2 = hexString.charAt(i); ///两位16进制数中的第二位(低位) - int int_ch2; - if (hex_char2 >= '0' && hex_char2 <= '9') - int_ch2 = (hex_char2 - 48); //// 0 的Ascll - 48 - else if (hex_char2 >= 'A' && hex_char2 <= 'F') - int_ch2 = hex_char2 - 55; //// A 的Ascll - 65 - else - return null; - int_ch = int_ch1 + int_ch2; - retData[i / 2] = (byte) int_ch;//将转化后的数放入Byte里 - } - return retData; - } - - -} \ No newline at end of file diff --git a/baselib/library/src/main/java/com/dhc/library/data/account/Account.java b/baselib/library/src/main/java/com/dhc/library/data/account/Account.java deleted file mode 100644 index cfa91e3..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/account/Account.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.dhc.library.data.account; - -public interface Account { - - String name(); - - String accessToken(); - - String toJson(); - - String getUserId(); - - String getRelAvatar(); - -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/account/AccountManager.java b/baselib/library/src/main/java/com/dhc/library/data/account/AccountManager.java deleted file mode 100644 index e791435..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/account/AccountManager.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.dhc.library.data.account; - -import android.content.Context; -import android.text.TextUtils; - -import com.dhc.library.utils.AppContext; - - -/** - * 创建者:邓浩宸 - * 时间 :2017/6/29 17:42 - * 描述 :登陆账号管理类 - */ -public enum AccountManager { - - INSTANCE; - - private final AuthPreferences authPreferences; - private Account mCurrentAccount; - private Context mContext; - - AccountManager() { - mContext = AppContext.get(); - authPreferences = new AuthPreferences(AppContext.get()); - } - - public boolean isLogin() { - return authPreferences.isLogin(); - } - - public void logout() { - mCurrentAccount = null; - authPreferences.clear(); - } - - /** - * 更新用户数据 - * - * @param account - */ - public void refreshAccount(Account account) { - mCurrentAccount = account; - authPreferences.setAccessToken(account.accessToken()); - authPreferences.setUser(account.name()); - authPreferences.setUserData(account.toJson()); - } - - /** - * 登录成功获取存入数据 - * - * @param account - */ - public void storeAccount(Account account) { - mCurrentAccount = account; - authPreferences.setAccessToken(account.accessToken()); - authPreferences.setUser(account.name()); - authPreferences.setUserData(account.toJson()); - } - - public String getUserId() { - return getCurrentAccount() != null ? getCurrentAccount().getUserId() : ""; - } - - public String getAccessToken() { - return authPreferences.getAccessToken(); - } - - /** - * 刷新AccessToken - * - * @param token - */ - public void refreshAccessToken(String token) { - authPreferences.setAccessToken(token); - } - - public String getQRData(){ - return authPreferences.getQRData(); - } - - public void refreshQRData(String qrData){ - authPreferences.setQRData(qrData); - } - - public String user() { - return authPreferences.getUser(); - } - - @SuppressWarnings("unchecked") - public T getCurrentAccount() { - if (mCurrentAccount == null) { - String accountJson = authPreferences.getUserData(); - if (!TextUtils.isEmpty(accountJson) - && mContext instanceof AccountProvider) { - mCurrentAccount = (Account) ((AccountProvider) mContext).provideAccount(accountJson); - } - } - return (T) mCurrentAccount; - } - } - - diff --git a/baselib/library/src/main/java/com/dhc/library/data/account/AccountProvider.java b/baselib/library/src/main/java/com/dhc/library/data/account/AccountProvider.java deleted file mode 100644 index 382d7c2..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/account/AccountProvider.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.dhc.library.data.account; - -public interface AccountProvider { - T provideAccount(String accountJson); -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/account/AuthPreferences.java b/baselib/library/src/main/java/com/dhc/library/data/account/AuthPreferences.java deleted file mode 100644 index 6ea1ee2..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/account/AuthPreferences.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.dhc.library.data.account; - -import android.content.Context; -import android.text.TextUtils; - -import com.dhc.library.data.SPHelper; - -public class AuthPreferences { - - private static final String KEY_USER = "user"; - private static final String KEY_ACCESSTOKEN = "accessToken"; - private static final String KEY_USER_DATA = "user_data"; - private static final String KEY_QR_DATA = "qr_data"; - private Context mContext; - - public AuthPreferences(Context context) { - mContext = context; - } - - public void setUser(String user) { - SPHelper.put(mContext, KEY_USER, user); - } - - public void setAccessToken(String token) { - SPHelper.put(mContext, KEY_ACCESSTOKEN, token); - } - - public void setUserData(String userData) { - SPHelper.put(mContext, KEY_USER_DATA, userData); - } - - - public String getUser() { - return (String) SPHelper.get(mContext, KEY_USER, ""); - } - - public String getAccessToken() { - return SPHelper.get(mContext, KEY_ACCESSTOKEN, "").toString(); - } - - public String getQRData(){ - return SPHelper.get(mContext,KEY_QR_DATA,"").toString(); - } - - public void setQRData(String qrData){ - SPHelper.put(mContext,KEY_QR_DATA,qrData); - } - - public String getUserData() { - return (String) SPHelper.get(mContext, KEY_USER_DATA, ""); - } - - public void clear() { - SPHelper.clear(mContext); - } - - public boolean isLogin() { - return !TextUtils.isEmpty(getAccessToken()); - } - -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/cache/ICache.java b/baselib/library/src/main/java/com/dhc/library/data/cache/ICache.java deleted file mode 100644 index a18563d..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/cache/ICache.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.dhc.library.data.cache; - -/** - * Created by 邓浩宸 on 2016/11/27. - */ - -public interface ICache { - void put(String key, Object value); - - Object get(String key); - - void remove(String key); - - boolean contains(String key); - - void clear(); - -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/cache/MemoryCache.java b/baselib/library/src/main/java/com/dhc/library/data/cache/MemoryCache.java deleted file mode 100644 index 419c15a..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/cache/MemoryCache.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.dhc.library.data.cache; - -import android.support.v4.util.LruCache; -import android.text.TextUtils; - -/** - * Created by 邓浩宸 on 2016/11/28. - */ - -public class MemoryCache implements ICache { - - private LruCache cache; - private static MemoryCache instance; - - private MemoryCache() { - int maxMemory = (int) Runtime.getRuntime().maxMemory(); - int cacheSize = maxMemory / 8; - cache = new LruCache(cacheSize); - - } - - public static MemoryCache getInstance() { - if (instance == null) { - synchronized (MemoryCache.class) { - if (instance == null) { - instance = new MemoryCache(); - } - } - } - return instance; - } - - - @Override - public synchronized void put(String key, Object value) { - if (TextUtils.isEmpty(key)) return; - - if (cache.get(key) != null) { - cache.remove(key); - } - cache.put(key, value); - } - - @Override - public Object get(String key) { - return cache.get(key); - } - - public synchronized T get(String key, Class clazz) { - try { - return (T) cache.get(key); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - @Override - public void remove(String key) { - if (cache.get(key) != null) { - cache.remove(key); - } - } - - @Override - public boolean contains(String key) { - return cache.get(key) != null; - } - - @Override - public void clear() { - cache.evictAll(); - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/net/ApiResponse.java b/baselib/library/src/main/java/com/dhc/library/data/net/ApiResponse.java deleted file mode 100644 index 16bb291..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/net/ApiResponse.java +++ /dev/null @@ -1,18 +0,0 @@ - -package com.dhc.library.data.net; - -/** - * Api响应结果的封装类. - * - * @author 邓浩宸 - * @date 15/6/21 - * @version 1.0 - */ -public interface ApiResponse { - - boolean isSuccess(); - - boolean checkReLogin(); - - T getData(); -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/net/CacheInterceptor.java b/baselib/library/src/main/java/com/dhc/library/data/net/CacheInterceptor.java deleted file mode 100644 index 8739e53..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/net/CacheInterceptor.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.dhc.library.data.net; - - -import android.content.Context; - -import com.dhc.library.utils.sys.NetworkUtil; - -import java.io.IOException; - -import okhttp3.CacheControl; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - -/** - * 创建者 邓浩宸 - * 创建时间 2016/9/6 14:48 - * 描述 ${Okhttp缓存策略拦截类} - *

- * 更新者 $Author$ - * 更新时间 $Date$ - * 更新描述 ${TODO} - */ -public class CacheInterceptor implements Interceptor { - private Context mContext; - - public CacheInterceptor(Context mContext) { - this.mContext=mContext; - } - - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - - if (!NetworkUtil.isConnected(mContext)) { - request = request.newBuilder() - .cacheControl(CacheControl.FORCE_CACHE) - .build(); - } - Response response = chain.proceed(request); - if (NetworkUtil.isConnected(mContext)){//判断是否连接网络 - int maxAge = 0; - // 有网络时 设置缓存超时时间0个小时 - response.newBuilder() - .header("Cache-Control", "public, max-age=" + maxAge) - .removeHeader("Pragma")// 清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效 - .build(); - } else { - // 无网络时,设置超时为4周 - int maxStale = 60 * 60 * 24 * 28; - response.newBuilder() - .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale) - .removeHeader("Pragma") - .build(); - } - return response; - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/net/CallInterceptor.java b/baselib/library/src/main/java/com/dhc/library/data/net/CallInterceptor.java deleted file mode 100644 index 6c31387..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/net/CallInterceptor.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.dhc.library.data.net; - -import com.dhc.library.data.HttpHelper; - -import java.io.IOException; - -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - - -/** - * 创建者:邓浩宸 - * 时间 :2017/4/26 15:46 - * 描述 :做请求前和请求后的操作 - */ -public class CallInterceptor implements Interceptor { - - HttpHelper.RequestCall call; - - public CallInterceptor(HttpHelper.RequestCall call) { - this.call = call; - } - - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - if (call != null) { - if (call.onBeforeRequest(request, chain)!=null) - request = call.onBeforeRequest(request, chain); - } - Response response = chain.proceed(request); - if (call != null) { - //response.body()不能多次使用string方法 - if (call.onAfterRequest(response, response.body(), chain)!=null) - response = call.onAfterRequest(response, response.body(), chain); - } - return response; - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/net/NetError.java b/baselib/library/src/main/java/com/dhc/library/data/net/NetError.java deleted file mode 100644 index 59a4ceb..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/net/NetError.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.dhc.library.data.net; - -/** - * 创建者:邓浩宸 - * 时间 :2017/9/28 10:23 - * 描述 :网络异常 - */ -public class NetError extends Exception { - private Throwable exception; - private String type = NoConnectError; - - public static final String ParseError = "0"; //数据解析异常 - public static final String NoConnectError = "-1"; //无连接异常 - public static final String AuthError = "-2"; //用户验证异常 - public static final String NoDataError = "-3"; //无数据返回异常 - public static final String BusinessError = "-4"; //业务异常 - public static final String SocketError = "-6"; //连接超时异常 - public static final String OtherError = "-5"; //其他异常 - public static final String NetError = "-7"; //请求错误 - - public NetError(Throwable exception, String type) { - this.exception = exception; - this.type = type; - } - - public Throwable getException() { - return exception; - } - - public void setException(Throwable exception) { - this.exception = exception; - } - - public NetError(String detailMessage, String type) { - super(detailMessage); - this.type = type; - } - - @Override - public String getMessage() { - if (exception != null) { - if (exception.getMessage() == null) { - return exception.toString(); - } else { - return exception.getMessage(); - } - } - if (super.getMessage() != null) { - return super.getMessage(); - } else { - return "未知错误"; - } - } - - public String getType() { - return type; - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/net/ProgressCancelListener.java b/baselib/library/src/main/java/com/dhc/library/data/net/ProgressCancelListener.java deleted file mode 100644 index e697534..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/net/ProgressCancelListener.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.dhc.library.data.net; - -/** - * @author nanchen - * @fileName RetrofitRxDemoo - * @packageName com.nanchen.retrofitrxdemoo - * @date 2016/12/12 15:00 - */ - -public interface ProgressCancelListener { - void onCancelProgress(); -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/net/ProgressDialogHandler.java b/baselib/library/src/main/java/com/dhc/library/data/net/ProgressDialogHandler.java deleted file mode 100644 index ae17eb0..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/net/ProgressDialogHandler.java +++ /dev/null @@ -1,76 +0,0 @@ -//package com.dhc.library.data.net; -// -//import android.content.Context; -//import android.content.DialogInterface; -//import android.os.Handler; -//import android.os.Message; -// -// -///** -// * @author nanchen -// * @fileName RetrofitRxDemoo -// * @packageName com.nanchen.retrofitrxdemoo -// * @date 2016/12/12 15:02 -// */ -// -//public class ProgressDialogHandler extends Handler { -// public static final int SHOW_PROGRESS_DIALOG = 1; -// public static final int DISMISS_PROGRESS_DIALOG = 2; -// -// private LoadingDialog pd; -// -// private Context context; -// private boolean cancelable; -// private ProgressCancelListener mProgressCancelListener; -// -// public ProgressDialogHandler(Context context, ProgressCancelListener mProgressCancelListener, -// boolean cancelable) { -// super(); -// this.context = context; -// this.mProgressCancelListener = mProgressCancelListener; -// this.cancelable = cancelable; -// } -// -// private void initProgressDialog(){ -// if (pd == null) { -// if (context==null){ -// return; -// } -// pd = new LoadingDialog(context); -// -// pd.setCanceledOnTouchOutside(cancelable); -// -// if (cancelable) { -// pd.setOnCancelListener(new DialogInterface.OnCancelListener() { -// @Override -// public void onCancel(DialogInterface dialogInterface) { -// mProgressCancelListener.onCancelProgress(); -// } -// }); -// } -// -// if (!pd.isShowing()) { -// pd.show(); -// } -// } -// } -// -// private void dismissProgressDialog(){ -// if (pd != null) { -// pd.dismiss(); -// pd = null; -// } -// } -// -// @Override -// public void handleMessage(Message msg) { -// switch (msg.what) { -// case SHOW_PROGRESS_DIALOG: -// initProgressDialog(); -// break; -// case DISMISS_PROGRESS_DIALOG: -// dismissProgressDialog(); -// break; -// } -// } -//} diff --git a/baselib/library/src/main/java/com/dhc/library/data/net/RetryWhenHandler.java b/baselib/library/src/main/java/com/dhc/library/data/net/RetryWhenHandler.java deleted file mode 100644 index bee488a..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/net/RetryWhenHandler.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.dhc.library.data.net; - -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.util.concurrent.TimeUnit; - -import io.reactivex.Flowable; -import io.reactivex.functions.Function; -import retrofit2.HttpException; - -/** - * 创建者:邓浩宸 - * 时间 :2017/5/24 10:27 - * 描述 :重连机制 - */ -public class RetryWhenHandler implements Function, Flowable> { - - private int mCount = 3; - private long mDelay = 3; //s - - private int counter = 0; - - public RetryWhenHandler() { - } - - public RetryWhenHandler(int count) { - this.mCount = count; - } - - public RetryWhenHandler(int count, long delay) { - this(count); - this.mCount = count; - this.mDelay = delay; - } - - - @Override - public Flowable apply(Flowable flowable) throws Exception { - return flowable - .flatMap(new Function>() { - @Override - public Flowable apply(Throwable throwable) throws Exception { - if (counter < mCount && (throwable instanceof UnknownHostException - || throwable instanceof SocketException - || throwable instanceof HttpException - || throwable instanceof SocketTimeoutException - )) { - counter++; - return Flowable.timer(mDelay, TimeUnit.SECONDS); - } else if ((counter < mCount && throwable instanceof NullPointerException - && throwable.getMessage() != null && "token_is_need_refresh".equals(throwable.getMessage()))) { - counter++; - return Flowable.timer(0, TimeUnit.SECONDS); - } - return Flowable.error(throwable); - } - - }); - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/net/StringConverterFactory.java b/baselib/library/src/main/java/com/dhc/library/data/net/StringConverterFactory.java deleted file mode 100644 index 2f0f89f..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/net/StringConverterFactory.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.dhc.library.data.net; - -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; - -import okhttp3.MediaType; -import okhttp3.RequestBody; -import okhttp3.ResponseBody; -import retrofit2.Converter; -import retrofit2.Retrofit; - -/** - * 创建者 邓浩宸 - * 创建时间 2016/9/12 17:16 - * 描述 ${请求网络返回String的Goson处理工厂} - *

- * 更新者 $Author$ - * 更新时间 $Date$ - * 更新描述 ${TODO} - */ -public class StringConverterFactory extends Converter.Factory { - - private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain"); - - - @Override - public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { - if (String.class.equals(type)) { - return new Converter() { - @Override - public String convert(ResponseBody value) throws IOException { - return value.string(); - } - }; - } - return null; - } - - @Override public Converter requestBodyConverter(Type type, Annotation[] parameterAnnotations, - Annotation[] methodAnnotations, Retrofit retrofit) { - if (String.class.equals(type)) { - return new Converter() { - @Override - public RequestBody convert(String value) throws IOException { - return RequestBody.create(MEDIA_TYPE, value); - } - }; - } - return null; - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/net/SubscriberListener.java b/baselib/library/src/main/java/com/dhc/library/data/net/SubscriberListener.java deleted file mode 100644 index af17055..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/net/SubscriberListener.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.dhc.library.data.net; - -/** - * Created by dhc on 16/3/10. - */ -public abstract class SubscriberListener { - - public abstract void onSuccess(T response); - - public abstract void onFail(NetError error); - - public abstract void onError(Throwable e); - - public void onCompleted() { - } - - public void onBegin() { - } - - public boolean isShowLoading(){ - return true; - } - - public abstract void checkReLogin(String errorCode,String errorMsg); -} diff --git a/baselib/library/src/main/java/com/dhc/library/data/net/TokenInterceptor.java b/baselib/library/src/main/java/com/dhc/library/data/net/TokenInterceptor.java deleted file mode 100644 index 68b91be..0000000 --- a/baselib/library/src/main/java/com/dhc/library/data/net/TokenInterceptor.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.dhc.library.data.net; - -import android.text.TextUtils; - -import com.dhc.library.data.account.AccountManager; - -import java.io.IOException; - -import okhttp3.FormBody; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - -/** - * 创建者 邓浩宸 - * 创建时间 2016/9/7 11:36 - * 描述 ${Token管理} - *

- * 更新者 $Author$ - * 更新时间 $Date$ - * 更新描述 ${TODO} - */ -public class TokenInterceptor implements Interceptor { - @Override - public Response intercept(Chain chain) throws IOException { - Request original = chain.request(); - //请求定制:添加请求头 - Request.Builder requestBuilder = original.newBuilder(); - String access_token = AccountManager.INSTANCE.getAccessToken(); - if(!TextUtils.isEmpty(access_token)){ - requestBuilder.addHeader("Authorization", access_token); - } - - requestBuilder.addHeader("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.6"); - - //请求体定制:统一添加token参数 - if (original.body() instanceof FormBody) { - FormBody.Builder newFormBody = new FormBody.Builder(); - FormBody oidFormBody = (FormBody) original.body(); - for (int i = 0; i < oidFormBody.size(); i++) { - newFormBody.addEncoded(oidFormBody.encodedName(i), oidFormBody.encodedValue(i)); - } - requestBuilder.method(original.method(), newFormBody.build()); - } - - Request request = requestBuilder.build(); - return chain.proceed(request); - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/di/ActivityScope.java b/baselib/library/src/main/java/com/dhc/library/di/ActivityScope.java deleted file mode 100644 index 0c6d94c..0000000 --- a/baselib/library/src/main/java/com/dhc/library/di/ActivityScope.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.dhc.library.di; - -import java.lang.annotation.Retention; - -import javax.inject.Scope; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; - - -/** - * 创建者:邓浩宸 - * 时间 :2017/3/21 10:52 - * 描述 :TODO 请描述该类职责 - */ -@Scope -@Retention(RUNTIME) -public @interface ActivityScope { -} diff --git a/baselib/library/src/main/java/com/dhc/library/di/ContextLife.java b/baselib/library/src/main/java/com/dhc/library/di/ContextLife.java deleted file mode 100644 index f75d6df..0000000 --- a/baselib/library/src/main/java/com/dhc/library/di/ContextLife.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.dhc.library.di; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; - -import javax.inject.Qualifier; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * 创建者:邓浩宸 - * 时间 :2017/3/21 10:52 - * 描述 :TODO 请描述该类职责 - */ -@Qualifier -@Documented -@Retention(RUNTIME) -public @interface ContextLife { - String value() default "Application"; -} diff --git a/baselib/library/src/main/java/com/dhc/library/di/FragmentScope.java b/baselib/library/src/main/java/com/dhc/library/di/FragmentScope.java deleted file mode 100644 index 9773477..0000000 --- a/baselib/library/src/main/java/com/dhc/library/di/FragmentScope.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.dhc.library.di; - -import java.lang.annotation.Retention; - -import javax.inject.Scope; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -/** - * 创建者:邓浩宸 - * 时间 :2017/3/21 10:52 - * 描述 :TODO 请描述该类职责 - */ -@Scope -@Retention(RUNTIME) -public @interface FragmentScope { -} diff --git a/baselib/library/src/main/java/com/dhc/library/di/component/AppComponent.java b/baselib/library/src/main/java/com/dhc/library/di/component/AppComponent.java deleted file mode 100644 index 80633ff..0000000 --- a/baselib/library/src/main/java/com/dhc/library/di/component/AppComponent.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.dhc.library.di.component; - - -import com.dhc.library.data.DBHelper; -import com.dhc.library.data.HttpHelper; -import com.dhc.library.di.ContextLife; -import com.dhc.library.base.BaseApplication; -import com.dhc.library.di.module.AppModule; -import com.dhc.library.di.module.DataModule; - -import java.util.Random; - -import javax.inject.Singleton; - -import dagger.Component; -import io.rx_cache2.internal.RxCache; - - -/** - * 创建者:邓浩宸 - * 时间 :2017/3/21 10:53 - * 描述 :App的注解使用 - */ -@Singleton -@Component(modules = {DataModule.class,AppModule.class}) -public interface AppComponent { - - BaseApplication getContext(); // 提供App的Context - - HttpHelper httpHelper(); //提供http的帮助类 - - DBHelper dtabaseHelper(); //提供db的帮助类 - /** - * {@link Random} instance from {@link AppModule} - * which now can be injected to children - * that depend on {@link AppComponent}. - */ - Random random(); - - RxCache getRxCache(); -} diff --git a/baselib/library/src/main/java/com/dhc/library/di/module/ActivityModule.java b/baselib/library/src/main/java/com/dhc/library/di/module/ActivityModule.java deleted file mode 100644 index 6ef3a9b..0000000 --- a/baselib/library/src/main/java/com/dhc/library/di/module/ActivityModule.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.dhc.library.di.module; - -import android.app.Activity; - -import com.dhc.library.di.ActivityScope; - -import dagger.Module; -import dagger.Provides; - -/** - * 创建者:邓浩宸 - * 时间 :2017/3/21 10:52 - * 描述 :TODO 请描述该类职责 - */ -@Module -public class ActivityModule { - private Activity mActivity; - - public ActivityModule(Activity activity) { - this.mActivity = activity; - } - - @Provides - @ActivityScope - public Activity provideActivity() { - return mActivity; - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/di/module/AppModule.java b/baselib/library/src/main/java/com/dhc/library/di/module/AppModule.java deleted file mode 100644 index 4484160..0000000 --- a/baselib/library/src/main/java/com/dhc/library/di/module/AppModule.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.dhc.library.di.module; - - -import android.support.annotation.NonNull; - -import com.dhc.library.base.BaseApplication; - -import java.util.Random; - -import javax.inject.Singleton; - -import dagger.Module; -import dagger.Provides; - -/** - * 创建者:邓浩宸 - * 时间 :2017/3/21 10:52 - * 描述 :提供一些框架必须的实例的 {@link Module} - */ -@Module -public class AppModule { - private final BaseApplication application; - - public AppModule(BaseApplication application) { - this.application = application; - } - - @Provides - @Singleton -// @ContextLife("Application") - BaseApplication provideApplicationContext() { - return application; - } - - - - @Provides @NonNull - @Singleton - public Random random() { - return new Random(); - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/di/module/DataModule.java b/baselib/library/src/main/java/com/dhc/library/di/module/DataModule.java deleted file mode 100644 index ea9c938..0000000 --- a/baselib/library/src/main/java/com/dhc/library/di/module/DataModule.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.dhc.library.di.module; - - -import com.dhc.library.base.BaseApplication; -import com.dhc.library.data.DBHelper; -import com.dhc.library.data.HttpHelper; -import com.dhc.library.data.IDataHelper; -import com.dhc.library.utils.file.FileUtil; - -import java.io.File; - -import javax.inject.Named; -import javax.inject.Singleton; - -import dagger.Module; -import dagger.Provides; -import io.rx_cache2.internal.RxCache; -import io.victoralbertos.jolyglot.GsonSpeaker; - -/** - * 创建者 邓浩宸 - * 创建时间 2018/3/29 12:51 - * 描述 数据工具提供者 - */ -@Module -public class DataModule { - - IDataHelper.NetConfig netConfig; - - - public DataModule(IDataHelper.NetConfig netConfig) { - this.netConfig = netConfig; - } - - @Provides - @Singleton - HttpHelper provideHttpHelper(BaseApplication application) { - HttpHelper httpHelper = new HttpHelper(application); - if (netConfig == null) - netConfig = new IDataHelper.NetConfig(); - httpHelper.initConfig(netConfig); - return httpHelper; - } - @Provides - @Singleton - DBHelper provideDatabaseHelper(BaseApplication application) { - return new DBHelper(application); - } - - - - /** - * 提供 {@link RxCache} - * - * @param cacheDirectory RxCache缓存路径 - * @return - */ - @Singleton - @Provides - RxCache provideRxCache(@Named("RxCacheDirectory") File cacheDirectory) { - RxCache.Builder builder = new RxCache.Builder(); - return builder - .persistence(cacheDirectory, new GsonSpeaker()); - } - - /** - * 需要单独给 {@link RxCache} 提供缓存路径 - * - * @return - */ - @Singleton - @Provides - @Named("RxCacheDirectory") - File provideRxCacheDirectory(BaseApplication application) { - File cacheDirectory = new File(FileUtil.getCacheDirectory(application), "RxCache"); - return FileUtil.makeDirs(cacheDirectory); - } - -} diff --git a/baselib/library/src/main/java/com/dhc/library/di/module/FragmentModule.java b/baselib/library/src/main/java/com/dhc/library/di/module/FragmentModule.java deleted file mode 100644 index 501d3d1..0000000 --- a/baselib/library/src/main/java/com/dhc/library/di/module/FragmentModule.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.dhc.library.di.module; - -import android.app.Activity; -import android.support.v4.app.Fragment; - -import com.dhc.library.di.FragmentScope; - -import dagger.Module; -import dagger.Provides; - - -/** - * 创建者:邓浩宸 - * 时间 :2017/3/21 10:53 - * 描述 :TODO 请描述该类职责 - */ -@Module -public class FragmentModule { - - private Fragment fragment; - - public FragmentModule(Fragment fragment) { - this.fragment = fragment; - } - - @Provides - @FragmentScope - public Activity provideActivity() { - return fragment.getActivity(); - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/framework/IDaggerListener.java b/baselib/library/src/main/java/com/dhc/library/framework/IDaggerListener.java deleted file mode 100644 index d3fe96a..0000000 --- a/baselib/library/src/main/java/com/dhc/library/framework/IDaggerListener.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.dhc.library.framework; - -import android.os.Bundle; - -/** - * 创建者 邓浩宸 - * 创建时间 2017/3/24 9:09 - * 描述 ${TODO} - */ - -public interface IDaggerListener { - - void initInject(Bundle savedInstanceState); -} diff --git a/baselib/library/src/main/java/com/dhc/library/framework/OnBackToFirstListener.java b/baselib/library/src/main/java/com/dhc/library/framework/OnBackToFirstListener.java deleted file mode 100644 index 68b0c6f..0000000 --- a/baselib/library/src/main/java/com/dhc/library/framework/OnBackToFirstListener.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.dhc.library.framework; - -public interface OnBackToFirstListener { - void onBackToFirstFragment(); -} \ No newline at end of file diff --git a/baselib/library/src/main/java/com/dhc/library/framework/OnShowHomeListener.java b/baselib/library/src/main/java/com/dhc/library/framework/OnShowHomeListener.java deleted file mode 100644 index fad41e6..0000000 --- a/baselib/library/src/main/java/com/dhc/library/framework/OnShowHomeListener.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.dhc.library.framework; - -/** - * 创建者 邓浩宸 - * 创建时间 2016/12/9 14:17 - * 描述 TODO - */ - -public interface OnShowHomeListener { - - void showHome(); -} diff --git a/baselib/library/src/main/java/com/dhc/library/framework/anim/BelowAnimator.java b/baselib/library/src/main/java/com/dhc/library/framework/anim/BelowAnimator.java deleted file mode 100644 index 9d687d5..0000000 --- a/baselib/library/src/main/java/com/dhc/library/framework/anim/BelowAnimator.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.dhc.library.framework.anim; - -import android.os.Parcel; -import android.os.Parcelable; - - -import com.dhc.library.R; - -import me.yokeyword.fragmentation.anim.FragmentAnimator; - - -/** - * Created by YoKeyword on 16/2/5. - */ -public class BelowAnimator extends FragmentAnimator implements Parcelable{ - - public BelowAnimator() { - enter = R.anim.login_in_below; - exit = R.anim.login_out_below; - popEnter = R.anim.login_in_below; - popExit = R.anim.login_out_below; - } - - protected BelowAnimator(Parcel in) { - super(in); - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - } - - @Override - public int describeContents() { - return 0; - } - - public static final Creator CREATOR = new Creator() { - @Override - public BelowAnimator createFromParcel(Parcel in) { - return new BelowAnimator(in); - } - - @Override - public BelowAnimator[] newArray(int size) { - return new BelowAnimator[size]; - } - }; -} diff --git a/baselib/library/src/main/java/com/dhc/library/framework/anim/OAnimator.java b/baselib/library/src/main/java/com/dhc/library/framework/anim/OAnimator.java deleted file mode 100644 index e88b406..0000000 --- a/baselib/library/src/main/java/com/dhc/library/framework/anim/OAnimator.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.dhc.library.framework.anim; - -import android.os.Parcel; -import android.os.Parcelable; - - -import com.dhc.library.R; - -import me.yokeyword.fragmentation.anim.FragmentAnimator; - - -/** - * Created by YoKeyword on 16/2/5. - */ -public class OAnimator extends FragmentAnimator implements Parcelable{ - - public OAnimator() { - enter = R.anim.h_fragment_enter; - exit = R.anim.h_fragment_exit; - popEnter = R.anim.v_fragment_pop_enter; - popExit = R.anim.v_fragment_pop_exit; - } - - protected OAnimator(Parcel in) { - super(in); - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - } - - @Override - public int describeContents() { - return 0; - } - - public static final Creator CREATOR = new Creator() { - @Override - public OAnimator createFromParcel(Parcel in) { - return new OAnimator(in); - } - - @Override - public OAnimator[] newArray(int size) { - return new OAnimator[size]; - } - }; -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/AppBlockCanaryContext.java b/baselib/library/src/main/java/com/dhc/library/utils/AppBlockCanaryContext.java deleted file mode 100644 index 3b063d1..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/AppBlockCanaryContext.java +++ /dev/null @@ -1,154 +0,0 @@ -package com.dhc.library.utils; - -import com.github.moduth.blockcanary.BlockCanaryContext; - -import java.io.File; -import java.util.LinkedList; -import java.util.List; - -/** - * 创建者:邓浩宸 - * 时间 :2016/11/15 16:02 - * 描述 :对过度绘制进行监控 - */ -public class AppBlockCanaryContext extends BlockCanaryContext { - - /** - * Implement in your project. - * - * @return Qualifier which can specify this installation, like version + flavor. - */ - public String provideQualifier() { - return "unknown"; - } - - /** - * Implement in your project. - * - * @return app_userword id - */ - public String provideUid() { - return "uid"; - } - - /** - * Network type - * - * @return {@link String} like 2G, 3G, 4G, wifi, etc. - */ - public String provideNetworkType() { - return "unknown"; - } - - /** - * Config monitor duration, after this time BlockCanary will stop, use - * with {@code BlockCanary}'s isMonitorDurationEnd - * - * @return monitor last duration (in hour) - */ - public int provideMonitorDuration() { - return -1; - } - - /** - * Config block threshold (in millis), dispatch over this duration is regarded as a BLOCK. You may set it - * from performance of device. - * - * @return threshold in mills - */ - public int provideBlockThreshold() { - return 1000; - } - - /** - * Thread stack dump interval, use when block happens, BlockCanary will dump on main thread - * stack according to current sample cycle. - *

- * Because the implementation mechanism of Looper, real dump interval would be longer than - * the period specified here (especially when cpu is busier). - *

- * - * @return dump interval (in millis) - */ - public int provideDumpInterval() { - return provideBlockThreshold(); - } - - /** - * Path to save log, like "/blockcanary/", will save to sdcard if can. - * - * @return path of log files - */ - public String providePath() { - return "/blockcanary/"; - } - - /** - * If need notification to notice block. - * - * @return true if need, else if not need. - */ - public boolean displayNotification() { - return true; - } - - /** - * Implement in your project, bundle files into a zip file. - * - * @param src files before compress - * @param dest files compressed - * @return true if compression is successful - */ - public boolean zip(File[] src, File dest) { - return false; - } - - /** - * Implement in your project, bundled log files. - * - * @param zippedFile zipped file - */ - public void upload(File zippedFile) { - throw new UnsupportedOperationException(); - } - - - /** - * Packages that developer concern, by default it uses process name, - * put high priority one in pre-order. - * - * @return null if simply concern only package with process name. - */ - public List concernPackages() { - return null; - } - - /** - * Filter stack without any in concern package, used with @{code concernPackages}. - * - * @return true if filter, false it not. - */ - public boolean filterNonConcernStack() { - return false; - } - - /** - * Provide white list, entry in white list will not be shown in ui list. - * - * @return return null if you don't need white-list filter. - */ - public List provideWhiteList() { - LinkedList whiteList = new LinkedList<>(); - whiteList.add("org.chromium"); - return whiteList; - } - - /** - * Whether to delete files whose stack is in white list, used with white-list. - * - * @return true if delete, false it not. - */ - public boolean deleteFilesInWhiteList() { - return true; - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/AppContext.java b/baselib/library/src/main/java/com/dhc/library/utils/AppContext.java deleted file mode 100644 index c7bd34f..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/AppContext.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.dhc.library.utils; - -import android.content.Context; - -/** - * Created by Nirui on 17/2/21. - */ - -public class AppContext { - public static Context mAppContext; - - - public static void init(Context context) { - if (mAppContext == null) { - mAppContext = context.getApplicationContext(); - } else { - throw new IllegalStateException("set context duplicate"); - } - } - - public static Context get() { - if (mAppContext == null) { - throw new IllegalStateException("forget init?"); - } else { - return mAppContext; - } - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/AppManager.java b/baselib/library/src/main/java/com/dhc/library/utils/AppManager.java deleted file mode 100644 index c1025c4..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/AppManager.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.dhc.library.utils; - -import android.app.Activity; - -import java.util.Stack; - -/** - * 创建者:denghaochen - * 时间 :2016-09-07 下午 3:43 - * 描述 :Activity进栈出栈统一管理 - */ -public class AppManager { - - private static Stack activityStack; - private static AppManager instance; - - static { - instance = new AppManager(); - } - - private AppManager() { - } - - - public static AppManager getInstance() { - return instance; - } - - public static AppManager getAppManager() { - if (instance == null) { - synchronized (AppManager.class) { - if (instance == null) { - instance = new AppManager(); - } - } - } - return instance; - } - - - public void addActivity(Activity activity) { - if (activityStack == null) { - activityStack = new Stack(); - } - activityStack.add(activity); - } - - - public Activity currentActivity() { - Activity activity = activityStack.lastElement(); - return activity; - } - - - public void finishActivity() { - Activity activity = activityStack.lastElement(); - finishActivity(activity); - } - - public void finishActivity(Activity activity) { - if (activity != null) { - activityStack.remove(activity); - activity.finish(); - } - } - - public void removeActivity(Activity activity) { - if (activity != null) { - activityStack.remove(activity); - } - } - - public void finishActivity(Class cls) { - for (Activity activity : activityStack) { - if (activity.getClass().equals(cls)) { - finishActivity(activity); - } - } - } - public void finishALLExcludeCurrentActivity(Class cls) { - for (int i = 0, size = activityStack.size(); i < size; i++) { - if (null != activityStack.get(i)) { - if (!activityStack.get(i).getClass().equals(cls)) { - activityStack.get(i).finish(); - } - } - } - } - public void finishALLExcludeCurrentActivity() { - for (int i = 0, size = activityStack.size(); i < size; i++) { - if (null != activityStack.get(i)) { - if (!activityStack.get(i).equals(currentActivity())) { - activityStack.get(i).finish(); - } - } - } - } - - - public void finishAllActivity() { - for (int i = 0, size = activityStack.size(); i < size; i++) { - if (null != activityStack.get(i)) { - activityStack.get(i).finish(); - } - } - activityStack.clear(); - } - - /** - * 退出应用 - */ - public void AppExit() { - try { - finishAllActivity(); - android.os.Process.killProcess(android.os.Process.myPid()); - } catch (Exception e) { - } - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/AppUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/AppUtil.java deleted file mode 100644 index 0cbcd8b..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/AppUtil.java +++ /dev/null @@ -1,203 +0,0 @@ -package com.dhc.library.utils; - -import android.app.ActivityManager; -import android.content.Context; -import android.content.Intent; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.net.Uri; -import android.provider.Settings; -import android.text.TextUtils; - -import java.io.File; - -/** - * app相关辅助类 - * 邓浩宸 - */ -public class AppUtil { - private AppUtil() { - /* cannot be instantiated*/ - throw new UnsupportedOperationException("cannot be instantiated"); - } - - /** - * 获取应用程序名称 - * - * @param context - * @return - */ - public static String getAppName(Context context) { - - PackageManager packageManager = context.getPackageManager(); - try { - PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0); - int labelRes = packageInfo.applicationInfo.labelRes; - return context.getResources().getString(labelRes); - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); - } - return null; - } - - /** - * 获取应用程序版本名称信息 - * - * @param context - * @return 当前应用的版本名称 - */ - public static String getVersionName(Context context) { - try { - PackageManager packageManager = context.getPackageManager(); - PackageInfo packageInfo = packageManager.getPackageInfo( - context.getPackageName(), 0); - return packageInfo.versionName; - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); - } - return null; - } - - /** - * 获取应用程序的版本Code信息 - * - * @param context - * @return 版本code - */ - public static int getVersionCode(Context context) { - try { - PackageManager packageManager = context.getPackageManager(); - PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0); - return packageInfo.versionCode; - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); - } - return 0; - } - - /** - * 获取当前进程名 - * @param context - * @return 进程名 - */ - public static final String getProcessName(Context context) { - String processName = null; - - // ActivityManager - ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)); - - while (true) { - for (ActivityManager.RunningAppProcessInfo info : am.getRunningAppProcesses()) { - if (info.pid == android.os.Process.myPid()) { - processName = info.processName; - - break; - } - } - // go home - if (!TextUtils.isEmpty(processName)) { - return processName; - } - // take a rest and again - try { - Thread.sleep(100L); - } catch (InterruptedException ex) { - ex.printStackTrace(); - } - } - } - - - /** - * 判断包是否安装 - * 邓浩宸 - * - * @param context - * @param packageName - * @return - */ - public static boolean isInstalled(Context context, String packageName) { - PackageManager manager = context.getPackageManager(); - try { - manager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES); - - return true; - } catch (PackageManager.NameNotFoundException e) { - return false; - } - } - - /** - * 安装应用程序 - * - * @param context - * @param apkFile - */ - public static void installApp(Context context, File apkFile) { - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive"); - context.startActivity(intent); - } - - /** - * 打开应用程序 - * - * @param context - * @param packageName - */ - public static void openApp(Context context, String packageName) { - Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName); - context.startActivity(intent); - } - - - private static Boolean isDebug = null; - - public static boolean isDebug() { - return isDebug == null ? false : isDebug.booleanValue(); - } - - /** - * Sync lib debug with app's debug value. Should be called in module Application - * - * @param context - */ - public static void syncIsDebug(Context context) { - if (isDebug == null) { - isDebug = context.getApplicationInfo() != null && - (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; - } - } - - /** - * 开启权限设置页面 - * @param context - */ - public static void startAppSettings(Context context) { - Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); - intent.setData(Uri.parse("package:" + context.getPackageName())); - context.startActivity(intent);//this - } - /** - * android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? - at android.app.ContextImpl.startActivity(ContextImpl.java:672) - at android.app.ContextImpl.startActivity(ContextImpl.java:659) - at android.content.ContextWrapper.startActivity(ContextWrapper.java:331) - at com.kairu.library.utils.AppUtil.startAppSettings(AppUtil.java:181) - at com.kairu.tutudao.ui.home.MainActivity$1$1.onBtnClickR(MainActivity.java:125) - at com.kairu.library.rxpermissions.RxPermissions$5.onBtnClick(RxPermissions.java:306) - at com.flyco.dialog.widget.internal.BaseAlertDialog$2.onClick(BaseAlertDialog.java:162) - at android.view.View.performClick(View.java:5198) - at android.view.View$PerformClick.run(View.java:21147) - at android.os.Handler.handleCallback(Handler.java:739) - at android.os.Handler.dispatchMessage(Handler.java:95) - at android.os.Looper.loop(Looper.java:148) - at android.app.ActivityThread.main(ActivityThread.java:5417) - at java.lang.reflect.Method.invoke(Native Method) - at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) - at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) - - */ -} \ No newline at end of file diff --git a/baselib/library/src/main/java/com/dhc/library/utils/ApplicationLike.java b/baselib/library/src/main/java/com/dhc/library/utils/ApplicationLike.java deleted file mode 100644 index 423f26e..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/ApplicationLike.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.dhc.library.utils; - -import android.app.Application; -import android.content.res.Configuration; - -import com.alibaba.android.arouter.facade.template.IProvider; - -/** - * Created by 邓浩宸 on 17/2/27. - * 作为接口,方便主工程调度子模块的声明周期 - */ - -public interface ApplicationLike extends IProvider { - - public void onTerminate(Application application); - public void onCreateAsLibrary(Application application); - public void onLowMemoryAsLibrary(Application application); - public void onTrimMemoryAsLibrary(Application application, int level); - public void onConfigurationChanged(Application application, Configuration configuration); - -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/ArithmeticUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/ArithmeticUtil.java deleted file mode 100644 index 85e7b06..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/ArithmeticUtil.java +++ /dev/null @@ -1,278 +0,0 @@ -package com.dhc.library.utils; - -/** - * 创建者 Deemons - * 创建时间 2016/6/13 0:18 - * 包名 com.duocai100.duocai.utils - * 描述 ${TODO} - *

- * 更新者 Deemons - * 更新时间 2016/6/13 - * 更新描述 - */ -/* - * Created by w4lle 2016 . - * Copyright (c) 2016 Boohee, Inc. All rights reserved. - */ - - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.ArrayList; - -/** - * 浮点数精确计算工具类 - */ -public class ArithmeticUtil { - - /** - * 对一个数字取精度 - * - * @param v - * @param scale - * @return - */ - public static float round(float v, int scale) { - if (scale < 0) { - throw new IllegalArgumentException( - "The scale must be a positive integer or zero"); - } - BigDecimal b = new BigDecimal(v); - BigDecimal one = new BigDecimal("1"); - return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).floatValue(); - } - - /** - * 精确加法 - * - * @param v1 - * @param v2 - * @return - */ - public static float add(float v1, float v2) { - BigDecimal bigDecimal1 = new BigDecimal(v1); - BigDecimal bigDecimal2 = new BigDecimal(v2); - return bigDecimal1.add(bigDecimal2).floatValue(); - } - - /** - * 精确加法 - * - * @param v1 - * @param v2 - * @param scale - * @return - */ - public static float addWithScale(float v1, float v2, int scale) { - BigDecimal bigDecimal1 = new BigDecimal(v1); - BigDecimal bigDecimal2 = new BigDecimal(v2); - return bigDecimal1.add(bigDecimal2).setScale(scale, BigDecimal.ROUND_HALF_UP).floatValue(); - } - - - /** - * 随机指定范围内N个不重复的数 - * 最简单最基本的方法 - * @param min 指定范围最小值 - * @param max 指定范围最大值 - * @param n 随机数个数 - */ - public static int[] randomCommon(int min, int max, int n){ - if (n > (max - min + 1) || max < min) { - return null; - } - int[] result = new int[n]; - int count = 0; - while(count < n) { - int num = (int) (Math.random() * (max - min)) + min; - boolean flag = true; - for (int j = 0; j < n; j++) { - if(num == result[j]){ - flag = false; - break; - } - } - if(flag){ - result[count] = num; - count++; - } - } - return result; - } - - /** - * 精确减法 - * - * @param v1 - * @param v2 - * @return - */ - public static float sub(float v1, float v2) { - BigDecimal b1 = new BigDecimal(v1); - BigDecimal b2 = new BigDecimal(v2); - return b1.subtract(b2).floatValue(); - } - - /** - * 精确乘法,默认保留一位小数 - * - * @param v1 - * @param v2 - * @return - */ - public static float mul(float v1, float v2) { - return mulWithScale(v1, v2, 1); - } - - /** - * 精确乘法,保留scale位小数 - * - * @param v1 - * @param v2 - * @param scale - * @return - */ - public static float mulWithScale(float v1, float v2, int scale) { - BigDecimal b1 = new BigDecimal(v1); - BigDecimal b2 = new BigDecimal(v2); - return round(b1.multiply(b2).floatValue(), scale); - } - - /** - * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。 - * - * @param v1 被除数 - * @param v2 除数 - * @param scale 表示需要精确到小数点以后几位。 - * @return 两个参数的商 - */ - public static float div(float v1, float v2, int scale) { - if (scale < 0) { - throw new IllegalArgumentException( - "The scale must be a positive integer or zero"); - } - BigDecimal b1 = new BigDecimal(v1); - BigDecimal b2 = new BigDecimal(v2); - return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).floatValue(); - } - - /** - * 取余数 - * - * @param v1 - * @param v2 - * @return - */ - public static int remainder(float v1, float v2) { - return Math.round(v1 * 100) % Math.round(v2 * 100); - } - - /** - * 比较大小 如果v1 大于v2 则 返回true 否则false - * - * @param v1 - * @param v2 - * @return - */ - public static boolean strCompareTo(String v1, String v2) { - BigDecimal b1 = new BigDecimal(v1); - BigDecimal b2 = new BigDecimal(v2); - int bj = b1.compareTo(b2); - boolean res; - if (bj > 0) - res = true; - else - res = false; - return res; - } - - - /** - * 计算阶乘数,即n! = n * (n-1) * ... * 2 * 1 - * - * @param n - * @return - */ - private static long factorial(int n) { - return (n > 1) ? n * factorial(n - 1) : 1; - } - - /** - * 计算排列数,即A(n, m) = n!/(n-m)! - * - * @param n - * @param m - * @return - */ - public static long arrangement(int n, int m) { - return (n >= m) ? factorial(n) / factorial(n - m) : 0; - } - - /** - * 计算组合数,即C(n, m) = n!/((n-m)! * m!) - * - * @param n - * @param m - * @return - */ - public static long combination(int n, int m) { - return (n >= m) ? factorial(n) / factorial(n - m) / factorial(m) : 0; - } - - public static int simpleCircle(int num) {//简单的循环计算的阶乘 - int sum = 1; - if (num < 0) {//判断传入数是否为负数 - throw new IllegalArgumentException("必须为正整数!");//抛出不合理参数异常 - } - for (int i = 1; i <= num; i++) {//循环num - sum *= i;//每循环一次进行乘法运算 - } - return sum;//返回阶乘的值 - } - - - - - - public static int recursion(int num) {//利用递归计算阶乘 - int sum = 1; - if (num < 0) - throw new IllegalArgumentException("必须为正整数!");//抛出不合理参数异常 - if (num == 1) { - return 1;//根据条件,跳出循环 - } else { - sum = num * recursion(num - 1);//运用递归计算 - return sum; - } - } - - public static long addArray(int num) {//数组添加计算阶乘 - long[] arr = new long[21];//创建数组 - arr[0] = 1; - - int last = 0; - if (num >= arr.length) { - throw new IllegalArgumentException("传入的值太大");//抛出传入的数太大异常 - } - if (num < 0) - throw new IllegalArgumentException("必须为正整数!");//抛出不合理参数异常 - while (last < num) {//建立满足小于传入数的while循环 - arr[last + 1] = arr[last] * (last + 1);//进行运算 - last++;//last先进行运算,再将last的值加1 - } - return arr[num]; - } - - public static synchronized BigInteger bigNumber(int num) {//利用BigInteger类计算阶乘 - - ArrayList list = new ArrayList();//创建集合数组 - list.add(BigInteger.valueOf(1));//往数组里添加一个数值 - for (int i = list.size(); i <= num; i++) { - BigInteger lastfact = (BigInteger) list.get(i - 1);//获得第一个元素 - BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(i));//获得下一个数组 - list.add(nextfact); - } - return (BigInteger) list.get(num);//返回数组中的下标为num的值 - - } -} \ No newline at end of file diff --git a/baselib/library/src/main/java/com/dhc/library/utils/AsLibUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/AsLibUtil.java deleted file mode 100644 index ab33979..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/AsLibUtil.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.dhc.library.utils; - -import android.app.Application; -import android.content.res.Configuration; - -import java.util.ArrayList; -import java.util.List; - -/** - * 创建者 邓浩宸 - * 创建时间 2017/3/29 11:55 - * 描述 ${TODO} - */ -public class AsLibUtil { - - - private static List mChildApplicationList = new ArrayList<>(); - - public static void addAsLIbChild(ApplicationLike applicationAsLibrary){ - if (applicationAsLibrary!=null) - mChildApplicationList.add(applicationAsLibrary); - } - - public static void doCreateAsLibrary(Application application){ - for (ApplicationLike app : mChildApplicationList) { - if (app!=null) - app.onCreateAsLibrary(application); - } - } - - public static void onLowMemoryAsLibrary(Application application) { - for (ApplicationLike app : mChildApplicationList) { - if (app!=null) - app.onLowMemoryAsLibrary(application); - } - } - - public static void onTrimMemoryAsLibrary(Application application, int level) { - for (ApplicationLike app : mChildApplicationList) { - if (app!=null) - app.onTrimMemoryAsLibrary(application,level); - } - } - - public static void onTerminate(Application application) { - for (ApplicationLike app : mChildApplicationList) { - if (app!=null) - app.onTerminate(application); - } - } - - public static void onConfigurationChanged(Application application, Configuration newConfig) { - for (ApplicationLike app : mChildApplicationList) { - if (app!=null) - app.onConfigurationChanged(application,newConfig); - } - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/BaseUtils.java b/baselib/library/src/main/java/com/dhc/library/utils/BaseUtils.java deleted file mode 100644 index 72258dc..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/BaseUtils.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.dhc.library.utils; - -import android.graphics.Paint; -import android.text.TextUtils; -import android.util.Log; - -import java.net.URLEncoder; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Created by baixiaokang on 16/12/10. - */ - -public class BaseUtils { - - public static List getOldWeekDays() { - final Calendar c = Calendar.getInstance(); - String[] months = new String[8]; - for (int i = 0; i < 8; i++) { - months[i] = new SimpleDateFormat("MM.dd").format(new Date(c - .getTimeInMillis())); - c.add(Calendar.DAY_OF_MONTH, -1); - } - return Arrays.asList(months); - } - - public static Paint getPaint(Paint.Style style, int color) { - Paint mPaint = new Paint(); - mPaint.setAntiAlias(true); - mPaint.setStyle(style); - mPaint.setColor(color); - mPaint.setTextSize(30); - return mPaint; - } - - /** - * @param fraction - * @param startValue - * @param endValue - * @return - */ - public static Integer evaluate(float fraction, Object startValue, Object endValue) { - int startInt = (Integer) startValue; - int startA = (startInt >> 24) & 0xff; - int startR = (startInt >> 16) & 0xff; - int startG = (startInt >> 8) & 0xff; - int startB = startInt & 0xff; - int endInt = (Integer) endValue; - int endA = (endInt >> 24) & 0xff; - int endR = (endInt >> 16) & 0xff; - int endG = (endInt >> 8) & 0xff; - int endB = endInt & 0xff; - return (int) ((startA + (int) (fraction * (endA - startA))) << 24) - | (int) ((startR + (int) (fraction * (endR - startR))) << 16) - | (int) ((startG + (int) (fraction * (endG - startG))) << 8) - | (int) ((startB + (int) (fraction * (endB - startB)))); - } - - /** - * 验证手机格式 - */ - public static boolean phoneVerification(String phoneNum) { - /* - 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188 - 联通:130、131、132、152、155、156、185、186 - 电信:133、153、180、189、(1349卫通) - 总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9 - */ - String telRegex = "[1][3578]\\d{9}";//"[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。 - if (TextUtils.isEmpty(phoneNum)) return false; - else return phoneNum.matches(telRegex); - } - /** - * 验证密码格式 - */ - public static boolean pwVerification(String pwString) { - String PATTERN="^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";//判断6-16字母数字组合 -// String PATTERN="'/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/'";//判断6-16字母数字组合 - if (TextUtils.isEmpty(pwString)) return false; - else return pwString.matches(PATTERN); - } - - public static String toURLEncoded(String paramString) { - if (paramString == null || paramString.equals("")) { - Log.e("URLEncoded","toURLEncoded error:"+paramString); - return ""; - } - - try - { - String str = new String(paramString.getBytes(), "UTF-8"); - str = URLEncoder.encode(str, "UTF-8"); - return str; - } - catch (Exception localException) - { - Log.e("URLEncoded","toURLEncoded error:"+paramString, localException); - } - - return ""; - } - - /** - * 通过正则表达式来判断。下面的例子只允许显示字母、数字和汉字。 - */ - public static boolean stringFilter(String str) { - // 只允许字母、数字和汉字 - String regex="^[a-zA-Z\u4E00-\u9FA5]+$"; - Pattern pattern = Pattern.compile(regex); - Matcher match=pattern.matcher(str); - return match.matches(); - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/ClipboardUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/ClipboardUtil.java deleted file mode 100644 index 6b308a7..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/ClipboardUtil.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.dhc.library.utils; - -import android.content.Context; -import android.text.ClipboardManager; - -public class ClipboardUtil { - public static final void clipboardCopyText(Context context, CharSequence text) { - ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); - if (cm != null) { - cm.setText(text); - } - } - - public static final int clipboardTextLength(Context context) { - ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); - CharSequence text = cm != null ? cm.getText() : null; - return text != null ? text.length() : 0; - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/ColorUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/ColorUtil.java deleted file mode 100644 index 2623adb..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/ColorUtil.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.dhc.library.utils; - -/** - * 创建者 邓浩宸 - * 创建时间 2017/8/28 13:17 - * 描述 ${TODO} - */ - -public class ColorUtil { - - /** - * @param fraction - * @param startValue - * @param endValue - * @return - */ - public static Integer evaluate(float fraction, Object startValue, Object endValue) { - int startInt = (Integer) startValue; - int startA = (startInt >> 24) & 0xff; - int startR = (startInt >> 16) & 0xff; - int startG = (startInt >> 8) & 0xff; - int startB = startInt & 0xff; - int endInt = (Integer) endValue; - int endA = (endInt >> 24) & 0xff; - int endR = (endInt >> 16) & 0xff; - int endG = (endInt >> 8) & 0xff; - int endB = endInt & 0xff; - return (int) ((startA + (int) (fraction * (endA - startA))) << 24) - | (int) ((startR + (int) (fraction * (endR - startR))) << 16) - | (int) ((startG + (int) (fraction * (endG - startG))) << 8) - | (int) ((startB + (int) (fraction * (endB - startB)))); - } - -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/ImageSaveUtils.java b/baselib/library/src/main/java/com/dhc/library/utils/ImageSaveUtils.java deleted file mode 100644 index 474b28b..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/ImageSaveUtils.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.dhc.library.utils; - -import android.content.Context; -import android.content.Intent; -import android.graphics.Bitmap; -import android.net.Uri; -import android.os.Environment; -import android.provider.MediaStore; -import android.widget.Toast; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * @author YK - * @time 2017/6/22 19:40 - * @desc TODO - */ - -public class ImageSaveUtils { - //保存文件到指定路径 - public static boolean saveImageToGallery(Context context, Bitmap bmp) { - // 首先保存图片 - String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "SunDownload"; - File appDir = new File(storePath); - if (!appDir.exists()) { - appDir.mkdir(); - } - String fileName = System.currentTimeMillis() + ".jpg"; - File file = new File(appDir, fileName); - try { - FileOutputStream fos = new FileOutputStream(file); - //通过io流的方式来压缩保存图片 - boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 75, fos); - fos.flush(); - fos.close(); - - //把文件插入到系统图库 - MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null); - - //保存图片后发送广播通知更新数据库 - Uri uri = Uri.fromFile(file); - context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri)); - if (isSuccess=true) { - Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show(); - return true; - } else { - return false; - } - } catch (IOException e) { - e.printStackTrace(); - } - return false; - } - -} - diff --git a/baselib/library/src/main/java/com/dhc/library/utils/MaterialColor.java b/baselib/library/src/main/java/com/dhc/library/utils/MaterialColor.java deleted file mode 100644 index 9f63db8..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/MaterialColor.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.dhc.library.utils; - -public class MaterialColor { - - public static final int material_deep_teal_500 = 0xff009688; - - //搬运自themes_material.java中的Theme.Material.Light - public static final class DefaultLight{ - //我是分割线 - public static final int colorPrimaryDark = 0xff757575;//@color/primary_dark_material_light - public static final int colorPrimary = 0xffbdbdbd;//@color/primary_material_light - public static final int colorAccent = material_deep_teal_500;//@color/accent_material_light - //我是分割线 - //public static final int colorControlNormal = 0;//?attr/textColorSecondary - //public static final int colorControlActivated = 0;//?attr/colorAccent - //我是分割线 - public static final int colorControlHighlight = 0x40000000;//@color/ripple_material_light - //public static final int colorButtonNormal = 0;//@color/btn_default_material_light - //public static final int colorSwitchThumbNormal = 0;//@color/switch_thumb_material_light - - } - -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/SpannableUtils.java b/baselib/library/src/main/java/com/dhc/library/utils/SpannableUtils.java deleted file mode 100644 index 6cb35fc..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/SpannableUtils.java +++ /dev/null @@ -1,677 +0,0 @@ -package com.dhc.library.utils; - -import android.graphics.Bitmap; -import android.graphics.BlurMaskFilter; -import android.graphics.Typeface; -import android.graphics.drawable.Drawable; -import android.net.Uri; -import android.support.annotation.ColorInt; -import android.support.annotation.DrawableRes; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.text.Layout; -import android.text.SpannableString; -import android.text.Spanned; -import android.text.style.AbsoluteSizeSpan; -import android.text.style.AlignmentSpan; -import android.text.style.BackgroundColorSpan; -import android.text.style.BulletSpan; -import android.text.style.ClickableSpan; -import android.text.style.ForegroundColorSpan; -import android.text.style.ImageSpan; -import android.text.style.LeadingMarginSpan; -import android.text.style.MaskFilterSpan; -import android.text.style.QuoteSpan; -import android.text.style.RelativeSizeSpan; -import android.text.style.ScaleXSpan; -import android.text.style.StrikethroughSpan; -import android.text.style.StyleSpan; -import android.text.style.SubscriptSpan; -import android.text.style.SuperscriptSpan; -import android.text.style.TypefaceSpan; -import android.text.style.URLSpan; -import android.text.style.UnderlineSpan; - -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * 创建者:邓浩宸 - * 时间 :2017/6/21 20:11 - * 描述 :TODO 请描述该类职责 - */ -@SuppressWarnings(value = {"unused", "WeakerAccess"}) -public class SpannableUtils { - - - private static Builder builder; - - private SpannableUtils() { - } - - - public static Builder getBuilder(CharSequence charSequence) { - builder = new Builder(charSequence); - return builder; - } - - - public static class Builder { - private int fontSize; - private boolean fontSizeIsDp; - private SpannableString spannableString; - private Index index; - - private int flag = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE; - private int defaultValue = 0x12000000; - - private int foregroundColor; - private int backgroundColor; - private int quoteColor; - private int first; - private int rest; - private boolean isLeadingMargin; - private int gapWidth; - private int bulletColor; - private boolean isBullet; - private float proportion; - private float xProportion; - private boolean isStrikethrough; - private boolean isUnderline; - private boolean isSuperscript; - private boolean isSubscript; - private boolean isBold; - private boolean isItalic; - private boolean isBoldItalic; - private String fontFamily; - private Layout.Alignment align; - private Bitmap bitmap; - private boolean imageIsBitmap; - private Drawable drawable; - private boolean imageIsDrawable; - private Uri uri; - private boolean imageIsUri; - private int resourceId; - private boolean imageIsResourceId; - private ClickableSpan clickSpan; - private String url; - private float radius; - private BlurMaskFilter.Blur style; - private boolean isBlur; - - private Builder(CharSequence charSequence) { - spannableString = new SpannableString(charSequence); - - foregroundColor = defaultValue; - backgroundColor = defaultValue; - quoteColor = defaultValue; - proportion = -1; - xProportion = -1; - } - - - /** - * 设置前景色 - * - * @param color 前景色 - * @return {@link Index} - */ - public Index setForegroundColor(@ColorInt int color) { - this.foregroundColor = color; - return getIndex(); - } - - - /** - * 设置背景色 - * - * @param color 背景色 - * @return {@link Index} - */ - public Index setBackgroundColor(@ColorInt int color) { - this.backgroundColor = color; - return getIndex(); - } - - - /** - * 设置字体尺寸 - * - * @param size 尺寸 - * @return {@link Builder} - */ - public Index setFontSize(int size) { - this.fontSize = size; - this.fontSizeIsDp = false; - return getIndex(); - } - - /** - * 设置字体尺寸 - * - * @param size 尺寸 - * @param isDp 是否使用dip - * @return {@link Builder} - */ - public Index setFontSize(int size, boolean isDp) { - this.fontSize = size; - this.fontSizeIsDp = isDp; - return getIndex(); - } - - - /** - * 设置引用线的颜色 - * - * @param color 引用线的颜色 - * @return {@link Index} - */ - public Index setQuoteColor(@ColorInt int color) { - this.quoteColor = color; - return getIndex(); - } - - /** - * 设置缩进 - * - * @param first 首行缩进 - * @param rest 剩余行缩进 - * @return {@link Index} - */ - public Index setLeadingMargin(int first, int rest) { - this.first = first; - this.rest = rest; - isLeadingMargin = true; - return getIndex(); - } - - /** - * 设置列表标记 - * - * @param gapWidth 列表标记和文字间距离 - * @param color 列表标记的颜色 - * @return {@link Index} - */ - public Index setBullet(int gapWidth, int color) { - this.gapWidth = gapWidth; - bulletColor = color; - isBullet = true; - return getIndex(); - } - - /** - * 设置字体比例 - * - * @param proportion 比例 - * @return {@link Index} - */ - public Index setProportion(float proportion) { - this.proportion = proportion; - return getIndex(); - } - - /** - * 设置字体横向比例 - * - * @param proportion 比例 - * @return {@link Index} - */ - public Index setXProportion(float proportion) { - this.xProportion = proportion; - return getIndex(); - } - - /** - * 设置删除线 - * - * @return {@link Index} - */ - public Index setStrikethrough() { - this.isStrikethrough = true; - return getIndex(); - } - - /** - * 设置下划线 - * - * @return {@link Index} - */ - public Index setUnderline() { - this.isUnderline = true; - return getIndex(); - } - - /** - * 设置上标 - * - * @return {@link Index} - */ - public Index setSuperscript() { - this.isSuperscript = true; - return getIndex(); - } - - /** - * 设置下标 - * - * @return {@link Index} - */ - public Index setSubscript() { - this.isSubscript = true; - return getIndex(); - } - - /** - * 设置粗体 - * - * @return {@link Index} - */ - public Index setBold() { - isBold = true; - return getIndex(); - } - - /** - * 设置斜体 - * - * @return {@link Index} - */ - public Index setItalic() { - isItalic = true; - return getIndex(); - } - - /** - * 设置粗斜体 - * - * @return {@link Index} - */ - public Index setBoldItalic() { - isBoldItalic = true; - return getIndex(); - } - - /** - * 设置字体 - * - * @param fontFamily 字体 - *

    - *
  • monospace
  • - *
  • serif
  • - *
  • sans-serif
  • - *
- * @return {@link Index} - */ - public Index setFontFamily(@Nullable String fontFamily) { - this.fontFamily = fontFamily; - return getIndex(); - } - - /** - * 设置对齐 - * - * @param align 对其方式 - *
    - *
  • {@link Layout.Alignment#ALIGN_NORMAL}正常
  • - *
  • {@link Layout.Alignment#ALIGN_OPPOSITE}相反
  • - *
  • {@link Layout.Alignment#ALIGN_CENTER}居中
  • - *
- * @return {@link Index} - */ - public Index setAlign(@Nullable Layout.Alignment align) { - this.align = align; - return getIndex(); - } - - /** - * 设置图片 - * - * @param bitmap 图片位图 - * @return {@link Index} - */ - public Index setBitmap(@NonNull Bitmap bitmap) { - this.bitmap = bitmap; - imageIsBitmap = true; - return getIndex(); - } - - /** - * 设置图片 - * - * @param drawable 图片资源 - * @return {@link Index} - */ - public Index setDrawable(@NonNull Drawable drawable) { - this.drawable = drawable; - imageIsDrawable = true; - return getIndex(); - } - - /** - * 设置图片 - * - * @param uri 图片uri - * @return {@link Index} - */ - public Index setUri(@NonNull Uri uri) { - this.uri = uri; - imageIsUri = true; - return getIndex(); - } - - /** - * 设置图片 - * - * @param resourceId 图片资源id - * @return {@link Index} - */ - public Index setResourceId(@DrawableRes int resourceId) { - this.resourceId = resourceId; - imageIsResourceId = true; - return getIndex(); - } - - /** - * 设置点击事件 - *

需添加view.setMovementMethod(LinkMovementMethod.getInstance())

- * - * @param clickSpan 点击事件 - * @return {@link Index} - */ - public Index setClickSpan(@NonNull ClickableSpan clickSpan) { - this.clickSpan = clickSpan; - return getIndex(); - } - - /** - * 设置超链接 - *

需添加view.setMovementMethod(LinkMovementMethod.getInstance())

- * - * @param url 超链接 - * @return {@link Index} - */ - public Index setUrl(@NonNull String url) { - this.url = url; - return getIndex(); - } - - /** - * 设置模糊 - *

尚存bug,其他地方存在相同的字体的话,相同字体出现在之前的话那么就不会模糊,出现在之后的话那会一起模糊

- *

推荐还是把所有字体都模糊这样使用

- * - * @param radius 模糊半径(需大于0) - * @param style 模糊样式
    - *
  • {@link BlurMaskFilter.Blur#NORMAL}
  • - *
  • {@link BlurMaskFilter.Blur#SOLID}
  • - *
  • {@link BlurMaskFilter.Blur#OUTER}
  • - *
  • {@link BlurMaskFilter.Blur#INNER}
  • - *
- * @return {@link Index} - */ - public Index setBlur(float radius, BlurMaskFilter.Blur style) { - this.radius = radius; - this.style = style; - this.isBlur = true; - return getIndex(); - } - - - /** - * 创建样式字符串 - * - * @return 样式字符串 - */ - public SpannableString build() { - return spannableString; - } - - @NonNull - private Index getIndex() { - if (index == null) { - index = new Index(spannableString.toString()); - } - return index; - } - - - private void setSpan() { - if (fontSize != -1) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new AbsoluteSizeSpan(fontSize, fontSizeIsDp), entry.getKey(), entry.getValue(), flag); - fontSize = -1; - fontSizeIsDp = false; - } - if (foregroundColor != defaultValue) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new ForegroundColorSpan(foregroundColor), entry.getKey(), entry.getValue(), flag); - foregroundColor = defaultValue; - } - if (backgroundColor != defaultValue) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new BackgroundColorSpan(backgroundColor), entry.getKey(), entry.getValue(), flag); - backgroundColor = defaultValue; - } - if (isLeadingMargin) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new LeadingMarginSpan.Standard(first, rest), entry.getKey(), entry.getValue(), flag); - isLeadingMargin = false; - } - if (quoteColor != defaultValue) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new QuoteSpan(quoteColor), entry.getKey(), entry.getValue(), 0); - quoteColor = defaultValue; - } - if (isBullet) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new BulletSpan(gapWidth, bulletColor), entry.getKey(), entry.getValue(), 0); - isBullet = false; - } - if (proportion != -1) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new RelativeSizeSpan(proportion), entry.getKey(), entry.getValue(), flag); - proportion = -1; - } - if (xProportion != -1) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new ScaleXSpan(xProportion), entry.getKey(), entry.getValue(), flag); - xProportion = -1; - } - if (isStrikethrough) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new StrikethroughSpan(), entry.getKey(), entry.getValue(), flag); - isStrikethrough = false; - } - if (isUnderline) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new UnderlineSpan(), entry.getKey(), entry.getValue(), flag); - isUnderline = false; - } - if (isSuperscript) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new SuperscriptSpan(), entry.getKey(), entry.getValue(), flag); - isSuperscript = false; - } - if (isSubscript) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new SubscriptSpan(), entry.getKey(), entry.getValue(), flag); - isSubscript = false; - } - if (isBold) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new StyleSpan(Typeface.BOLD), entry.getKey(), entry.getValue(), flag); - isBold = false; - } - if (isItalic) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new StyleSpan(Typeface.ITALIC), entry.getKey(), entry.getValue(), flag); - isItalic = false; - } - if (isBoldItalic) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), entry.getKey(), entry.getValue(), flag); - isBoldItalic = false; - } - if (fontFamily != null) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new TypefaceSpan(fontFamily), entry.getKey(), entry.getValue(), flag); - fontFamily = null; - } - if (align != null) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new AlignmentSpan.Standard(align), entry.getKey(), entry.getValue(), flag); - align = null; - } - if (imageIsBitmap || imageIsDrawable || imageIsUri || imageIsResourceId) { - if (imageIsBitmap) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new ImageSpan(AppContext.get(), bitmap), entry.getKey(), entry.getValue(), flag); - bitmap = null; - imageIsBitmap = false; - } else if (imageIsDrawable) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new ImageSpan(drawable), entry.getKey(), entry.getValue(), flag); - drawable = null; - imageIsDrawable = false; - } else if (imageIsUri) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new ImageSpan(AppContext.get(), uri), entry.getKey(), entry.getValue(), flag); - uri = null; - imageIsUri = false; - } else { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new ImageSpan(AppContext.get(), resourceId), entry.getKey(), entry.getValue(), flag); - resourceId = 0; - imageIsResourceId = false; - } - } - if (clickSpan != null) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(clickSpan, entry.getKey(), entry.getValue(), flag); - clickSpan = null; - } - if (url != null) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new URLSpan(url), entry.getKey(), entry.getValue(), flag); - url = null; - } - if (isBlur) { - for (Map.Entry entry : index.getIndex()) - spannableString.setSpan(new MaskFilterSpan(new BlurMaskFilter(radius, style)), entry.getKey(), entry.getValue(), flag); - isBlur = false; - } - } - - - public static class Index { - - private int start; - private int end; - private int position; - private final String source; - private TreeMap map; - - - public Index(String s) { - source = s; - } - - public Index setContain(String s) { - int indexOf = source.indexOf(s); - setIndex(indexOf, indexOf + s.length()); - return this; - } - - public Index setContain(String s, int start) { - int indexOf = source.indexOf(s, start); - setIndex(indexOf, indexOf + s.length()); - return this; - } - - - public Index setRegex(String regex) { - Matcher m = Pattern.compile(regex).matcher(source); - - while (m.find()) { - setContain(m.group(), position); - } - - return this; - } - - - public Index setStart(int start) { - if (start > this.start) { - this.start = start; - } - if (this.start > this.end) { - this.end = this.start; - } - return this; - } - - public Index setStart(String c) { - setStart(source.indexOf(c)); - return this; - } - - public Index setEnd(String c) { - setEnd(source.lastIndexOf(c)); - return this; - } - - public Index setEnd(int end) { - if (end <= source.length()) { - this.end = end; - } - return this; - } - - public Index setMaxEnd() { - end = source.length(); - return this; - } - - public Index setIndex(int start, int end) { - boolean canPut = start >= 0 && start <= end; - if (map == null) { - map = new TreeMap<>(); - } - - for (Map.Entry entry : map.entrySet()) { - canPut = canPut && entry.getKey() < start && start < entry.getValue(); - } - - if (canPut) { - map.put(start, end); - position = end; - } - return this; - } - - - public Builder create() { - if (map == null) { - setIndex(start, end); - } - builder.setSpan(); - builder.index = null; - return builder; - } - - - private Set> getIndex() { - return map.entrySet(); - - } - - } - - - } - -} - diff --git a/baselib/library/src/main/java/com/dhc/library/utils/UploadUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/UploadUtil.java deleted file mode 100644 index 46abcfa..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/UploadUtil.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.dhc.library.utils; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import okhttp3.MediaType; -import okhttp3.MultipartBody; -import okhttp3.RequestBody; - -/** - * 创建者 邓浩宸 - * 创建时间 2016/12/9 14:17 - * 描述 TODO - */ - -public class UploadUtil { - - - /** - * 将文件路径数组封装为{@link List} - * @param key 对应请求正文中name的值。目前服务器给出的接口中,所有图片文件使用
- * 同一个name值,实际情况中有可能需要多个 - * @param filePaths 文件路径数组 - * @param imageType 文件类型 - */ - public static List files2Parts(String key, - String[] filePaths, MediaType imageType) { - List parts = new ArrayList<>(filePaths.length); - for (int i = 0; i - * 不同的是使用MultipartBody.Builder来构建MultipartBody - * @param key 同上 - * @param filePaths 同上 - * @param imageType 同上 - */ - public static MultipartBody filesToMultipartBody(String key, - String[] filePaths, - MediaType imageType) { - MultipartBody.Builder builder = new MultipartBody.Builder(); - for (int i = 0; i parts, - String key, String value, int position) { - RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value); - MultipartBody.Part part = MultipartBody.Part.createFormData(key, null, requestBody); - parts.add(position, part); - } - - /** - * 添加文本类型的Part到的MultipartBody.Builder中 - * @param builder 用于构建MultipartBody的Builder - * @param key 参数名(name属性) - * @param value 文本内容 - */ - public static MultipartBody.Builder addTextPart(MultipartBody.Builder builder, - String key, String value) { - RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value); - // MultipartBody.Builder的addFormDataPart()有一个直接添加key value的重载,但坑的是这个方法 - // 不会设置编码类型,会出乱码,所以可以使用3个参数的,将中间的filename置为null就可以了 - // builder.addFormDataPart(key, value); - // 还有一个坑就是,后台取数据的时候有可能是有顺序的,比如必须先取文本后取文件, - // 否则就取不到(真弱啊...),所以还要注意add的顺序 - builder.addFormDataPart(key, null, requestBody); - return builder; - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/file/AttachmentStore.java b/baselib/library/src/main/java/com/dhc/library/utils/file/AttachmentStore.java deleted file mode 100644 index 3166958..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/file/AttachmentStore.java +++ /dev/null @@ -1,348 +0,0 @@ - -package com.dhc.library.utils.file; - -import android.graphics.Bitmap; -import android.text.TextUtils; -import android.util.Log; - - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; - - -/** - * 用于把附件保存到文件系统中 - */ -public class AttachmentStore { - public static long copy(String srcPath, String dstPath) { - if (TextUtils.isEmpty(srcPath) || TextUtils.isEmpty(dstPath)) { - return -1; - } - - File source = new File(srcPath); - if (!source.exists()) { - return -1; - } - - if (srcPath.equals(dstPath)) { - return source.length(); - } - - FileChannel fcin = null; - FileChannel fcout = null; - try { - fcin = new FileInputStream(source).getChannel(); - fcout = new FileOutputStream(create(dstPath)).getChannel(); - ByteBuffer tmpBuffer = ByteBuffer.allocateDirect(4096); - while (fcin.read(tmpBuffer) != -1) { - tmpBuffer.flip(); - fcout.write(tmpBuffer); - tmpBuffer.clear(); - } - return source.length(); - - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if (fcin != null) { - fcin.close(); - } - if (fcout != null) { - fcout.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - return -1; - } - - public static long getFileLength(String srcPath) { - if (TextUtils.isEmpty(srcPath)) { - return -1; - } - - File srcFile = new File(srcPath); - if (!srcFile.exists()) { - return -1; - } - - return srcFile.length(); - } - - public static long save(String path, String content) { - return save(content.getBytes(), path); - } - - /** - * 把数据保存到文件系统中,并且返回其大小 - * - * @param data - * @param filePath - * @return 如果保存失败,则返回-1 - */ - public static long save(byte[] data, String filePath) { - if (TextUtils.isEmpty(filePath)) { - return -1; - } - - File f = new File(filePath); - if(f.getParentFile() == null) { - return -1; - } - - if (!f.getParentFile().exists()) {// 如果不存在上级文件夹 - f.getParentFile().mkdirs(); - } - try { - f.createNewFile(); - FileOutputStream fout = new FileOutputStream(f); - fout.write(data); - fout.close(); - } catch (IOException e) { - e.printStackTrace(); - return -1; - } - return f.length(); - } - - public static boolean move(String srcFilePath, String dstFilePath) { - if (TextUtils.isEmpty(srcFilePath) || TextUtils.isEmpty(dstFilePath)) { - return false; - } - - File srcFile = new File(srcFilePath); - if (!srcFile.exists() || !srcFile.isFile()) { - return false; - } - - File dstFile = new File(dstFilePath); - if(dstFile.getParentFile() == null) { - return false; - } - - if (!dstFile.getParentFile().exists()) {// 如果不存在上级文件夹 - dstFile.getParentFile().mkdirs(); - } - - return srcFile.renameTo(dstFile); - } - - public static File create(String filePath) { - if (TextUtils.isEmpty(filePath)) { - return null; - } - - File f = new File(filePath); - if (!f.getParentFile().exists()) {// 如果不存在上级文件夹 - f.getParentFile().mkdirs(); - } - try { - f.createNewFile(); - return f; - } catch (IOException e) { - if(f!=null && f.exists()){ - f.delete(); - } - return null; - } - } - - /** - * @param is - * @param filePath - * @return 保存失败,返回-1 - */ - public static long save(InputStream is, String filePath) { - File f = new File(filePath); - if (!f.getParentFile().exists()) {// 如果不存在上级文件夹 - f.getParentFile().mkdirs(); - } - FileOutputStream fos = null; - try { - f.createNewFile(); - fos = new FileOutputStream(f); - int read = 0; - byte[] bytes = new byte[8091]; - while ((read = is.read(bytes)) != -1) { - fos.write(bytes, 0, read); - } - return f.length(); - } catch (IOException e) { - if(f!=null && f.exists()){ - f.delete(); - } - Log.i("file", "save is to " + filePath + " failed: " + e.getMessage()); - return -1; - } finally { - try { - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - try { - if (fos != null) { - fos.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - /** - * 把文件从文件系统中读取出来 - * - * @param path - * @return 如果无法读取,则返回null - */ - public static byte[] load(String path) { - try { - File f = new File(path); - int unread = (int) f.length(); - int read = 0; - byte[] buf = new byte[unread]; // 读取文件长度 - FileInputStream fin = new FileInputStream(f); - do { - int count = fin.read(buf, read, unread); - read += count; - unread -= count; - } while (unread != 0); - fin.close(); - return buf; - } catch (FileNotFoundException e) { - return null; - } catch (IOException e) { - return null; - } - } - - public static String loadAsString(String path) { - if (isFileExist(path)) { - byte[] content = load(path); - return new String(content); - } else { - return null; - } - } - - /** - * 删除指定路径文件 - * - * @param path - */ - public static boolean delete(String path) { - if(TextUtils.isEmpty(path)){ - return false; - } - File f = new File(path); - if (f.exists()) { - f = renameOnDelete(f); - return f.delete(); - } else { - return false; - } - } - - public static void deleteOnExit(String path) { - if(TextUtils.isEmpty(path)){ - return; - } - File f = new File(path); - if (f.exists()) { - f.deleteOnExit(); - } - } - - public static boolean deleteDir(String path) { - return deleteDir(path, true); - } - - private static boolean deleteDir(String path, boolean rename) { - boolean success = true; - File file = new File(path); - if (file.exists()) { - if (rename) { - file = renameOnDelete(file); - } - - File[] list = file.listFiles(); - if (list != null) { - int len = list.length; - for (int i = 0; i < len; ++i) { - if (list[i].isDirectory()) { - deleteDir(list[i].getPath(), false); - } else { - boolean ret = list[i].delete(); - if (!ret) { - success = false; - } - } - } - } - } else { - success = false; - } - if (success) { - file.delete(); - } - return success; - } - - // rename before delete to avoid lingering filesystem lock of android - private static File renameOnDelete(File file) { - String tmpPath = file.getParent() + "/" + System.currentTimeMillis() + "_tmp"; - File tmpFile = new File(tmpPath); - if (file.renameTo(tmpFile)) { - return tmpFile; - } else { - return file; - } - } - - public static boolean isFileExist(String path) { - if (!TextUtils.isEmpty(path) && new File(path).exists()) { - return true; - } - else { - return false; - } - } - - public static boolean saveBitmap(Bitmap bitmap, String path, boolean recyle) { - if (bitmap == null || TextUtils.isEmpty(path)) { - return false; - } - - BufferedOutputStream bos = null; - try { - FileOutputStream fos = new FileOutputStream(path); - bos = new BufferedOutputStream(fos); - bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos); - return true; - - } catch (FileNotFoundException e) { - return false; - } finally { - if (bos != null) { - try { - bos.close(); - } catch (IOException e) { - } - } - if (recyle) { - bitmap.recycle(); - } - } - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/file/FileUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/file/FileUtil.java deleted file mode 100644 index 75cf709..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/file/FileUtil.java +++ /dev/null @@ -1,653 +0,0 @@ -package com.dhc.library.utils.file; - -import android.content.Context; -import android.content.res.AssetFileDescriptor; -import android.graphics.Bitmap; -import android.graphics.drawable.BitmapDrawable; -import android.os.Environment; -import android.text.TextUtils; - -import com.dhc.library.utils.string.StringUtil; - -import java.io.BufferedOutputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.text.DecimalFormat; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Properties; -import java.util.Set; - -/** - * 文件工具类 - */ -public class FileUtil { - - - public static final String ASSETS_PREFIX = "file://android_assets/"; - public static final String ASSETS_PREFIX2 = "file://android_asset/"; - public static final String ASSETS_PREFIX3 = "assets://"; - public static final String ASSETS_PREFIX4 = "asset://"; - public static final String RAW_PREFIX = "file://android_raw/"; - public static final String RAW_PREFIX2 = "raw://"; - public static final String FILE_PREFIX = "file://"; - public static final String DRAWABLE_PREFIX = "drawable://"; - - public enum SizeUnit { - Byte, - KB, - MB, - GB, - TB, - Auto, - } - - private static final String TAG = "FileUtil"; - - public static boolean hasExtentsion(String filename) { - int dot = filename.lastIndexOf('.'); - if ((dot > -1) && (dot < (filename.length() - 1))) { - return true; - } else { - return false; - } - } - - // 获取文件扩展名 - public static String getExtensionName(String filename) { - if ((filename != null) && (filename.length() > 0)) { - int dot = filename.lastIndexOf('.'); - if ((dot > -1) && (dot < (filename.length() - 1))) { - return filename.substring(dot + 1); - } - } - return ""; - } - - // 获取文件名 - public static String getFileNameFromPath(String filepath) { - if ((filepath != null) && (filepath.length() > 0)) { - int sep = filepath.lastIndexOf('/'); - if ((sep > -1) && (sep < filepath.length() - 1)) { - return filepath.substring(sep + 1); - } - } - return filepath; - } - - // 获取不带扩展名的文件名 - public static String getFileNameNoEx(String filename) { - if ((filename != null) && (filename.length() > 0)) { - int dot = filename.lastIndexOf('.'); - if ((dot > -1) && (dot < (filename.length()))) { - return filename.substring(0, dot); - } - } - return filename; - } - - - - /** - * 读取Property文件 - */ - public static HashMap simpleProperty2HashMap(Context context, String path) { - try { - InputStream is = getStream(context, path); - return simpleProperty2HashMap(is); - } catch (IOException e) { - e.printStackTrace(); - } - - return new HashMap(); - } - - private static HashMap simpleProperty2HashMap(InputStream in) throws IOException { - HashMap hashMap = new HashMap(); - Properties properties = new Properties(); - properties.load(in); - in.close(); - Set keyValue = properties.keySet(); - for (Iterator it = keyValue.iterator(); it.hasNext(); ) { - String key = (String) it.next(); - hashMap.put(key, (String) properties.get(key)); - } - - return hashMap; - } - - - public static InputStream getStream(Context context, String url) throws IOException { - String lowerUrl = url.toLowerCase(); - InputStream is; - if (lowerUrl.startsWith(ASSETS_PREFIX)) { - String assetPath = url.substring(ASSETS_PREFIX.length()); - is = getAssetsStream(context, assetPath); - } else if (lowerUrl.startsWith(ASSETS_PREFIX2)) { - String assetPath = url.substring(ASSETS_PREFIX2.length()); - is = getAssetsStream(context, assetPath); - } else if (lowerUrl.startsWith(ASSETS_PREFIX3)) { - String assetPath = url.substring(ASSETS_PREFIX3.length()); - is = getAssetsStream(context, assetPath); - } else if (lowerUrl.startsWith(ASSETS_PREFIX4)) { - String assetPath = url.substring(ASSETS_PREFIX4.length()); - is = getAssetsStream(context, assetPath); - } else if (lowerUrl.startsWith(RAW_PREFIX)) { - String rawName = url.substring(RAW_PREFIX.length()); - is = getRawStream(context, rawName); - } else if (lowerUrl.startsWith(RAW_PREFIX2)) { - String rawName = url.substring(RAW_PREFIX2.length()); - is = getRawStream(context, rawName); - } else if (lowerUrl.startsWith(FILE_PREFIX)) { - String filePath = url.substring(FILE_PREFIX.length()); - is = getFileStream(filePath); - } else if (lowerUrl.startsWith(DRAWABLE_PREFIX)) { - String drawableName = url.substring(DRAWABLE_PREFIX.length()); - is = getDrawableStream(context, drawableName); - } else { - throw new IllegalArgumentException(String.format("Unsupported url: %s \n" + - "Supported: \n%sxxx\n%sxxx\n%sxxx", url, ASSETS_PREFIX, RAW_PREFIX, FILE_PREFIX)); - } - return is; - } - - private static InputStream getAssetsStream(Context context, String path) throws IOException { - return context.getAssets().open(path); - } - - private static InputStream getFileStream(String path) throws IOException { - return new FileInputStream(path); - } - - private static InputStream getRawStream(Context context, String rawName) throws IOException { - int id = context.getResources().getIdentifier(rawName, "raw", context.getPackageName()); - if (id != 0) { - try { - return context.getResources().openRawResource(id); - } catch (Exception e) { - e.printStackTrace(); - } - } - - throw new IOException(String.format("raw of id: %s from %s not found", id, rawName)); - } - - private static InputStream getDrawableStream(Context context, String rawName) throws IOException { - int id = context.getResources().getIdentifier(rawName, "drawable", context.getPackageName()); - if (id != 0) { - BitmapDrawable drawable = (BitmapDrawable) context.getResources().getDrawable(id); - Bitmap bitmap = drawable.getBitmap(); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - bitmap.compress(Bitmap.CompressFormat.PNG, 0, os); - return new ByteArrayInputStream(os.toByteArray()); - } - - throw new IOException(String.format("bitmap of id: %s from %s not found", id, rawName)); - } - - public static String getString(Context context, String url) throws IOException { - return getString(context, url, "UTF-8"); - } - - public static String getString(Context context, String url, String encoding) throws IOException { - String result = readStreamString(getStream(context, url), encoding); - if (result.startsWith("\ufeff")) { - result = result.substring(1); - } - - return result; - } - - public static String readStreamString(InputStream is, String encoding) throws IOException { - return new String(readStream(is), encoding); - } - - public static byte[] readStream(InputStream is) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte[] buf = new byte[1024 * 10]; - int readlen; - while ((readlen = is.read(buf)) >= 0) { - baos.write(buf, 0, readlen); - } - baos.close(); - - return baos.toByteArray(); - } - - - - /** - * 把字节数组保存为一个文件 - * - * @param b - * @param fileName - * @return - */ - public static File write(byte[] b, String fileName) { - BufferedOutputStream stream = null; - File file = null; - try { - file = new File(fileName); - stream = new BufferedOutputStream(new FileOutputStream(file)); - stream.write(b); - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (stream != null) { - try { - stream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - return file; - } - - /** - * 文件/目录是否存在 - * - * @param fileName - * @return - */ - public static boolean exist(String fileName) { - return new File(fileName).exists(); - } - - /** - * 创建目录 - * - * @param path 目录 - * @param cover 是否覆盖 - * @return - */ - public static void createFolder(String path, boolean cover) { - try { - File file = new File(path); - if (file.exists()) { - if (cover) { - FileUtil.deleteFile(path, true); - file.mkdirs(); - } - } else { - file.mkdirs(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * 创建空的文件 - * - * @param fileName 文件 - * @param cover 是否覆盖 - * @return - */ - public static boolean createFile(String fileName, boolean cover) { - if (TextUtils.isEmpty(fileName)) { - return false; - } - try { - File file = new File(fileName); - if (file.exists()) { - if (cover) { - file.delete(); - file.createNewFile(); - } - } else { - // 如果路径不存在,先创建路 - File mFile = file.getParentFile(); - if (!mFile.exists()) { - mFile.mkdirs(); - } - file.createNewFile(); - } - } catch (Exception e) { - return false; - } - return true; - } - - /** - * 删除文件 - * - * @param filePath - * @param deleteParent 是否删除父目录 - */ - public static void deleteFile(String filePath, boolean deleteParent) { - if (filePath == null) { - return; - } - try { - File f = new File(filePath); - if (f.exists() && f.isDirectory()) { - File[] delFiles = f.listFiles(); - if (delFiles != null) { - for (File delFile : delFiles) { - deleteFile(delFile.getAbsolutePath(), deleteParent); - } - } - } - if (deleteParent) { - f.delete(); - } else if (f.isFile()) { - f.delete(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * 复制单个文件 - * - * @param oldPath String 原文件路径 如:c:/fqf.txt - * @param newPath String 复制后路径 如:f:/fqf.txt - * @return boolean - */ - public static void copyFile(String oldPath, String newPath) { - try { -// int bytesum = 0; - int byteread = 0; - File oldfile = new File(oldPath); - if (oldfile.exists()) { //文件存在时 - InputStream inStream = new FileInputStream(oldPath); //读入原文件 - FileOutputStream fs = new FileOutputStream(newPath); - byte[] buffer = new byte[1444]; - int length; - while ((byteread = inStream.read(buffer)) != -1) { -// bytesum += byteread; //字节数 文件大小 -// System.out.println(bytesum); - fs.write(buffer, 0, byteread); - } - inStream.close(); - } - } catch (Exception e) { -// System.out.println("复制单个文件操作出错"); - e.printStackTrace(); - - } - - } - - /** - * 复制整个文件夹内容 - * - * @param oldPath String 原文件路径 如:c:/fqf - * @param newPath String 复制后路径 如:f:/fqf/ff - * @return boolean - */ - public static void copyFolder(String oldPath, String newPath) { - - try { - (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹 - File a = new File(oldPath); - String[] file = a.list(); - File temp = null; - for (int i = 0; i < file.length; i++) { - if (oldPath.endsWith(File.separator)) { - temp = new File(oldPath + file[i]); - } else { - temp = new File(oldPath + File.separator + file[i]); - } - - if (temp.isFile()) { - FileInputStream input = new FileInputStream(temp); - FileOutputStream output = new FileOutputStream(newPath + "/" + temp.getName()); - byte[] b = new byte[1024 * 5]; - int len; - while ((len = input.read(b)) != -1) { - output.write(b, 0, len); - } - output.flush(); - output.close(); - input.close(); - } - if (temp.isDirectory()) {//如果是子文件夹 - copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]); - } - } - } catch (Exception e) { -// System.out.println("复制整个文件夹内容操作出错"); - e.printStackTrace(); - - } - - } - - /** - * 判断手机SDCard是否已安装并可读写 - * - * @return - */ - public static boolean isSDCardAvailable() { - return Environment.MEDIA_MOUNTED.equalsIgnoreCase(Environment.getExternalStorageState()); - } - - /** - * 读取文件 - * - * @param fileName - * @return - */ - public static String readFile(String fileName) { - try { - return readFromStream(new FileInputStream(new File(fileName))); - } catch (FileNotFoundException e) { - e.printStackTrace(); - return null; - } - } - - /** - * 读取assets文件 - * - * @param context - * @param fileName - * @return - */ - public static String readAsset(Context context, String fileName) { - try { - AssetFileDescriptor descriptor = context.getApplicationContext().getAssets().openFd(fileName); - return readFromStream(descriptor.createInputStream()); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - - /** - * 读取raw文件 - * - * @param context - * @param resId - * @return - */ - public static String readRaw(Context context, int resId) { - return readFromStream(context.getResources().openRawResource(resId)); - } - - private static String readFromStream(InputStream in) { - if (in == null) { - return null; - } - - try { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - int len; - while ((len = in.read(buffer)) != -1) { - out.write(buffer, 0, len); - } - in.close(); - out.close(); - return new String(out.toByteArray(), "UTF-8"); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - - public static String getSavePath(Context context, String FileName) { - return getCacheDirectory(context).getAbsolutePath() + File.separator - + FileName; - } - - public static File getCacheDirectory(Context context) { - File appCacheDir = null; - if (Environment.getExternalStorageState().equals( - Environment.MEDIA_MOUNTED)) { - appCacheDir = getExternalCacheDir(context); - } - if (appCacheDir == null) { - appCacheDir = context.getCacheDir(); - } - return appCacheDir; - } - - private static File getExternalCacheDir(Context context) { - File dataDir = new File(new File( - Environment.getExternalStorageDirectory(), "Android"), "data"); - File appCacheDir = new File( - new File(dataDir, context.getPackageName()), "cache"); - if (!appCacheDir.exists()) { - if (!appCacheDir.mkdirs()) { - return null; - } - try { - new File(appCacheDir, ".nomedia").createNewFile(); - } catch (IOException e) { - } - } - return appCacheDir; - } - - public static File createFile(String path) { - if (path != null) { - File file = new File(path); - if (!file.exists()) { - File file2 = new File(file.getParent()); - file2.mkdir(); - try { - file.createNewFile(); - } catch (IOException e) { - return null; - } - } - return file; - } - return null; - - } - - - /** - * 获取文件或文件夹大小 - * - * @param fileOrDir 文件或文件夹对象 - * @return 字节数 - */ - public static long getFileOrDirSize(File fileOrDir) { - if (fileOrDir == null || !fileOrDir.exists()) { - return 0L; - } - - if (fileOrDir.isDirectory()) { - File[] children = fileOrDir.listFiles(); - long length = 0L; - for (File child : children) { - length += getFileOrDirSize(child); - } - return length; - } else { - return getFileSize(fileOrDir); - } - } - - /** - * 获取文件大小 - * - * @param file 文件对象 - * @return 字节数 - */ - private static long getFileSize(File file) { - if (file == null || !file.exists() || file.isDirectory()) { - return 0L; - } - return file.length(); - } - - - /** - * 获取文件后缀名 - * - * @param fileNameOrPath 文件名或文件路径 - * @return 后缀名(含“.”) - */ - public static String getSuffix(String fileNameOrPath) { - if (StringUtil.isEmpty(fileNameOrPath)) { - return ""; - } - String dot = "."; - if (!fileNameOrPath.contains(dot)) { - return ""; - } - return fileNameOrPath.substring(fileNameOrPath.lastIndexOf(dot)).toLowerCase(); - } - - /** - * 返回byte的数据大小对应的文本 - * - * @param size - * @return - */ - public static String formatFileSize(long size) { - DecimalFormat formater = new DecimalFormat("####.00"); - if (size == 0){ - return "0KB"; - }else if (size < 1024) { - return size + "bytes"; - } else if (size < 1024 * 1024) { - float kbsize = size / 1024f; - return formater.format(kbsize) + "KB"; - } else if (size < 1024 * 1024 * 1024) { - float mbsize = size / 1024f / 1024f; - return formater.format(mbsize) + "MB"; - } else if (size < 1024 * 1024 * 1024 * 1024) { - float gbsize = size / 1024f / 1024f / 1024f; - return formater.format(gbsize) + "GB"; - } else { - return "size: error"; - } - } - - - - public static void cleanCache(Context context){ - deleteFile(getCacheDirectory(context).getPath(),false); - } - - - /** - * 创建未存在的文件夹 - * - * @param file - * @return - */ - public static File makeDirs(File file) { - if (!file.exists()) { - file.mkdirs(); - } - return file; - } - - -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/media/BitmapDecoder.java b/baselib/library/src/main/java/com/dhc/library/utils/media/BitmapDecoder.java deleted file mode 100644 index f5b1f6a..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/media/BitmapDecoder.java +++ /dev/null @@ -1,275 +0,0 @@ -package com.dhc.library.utils.media; - -import android.annotation.TargetApi; -import android.content.res.Resources; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.media.ThumbnailUtils; -import android.os.Build; -import android.provider.MediaStore; - -import com.dhc.library.utils.sys.ScreenUtil; -import com.dhc.library.utils.file.AttachmentStore; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -/** - * 创建者:邓浩宸 - * 时间 :2017/5/11 11:37 - * 描述 :IM图片解码器 - */ -public class BitmapDecoder { - public static Bitmap decode(InputStream is) { - BitmapFactory.Options options = new BitmapFactory.Options(); - - // RGB_565 - options.inPreferredConfig = Bitmap.Config.RGB_565; - - /** - * 在4.4上,如果之前is标记被移动过,会导致解码失败 - */ - try { - if (is.markSupported()) { - is.reset(); - } - } catch (IOException e) { - e.printStackTrace(); - } - - try { - return BitmapFactory.decodeStream(is, null, options); - } catch (OutOfMemoryError e) { - e.printStackTrace(); - } - - return null; - } - - public static Bitmap decodeSampledForDisplay(String pathName) { - return decodeSampledForDisplay(pathName, true); - } - - public static Bitmap decodeSampledForDisplay(String pathName, boolean withTextureLimit) { - float ratio = ImageUtil.MAX_IMAGE_RATIO; - int[][] reqBounds = new int[][]{ - new int[]{ScreenUtil.screenWidth * 2, ScreenUtil.screenHeight}, - new int[]{ScreenUtil.screenWidth, ScreenUtil.screenHeight * 2}, - new int[]{(int) (ScreenUtil.screenWidth * 1.414), (int) (ScreenUtil.screenHeight * 1.414)}, - }; - - // decode bound - int[] bound = decodeBound(pathName); - // pick request bound - int[] reqBound = pickReqBoundWithRatio(bound, reqBounds, ratio); - - int width = bound[0]; - int height = bound[1]; - int reqWidth = reqBound[0]; - int reqHeight = reqBound[1]; - - // calculate sample size - int sampleSize = SampleSizeUtil.calculateSampleSize(width, height, reqWidth, reqHeight); - - if (withTextureLimit) { - // adjust sample size - sampleSize = SampleSizeUtil.adjustSampleSizeWithTexture(sampleSize, width, height); - } - - int RETRY_LIMIT = 5; - Bitmap bitmap = decodeSampled(pathName, sampleSize); - while (bitmap == null && RETRY_LIMIT > 0) { - sampleSize++; - RETRY_LIMIT--; - bitmap = decodeSampled(pathName, sampleSize); - } - - return bitmap; - } - - public static int[] decodeBound(String pathName) { - BitmapFactory.Options options = new BitmapFactory.Options(); - options.inJustDecodeBounds = true; - BitmapFactory.decodeFile(pathName, options); - - return new int[]{options.outWidth, options.outHeight}; - } - - public static int[] decodeBound(Resources res, int resId) { - BitmapFactory.Options options = new BitmapFactory.Options(); - options.inJustDecodeBounds = true; - BitmapFactory.decodeResource(res, resId, options); - - return new int[]{options.outWidth, options.outHeight}; - } - - private static int[] pickReqBoundWithRatio(int[] bound, int[][] reqBounds, float ratio) { - float hRatio = bound[1] == 0 ? 0 : (float) bound[0] / (float) bound[1]; - float vRatio = bound[0] == 0 ? 0 : (float) bound[1] / (float) bound[0]; - - if (hRatio >= ratio) { - return reqBounds[0]; - } else if (vRatio >= ratio) { - return reqBounds[1]; - } else { - return reqBounds[2]; - } - } - - public static Bitmap decodeSampled(String pathName, int sampleSize) { - BitmapFactory.Options options = new BitmapFactory.Options(); - - // RGB_565 - options.inPreferredConfig = Bitmap.Config.RGB_565; - // sample size - options.inSampleSize = sampleSize; - - Bitmap bitmap = null; - try { - bitmap = BitmapFactory.decodeFile(pathName, options); - } catch (OutOfMemoryError e) { - e.printStackTrace(); - return null; - } - - return checkInBitmap(bitmap, options, pathName); - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - private static Bitmap checkInBitmap(Bitmap bitmap, - BitmapFactory.Options options, String path) { - boolean honeycomb = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; - if (honeycomb && bitmap != options.inBitmap && options.inBitmap != null) { - options.inBitmap.recycle(); - options.inBitmap = null; - } - - if (bitmap == null) { - try { - bitmap = BitmapFactory.decodeFile(path, options); - } catch (OutOfMemoryError e) { - e.printStackTrace(); - } - } - return bitmap; - } - - public static int[] decodeBound(File file) { - InputStream is = null; - try { - is = new FileInputStream(file); - int[] bound = decodeBound(is); - return bound; - } catch (FileNotFoundException e) { - e.printStackTrace(); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - return new int[]{0, 0}; - } - - public static int[] decodeBound(InputStream is) { - BitmapFactory.Options options = new BitmapFactory.Options(); - options.inJustDecodeBounds = true; - BitmapFactory.decodeStream(is, null, options); - - return new int[]{options.outWidth, options.outHeight}; - } - - public static Bitmap decodeSampled(InputStream is, int reqWidth, int reqHeight) { - BitmapFactory.Options options = new BitmapFactory.Options(); - - // RGB_565 - options.inPreferredConfig = Bitmap.Config.RGB_565; - // sample size - options.inSampleSize = getSampleSize(is, reqWidth, reqHeight); - - try { - return BitmapFactory.decodeStream(is, null, options); - } catch (OutOfMemoryError e) { - e.printStackTrace(); - } - - return null; - } - - public static Bitmap decodeSampled(String pathName, int reqWidth, int reqHeight) { - return decodeSampled(pathName, getSampleSize(pathName, reqWidth, reqHeight)); - } - - public static int getSampleSize(InputStream is, int reqWidth, int reqHeight) { - // decode bound - int[] bound = decodeBound(is); - - // calculate sample size - int sampleSize = SampleSizeUtil.calculateSampleSize(bound[0], bound[1], reqWidth, reqHeight); - - return sampleSize; - } - - public static int getSampleSize(String pathName, int reqWidth, int reqHeight) { - // decode bound - int[] bound = decodeBound(pathName); - - // calculate sample size - int sampleSize = SampleSizeUtil.calculateSampleSize(bound[0], bound[1], reqWidth, reqHeight); - - return sampleSize; - } - - /** - * ******************************* decode resource ****************************************** - */ - - public static Bitmap decodeSampled(Resources resources, int resId, int reqWidth, int reqHeight) { - return decodeSampled(resources, resId, getSampleSize(resources, resId, reqWidth, reqHeight)); - } - - public static int getSampleSize(Resources resources, int resId, int reqWidth, int reqHeight) { - // decode bound - int[] bound = decodeBound(resources, resId); - - // calculate sample size - int sampleSize = SampleSizeUtil.calculateSampleSize(bound[0], bound[1], reqWidth, reqHeight); - - return sampleSize; - } - - - public static Bitmap decodeSampled(Resources res, int resId, int sampleSize) { - BitmapFactory.Options options = new BitmapFactory.Options(); - - // RGB_565 - options.inPreferredConfig = Bitmap.Config.RGB_565; - // sample size - options.inSampleSize = sampleSize; - - try { - return BitmapFactory.decodeResource(res, resId, options); - } catch (OutOfMemoryError e) { - e.printStackTrace(); - } - - return null; - } - - public static boolean extractThumbnail(String videoPath, String thumbPath) { - if (!AttachmentStore.isFileExist(thumbPath)) { - Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Images.Thumbnails.MINI_KIND); - if (thumbnail != null) { - AttachmentStore.saveBitmap(thumbnail, thumbPath, true); - return true; - } - } - return false; - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/media/BitmapUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/media/BitmapUtil.java deleted file mode 100644 index 2907756..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/media/BitmapUtil.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.dhc.library.utils.media; - -import android.content.res.Resources; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Matrix; -import android.media.ExifInterface; -import android.text.TextUtils; - -import java.io.IOException; - -/** - * 创建者:邓浩宸 - * 时间 :2017/5/11 11:37 - * 描述 :IM图片bitmap的工具类 - */ -public class BitmapUtil { - - /** - * 获取压缩后的图片 - * - * @param res - * @param resId - * @param reqWidth 所需图片压缩尺寸最小宽度 - * @param reqHeight 所需图片压缩尺寸最小高度 - * @return - */ - public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { - /** - * 1.获取图片的像素宽高(不加载图片至内存中,所以不会占用资源) - * 2.计算需要压缩的比例 - * 3.按将图片用计算出的比例压缩,并加载至内存中使用 - */ - // 首先不加载图片,仅获取图片尺寸 - final BitmapFactory.Options options = new BitmapFactory.Options(); - // 当inJustDecodeBounds设为true时,不会加载图片仅获取图片尺寸信息 - options.inJustDecodeBounds = true; - // 此时仅会将图片信息会保存至options对象内,decode方法不会返回bitmap对象 - BitmapFactory.decodeResource(res, resId, options); - - // 计算压缩比例,如inSampleSize=4时,图片会压缩成原图的1/4 - options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); - - // 当inJustDecodeBounds设为false时,BitmapFactory.decode...就会返回图片对象了 - options.inJustDecodeBounds = false; - options.inScaled = false; - // 利用计算的比例值获取压缩后的图片对象 - return BitmapFactory.decodeResource(res, resId, options); - } - - /** - * 计算压缩比例值 - * - * @param options 解析图片的配置信息 - * @param reqWidth 所需图片压缩尺寸最小宽度 - * @param reqHeight 所需图片压缩尺寸最小高度 - * @return - */ - public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { - // 保存图片原宽高值 - final int height = options.outHeight; - final int width = options.outWidth; - // 初始化压缩比例为1 - int inSampleSize = 1; - - // 当图片宽高值任何一个大于所需压缩图片宽高值时,进入循环计算系统 - if (height > reqHeight || width > reqWidth) { - - final int halfHeight = height / 2; - final int halfWidth = width / 2; - - // 压缩比例值每次循环两倍增加, - // 直到原图宽高值的一半除以压缩值后都~大于所需宽高值为止 - while ((halfHeight / inSampleSize) >= reqHeight - && (halfWidth / inSampleSize) >= reqWidth) { - inSampleSize *= 2; - } - } - - return inSampleSize; - } - - public static Bitmap reviewPicRotate(Bitmap bitmap, String path) { - int degree = 0; - String mimeType = getImageType(path); - if (!TextUtils.isEmpty(mimeType) && !mimeType.equals("image/png")) { - degree = getPicRotate(path); - } - if (degree != 0) { - try { - Matrix m = new Matrix(); - int width = bitmap.getWidth(); - int height = bitmap.getHeight(); - m.setRotate(degree); - bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true); - } catch (Exception e) { - e.printStackTrace(); - } catch (Error err) { - err.printStackTrace(); - } - } - return bitmap; - } - - - /** - * 读取图片属性:旋转的角度 - * - * @param path - * 图片绝对路径 - * @return degree旋转的角度 - */ - public static int getPicRotate(String path) { - int degree = 0; - try { - ExifInterface exifInterface = new ExifInterface(path); - int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); - switch (orientation) { - case ExifInterface.ORIENTATION_ROTATE_90: - degree = 90; - break; - case ExifInterface.ORIENTATION_ROTATE_180: - degree = 180; - break; - case ExifInterface.ORIENTATION_ROTATE_270: - degree = 270; - break; - } - } catch (IOException e) { - e.printStackTrace(); - } - return degree; - } - - public static Bitmap resizeBitmap(Bitmap bitmap, int w, int h) - { - if(bitmap == null) { - return null; - } - - Bitmap BitmapOrg = bitmap; - int width = BitmapOrg.getWidth(); - int height = BitmapOrg.getHeight(); - int newWidth = w; - int newHeight = h; - - float scaleWidth = ((float) newWidth) / width; - float scaleHeight = ((float) newHeight) / height; - - Matrix matrix = new Matrix(); - matrix.postScale(scaleWidth, scaleHeight); - - return Bitmap.createBitmap(BitmapOrg, 0, 0, width, height, matrix, true); - } - - public static String getImageType(String path) { - BitmapFactory.Options options = new BitmapFactory.Options(); - options.inJustDecodeBounds = true; - BitmapFactory.decodeFile(path, options); - return options.outMimeType; - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/media/ImageUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/media/ImageUtil.java deleted file mode 100644 index 806f674..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/media/ImageUtil.java +++ /dev/null @@ -1,469 +0,0 @@ -package com.dhc.library.utils.media; - -import android.content.Context; -import android.content.res.Resources; -import android.graphics.Bitmap; -import android.graphics.Bitmap.Config; -import android.graphics.Matrix; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; -import android.media.ExifInterface; -import android.text.TextUtils; -import android.util.Log; - -import com.dhc.library.R; -import com.dhc.library.utils.AppContext; -import com.dhc.library.utils.file.AttachmentStore; -import com.dhc.library.utils.file.FileUtil; -import com.dhc.library.utils.storage.StorageType; -import com.dhc.library.utils.storage.StorageUtil; -import com.dhc.library.utils.string.StringUtil; -import com.dhc.library.utils.sys.DensityUtils; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - - -/** - * 创建者:邓浩宸 - * 时间 :2017/5/11 11:37 - * 描述 :IM处理图片的工具类 - */ -public class ImageUtil { - public static class ImageSize { - public int width = 0; - public int height = 0; - - public ImageSize(int width, int height) { - this.width = width; - this.height = height; - } - } - - public final static float MAX_IMAGE_RATIO = 5f; - -// public static Bitmap getDefaultBitmapWhenGetFail() { -// try { -// return getBitmapImmutableCopy(AppContext.get().getResources(), R.mipmap.image_download_failed); -// } catch (Exception e) { -// e.printStackTrace(); -// return null; -// } -// } - - public static final Bitmap getBitmapImmutableCopy(Resources res, int id) { - return getBitmap(res.getDrawable(id)).copy(Config.RGB_565, false); - } - - public static final Bitmap getBitmap(Drawable dr) { - if (dr == null) { - return null; - } - - if (dr instanceof BitmapDrawable) { - return ((BitmapDrawable) dr).getBitmap(); - } - - return null; - } - - public static Bitmap rotateBitmapInNeeded(String path, Bitmap srcBitmap) { - if (TextUtils.isEmpty(path) || srcBitmap == null) { - return null; - } - - ExifInterface localExifInterface; - try { - localExifInterface = new ExifInterface(path); - int rotateInt = localExifInterface.getAttributeInt( - ExifInterface.TAG_ORIENTATION, - ExifInterface.ORIENTATION_NORMAL); - float rotate = getImageRotate(rotateInt); - if (rotate != 0) { - Matrix matrix = new Matrix(); - matrix.postRotate(rotate); - Bitmap dstBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, - srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, - false); - if (dstBitmap == null) { - return srcBitmap; - } else { - if (srcBitmap != null && !srcBitmap.isRecycled()) { - srcBitmap.recycle(); - } - return dstBitmap; - } - } else { - return srcBitmap; - } - } catch (IOException e) { - e.printStackTrace(); - return srcBitmap; - } - } - - /** - * 获得旋转角度 - * - * @param rotate - * @return - */ - public static float getImageRotate(int rotate) { - float f; - if (rotate == 6) { - f = 90.0F; - } else if (rotate == 3) { - f = 180.0F; - } else if (rotate == 8) { - f = 270.0F; - } else { - f = 0.0F; - } - - return f; - } - - public static String makeThumbnail(Context context, File imageFile) { - String thumbFilePath = StorageUtil.getWritePath(imageFile.getName(), - StorageType.TYPE_THUMB_IMAGE); - File thumbFile = AttachmentStore.create(thumbFilePath); - if (thumbFile == null) { - return null; - } - - boolean result = scaleThumbnail( - imageFile, - thumbFile, - DensityUtils.getImageMaxEdge(), - DensityUtils.getImageMinEdge(), - Bitmap.CompressFormat.JPEG, - 60); - if (!result) { - AttachmentStore.delete(thumbFilePath); - return null; - } - - return thumbFilePath; - } - - public static Boolean scaleThumbnail(File srcFile, File dstFile, int dstMaxWH, int dstMinWH, Bitmap.CompressFormat compressFormat, int quality) { - Boolean bRet = false; - Bitmap srcBitmap = null; - Bitmap dstBitmap = null; - BufferedOutputStream bos = null; - - try { - int[] bound = BitmapDecoder.decodeBound(srcFile); - ImageSize size = getThumbnailDisplaySize(bound[0], bound[1], dstMaxWH, dstMinWH); - srcBitmap = BitmapDecoder.decodeSampled(srcFile.getPath(), size.width, size.height); - - // 旋转 - ExifInterface localExifInterface = new ExifInterface(srcFile.getAbsolutePath()); - int rotateInt = localExifInterface.getAttributeInt( - ExifInterface.TAG_ORIENTATION, - ExifInterface.ORIENTATION_NORMAL); - float rotate = getImageRotate(rotateInt); - - Matrix matrix = new Matrix(); - matrix.postRotate(rotate); - - float inSampleSize = 1; - - if (srcBitmap.getWidth() >= dstMinWH && srcBitmap.getHeight() <= dstMaxWH - && srcBitmap.getWidth() >= dstMinWH && srcBitmap.getHeight() <= dstMaxWH) { - //如果第一轮拿到的srcBitmap尺寸都符合要求,不需要再做缩放 - } else { - if (srcBitmap.getWidth() != size.width || srcBitmap.getHeight() != size.height) { - float widthScale = (float) size.width / (float) srcBitmap.getWidth(); - float heightScale = (float) size.height / (float) srcBitmap.getHeight(); - - if (widthScale >= heightScale) { - size.width = srcBitmap.getWidth(); - size.height /= widthScale;//必定小于srcBitmap.getHeight() - inSampleSize = widthScale; - } else { - size.width /= heightScale;//必定小于srcBitmap.getWidth() - size.height = srcBitmap.getHeight(); - inSampleSize = heightScale; - } - } - } - - matrix.postScale(inSampleSize, inSampleSize); - - if (rotate == 0 && inSampleSize == 1) { - dstBitmap = srcBitmap; - } else { - dstBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, size.width, size.height, matrix, true); - } - - bos = new BufferedOutputStream(new FileOutputStream(dstFile)); - dstBitmap.compress(compressFormat, quality, bos); - bos.flush(); - bRet = true; - } catch (OutOfMemoryError e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (bos != null) { - try { - bos.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - if (srcBitmap != null && !srcBitmap.isRecycled()) { - srcBitmap.recycle(); - srcBitmap = null; - } - - if (dstBitmap != null && !dstBitmap.isRecycled()) { - dstBitmap.recycle(); - dstBitmap = null; - } - } - return bRet; - } - - public static ImageSize getThumbnailDisplaySize(float srcWidth, float srcHeight, float dstMaxWH, float dstMinWH) { - if (srcWidth <= 0 || srcHeight <= 0) { // bounds check - return new ImageSize((int) dstMinWH, (int) dstMinWH); - } - - float shorter; - float longer; - boolean widthIsShorter; - - //store - if (srcHeight < srcWidth) { - shorter = srcHeight; - longer = srcWidth; - widthIsShorter = false; - } else { - shorter = srcWidth; - longer = srcHeight; - widthIsShorter = true; - } - - if (shorter < dstMinWH) { - float scale = dstMinWH / shorter; - shorter = dstMinWH; - if (longer * scale > dstMaxWH) { - longer = dstMaxWH; - } else { - longer *= scale; - } - } else if (longer > dstMaxWH) { - float scale = dstMaxWH / longer; - longer = dstMaxWH; - if (shorter * scale < dstMinWH) { - shorter = dstMinWH; - } else { - shorter *= scale; - } - } - - //restore - if (widthIsShorter) { - srcWidth = shorter; - srcHeight = longer; - } else { - srcWidth = longer; - srcHeight = shorter; - } - - return new ImageSize((int) srcWidth, (int) srcHeight); - } - - public static File getScaledImageFileWithMD5(File imageFile, String mimeType) { - String filePath = imageFile.getPath(); - - if (!isInvalidPictureFile(mimeType)) { - Log.i("ImageUtil", "is invalid picture file"); - return null; - } - - String tempFilePath = getTempFilePath(FileUtil.getExtensionName(filePath)); - File tempImageFile = AttachmentStore.create(tempFilePath); - if (tempImageFile == null) { - return null; - } - - Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.JPEG; - // 压缩数值由第三方开发者自行决定 - int maxWidth = 720; - int quality = 60; - - if (ImageUtil.scaleImage(imageFile, tempImageFile, maxWidth, compressFormat, quality)) { - return tempImageFile; - } else { - return null; - } - } - - private static String getTempFilePath(String extension) { - return StorageUtil.getWritePath( - AppContext.get(), - "temp_image_" + StringUtil.get36UUID() + "." + extension, - StorageType.TYPE_TEMP); - } - - public static Boolean scaleImage(File srcFile, File dstFile, int dstMaxWH, Bitmap.CompressFormat compressFormat, int quality) { - Boolean success = false; - - try { - int inSampleSize = SampleSizeUtil.calculateSampleSize(srcFile.getAbsolutePath(), dstMaxWH * dstMaxWH); - Bitmap srcBitmap = BitmapDecoder.decodeSampled(srcFile.getPath(), inSampleSize); - if (srcBitmap == null) { - return success; - } - - // 旋转 - ExifInterface localExifInterface = new ExifInterface(srcFile.getAbsolutePath()); - int rotateInt = localExifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); - float rotate = getImageRotate(rotateInt); - - Bitmap dstBitmap; - float scale = (float) Math.sqrt(((float) dstMaxWH * (float) dstMaxWH) / ((float) srcBitmap.getWidth() * (float) srcBitmap.getHeight())); - if (rotate == 0f && scale >= 1) { - dstBitmap = srcBitmap; - } else { - try { - Matrix matrix = new Matrix(); - if (rotate != 0) { - matrix.postRotate(rotate); - } - if (scale < 1) { - matrix.postScale(scale, scale); - } - dstBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true); - } catch (OutOfMemoryError e) { - BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dstFile)); - srcBitmap.compress(compressFormat, quality, bos); - bos.flush(); - bos.close(); - success = true; - - if (!srcBitmap.isRecycled()) - srcBitmap.recycle(); - srcBitmap = null; - - return success; - } - } - - BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dstFile)); - dstBitmap.compress(compressFormat, quality, bos); - bos.flush(); - bos.close(); - success = true; - - if (!srcBitmap.isRecycled()) - srcBitmap.recycle(); - srcBitmap = null; - - if (!dstBitmap.isRecycled()) - dstBitmap.recycle(); - dstBitmap = null; - } catch (Exception e) { - e.printStackTrace(); - } catch (OutOfMemoryError e) { - e.printStackTrace(); - } - return success; - } - - public static ImageSize getThumbnailDisplaySize(int maxSide, int minSide, String imagePath) { - int[] bound = BitmapDecoder.decodeBound(imagePath); - ImageSize imageSize = getThumbnailDisplaySize(bound[0], bound[1], maxSide, minSide); - return imageSize; - } - - public static int[] getBoundWithLength(int maxSide, Object imageObject, boolean resizeToDefault) { - int width = -1; - int height = -1; - - int[] bound; - if (String.class.isInstance(imageObject)) { - bound = BitmapDecoder.decodeBound((String) imageObject); - width = bound[0]; - height = bound[1]; - } else if (Integer.class.isInstance(imageObject)) { - bound = BitmapDecoder.decodeBound(AppContext.get().getResources(), (Integer) imageObject); - width = bound[0]; - height = bound[1]; - } else if (InputStream.class.isInstance(imageObject)) { - bound = BitmapDecoder.decodeBound((InputStream) imageObject); - width = bound[0]; - height = bound[1]; - } - - int defaultWidth = maxSide; - int defaultHeight = maxSide; - if (width <= 0 || height <= 0) { - width = defaultWidth; - height = defaultHeight; - } else if (resizeToDefault) { - if (width > height) { - height = (int) (defaultWidth * ((float) height / (float) width)); - width = defaultWidth; - } else { - width = (int) (defaultHeight * ((float) width / (float) height)); - height = defaultHeight; - } - } - - return new int[]{width, height}; - } - - /** - * 下载失败与获取失败时都统一显示默认下载失败图片 - * - * @return - */ - public static Bitmap getBitmapFromDrawableRes(int res) { - try { - return getBitmapImmutableCopy(AppContext.get().getResources(), res); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public static boolean isInvalidPictureFile(String mimeType) { - String lowerCaseFilepath = mimeType.toLowerCase(); - return (lowerCaseFilepath.contains("jpg") || lowerCaseFilepath.contains("jpeg") - || lowerCaseFilepath.toLowerCase().contains("png") || lowerCaseFilepath.toLowerCase().contains("bmp") || lowerCaseFilepath - .toLowerCase().contains("gif")); - } - - public static int getImageOrientation(String mPaths) { - int orientation = 0; - try { - ExifInterface ei = new ExifInterface(mPaths); - int exif = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); - switch (exif) { - case ExifInterface.ORIENTATION_ROTATE_90: - orientation = 90; - break; - case ExifInterface.ORIENTATION_ROTATE_180: - orientation = 180; - break; - case ExifInterface.ORIENTATION_ROTATE_270: - orientation = 270; - break; - } - } catch (Exception e) { - } - return orientation; - } - - - - -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/media/SampleSizeUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/media/SampleSizeUtil.java deleted file mode 100644 index 57c0a73..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/media/SampleSizeUtil.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.dhc.library.utils.media; - -import android.opengl.GLES10; -/** - * 创建者:邓浩宸 - * 时间 :2017/5/11 11:37 - * 描述 :IM计算图片size和采样率 - */ -public class SampleSizeUtil { - - public static int calculateSampleSize(String imagePath, int totalPixel) { - int[] bound = BitmapDecoder.decodeBound(imagePath); - return calculateSampleSize(bound[0], bound[1], totalPixel); - } - - public static int calculateSampleSize(int width, int height, int totalPixel) { - int ratio = 1; - - if (width > 0 && height > 0) { - ratio = (int) Math.sqrt((float) (width * height) / totalPixel); - if (ratio < 1) { - ratio = 1; - } - } - - return ratio; - } - - /** - * Calculate an inSampleSize for use in a {@link android.graphics.BitmapFactory.Options} - * object when decoding bitmaps using the decode* methods from - * {@link android.graphics.BitmapFactory}. This implementation calculates the closest - * inSampleSize that will result in the final decoded bitmap having a width - * and height equal to or larger than the requested width and height. This - * implementation does not ensure a power of 2 is returned for inSampleSize - * which can be faster when decoding but results in a larger bitmap which - * isn't as useful for caching purposes. - * - * @param width - * @param height - * @param reqWidth - * @param reqHeight - * @return - */ - public static int calculateSampleSize(int width, int height, int reqWidth, int reqHeight) { - // can't proceed - if (width <= 0 || height <= 0) { - return 1; - } - // can't proceed - if (reqWidth <= 0 && reqHeight <= 0) { - return 1; - } else if (reqWidth <= 0) { - reqWidth = (int) (width * reqHeight / (float)height + 0.5f) ; - } else if (reqHeight <= 0) { - reqHeight = (int) (height * reqWidth / (float)width + 0.5f); - } - - int inSampleSize = 1; - - if (height > reqHeight || width > reqWidth) { - // Calculate ratios of height and width to requested height and width - final int heightRatio = Math.round((float) height / (float) reqHeight); - final int widthRatio = Math.round((float) width / (float) reqWidth); - - // Choose the smallest ratio as inSampleSize value, this will - // guarantee a final image - // with both dimensions larger than or equal to the requested height and width. - inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; - if (inSampleSize == 0) { - inSampleSize = 1; - } - - // This offers some additional logic in case the image has a strange - // aspect ratio. For example, a panorama may have a much larger - // width than height. In these cases the total pixels might still - // end up being too large to fit comfortably in memory, so we should - // be more aggressive with sample down the image (=larger - // inSampleSize). - - final float totalPixels = width * height; - - // Anything more than 2x the requested pixels we'll sample down - // further - final float totalReqPixelsCap = reqWidth * reqHeight * 2; - - while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) { - inSampleSize++; - } - } - - return inSampleSize; - } - - public static final int adjustSampleSizeWithTexture(int sampleSize, int width, int height) { - int textureSize = getTextureSize(); - - if ((textureSize > 0) && ((width > sampleSize) || (height > sampleSize))) { - while ((width / (float)sampleSize) > textureSize || (height / (float)sampleSize) > textureSize) { - sampleSize++; - } - - // 2的指数对齐 - sampleSize = SampleSizeUtil.roundup2n(sampleSize); - } - - return sampleSize; - } - - private static int textureSize = 0; - //存在第二次拿拿不到的情况,所以把拿到的数据用一个static变量保存下来 - public static final int getTextureSize() { - if (textureSize > 0) { - return textureSize; - } - - int[] params = new int[1]; - GLES10.glGetIntegerv(GLES10.GL_MAX_TEXTURE_SIZE, params, 0); - textureSize = params[0]; - - return textureSize; - } - - // 将x向上对齐到2的幂指数 - private static final int roundup2n(int x) { - if ((x & (x - 1)) == 0) { - return x; - } - int pos = 0; - while (x > 0) { - x >>= 1; - ++pos; - } - return 1 << pos; - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/rx/BaseSubscriberListener.java b/baselib/library/src/main/java/com/dhc/library/utils/rx/BaseSubscriberListener.java deleted file mode 100644 index 50a35d1..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/rx/BaseSubscriberListener.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.dhc.library.utils.rx; - -import com.dhc.library.R; -import com.dhc.library.data.net.NetError; -import com.dhc.library.data.net.SubscriberListener; -import com.dhc.library.utils.AppContext; -import com.dhc.library.data.account.AccountManager; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSyntaxException; - -import org.json.JSONException; - -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; - -import retrofit2.HttpException; - - - -/** - * 创建者 邓浩宸 - * 创建时间 2017/3/16 13:51 - * 描述 ${请求统一处理} - */ -public abstract class BaseSubscriberListener extends SubscriberListener { - //对应HTTP的状态码 - private static final int ERROR = 400; - private static final int UNAUTHORIZED = 401;//没有权限 - private static final int FORBIDDEN = 403;//没有权限 - private static final int NOT_FOUND = 404;// - private static final int INTERNAL_SERVER_ERROR = 500;//服务器错误 - private static final int BAD_GATEWAY = 502; - private static final int SERVICE_UNAVAILABLE = 503; - private static final int GATEWAY_TIMEOUT = 504; - - - public void onFail(NetError errorMsg) { - - } - - - @Override - public void onError(Throwable e) { - NetError error = null; - if (e != null) { - if (!(e instanceof NetError)) { - if (e instanceof UnknownHostException) { - error = new NetError(e, NetError.NoConnectError); - } else if (e instanceof JSONException - || e instanceof JsonParseException - || e instanceof JsonSyntaxException) { - error = new NetError(e, NetError.ParseError); - } else if (e instanceof SocketException - || e instanceof SocketTimeoutException) { - error = new NetError(e, NetError.SocketError); - } else if (e instanceof HttpException) { - HttpException httpException = (HttpException) e; - if (httpException.code() == UNAUTHORIZED) {//去认证 - checkReLogin("401", "checkout"); - } - error = new NetError(e, NetError.NetError); - } else { - error = new NetError(e, NetError.OtherError); - } - } else { - error = (NetError) e; - } - onFail(error); - } - - } - - @Override - public void checkReLogin(String errorCode, String errorMsg) { - AccountManager.INSTANCE.logout(); -// RxBus.getDefault().post(new Events(GO_LOGIN, AppContext.get().getString(R.string.GO_LOGIN))); - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/rx/RxUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/rx/RxUtil.java deleted file mode 100644 index 45141d0..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/rx/RxUtil.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.dhc.library.utils.rx; - - -import com.dhc.library.data.net.ApiResponse; -import com.dhc.library.data.net.RetryWhenHandler; - -import io.reactivex.Flowable; -import io.reactivex.FlowableTransformer; -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.functions.Function; -import io.reactivex.schedulers.Schedulers; - -/** - * 创建者:邓浩宸 - * 时间 :2016/11/15 16:01 - * 描述 :Rxjava使用的工具类 - */ -public class RxUtil { - - /** - * 统一线程处理 - * - * @param - * @return - */ - public static FlowableTransformer rxSchedulerHelper() { //compose简化线程 - return rxSchedulerHelper(3,3); - } - - - /** - * 统一线程处理和失败重连 - * @param count 失败重连次数 - * @param delay 延迟时间 - * @param 返回数据data实际的 数据 - * @return 返回数据data实际的 数据 - */ - public static FlowableTransformer rxSchedulerHelper(final int count, final long delay) { //compose简化线程 - return new FlowableTransformer() { - @Override - public Flowable apply(Flowable upstream) { - return upstream.subscribeOn(Schedulers.io()) - .flatMap(new Function>() { - @Override - public Flowable apply(T t) throws Exception { - -// if (t != null && "40108".equals(t.getCode())) { -// SPHelper.put(AppContext.get(), "access_token", t.getMessage()); -// throw new NullPointerException("token_is_need_refresh"); -// } else { -// return Flowable.just(t); -// } - - // TODO: 2017/8/22 根据实际情况去处理 - return Flowable.just(t); - } - }) - .retryWhen(new RetryWhenHandler(count, delay)) - .observeOn(AndroidSchedulers.mainThread()); - } - }; - } - - - // /** - // * 统一返回结果处理 - // * @param - // * @return - // */ - // public static Observable.Transformer, T> handleMyResult() { //compose判断结果 - // return new Observable.Transformer, T>() { - // @Override - // public Observable call(Observable> httpResponseObservable) { - // return httpResponseObservable.flatMap(new Func1, Observable>() { - // @Override - // public Observable call(MyHttpResponse tMyHttpResponse) { - // if(tMyHttpResponse.getCode() == 200) { - // return createData(tMyHttpResponse.getData()); - // } else { - // return Observable.error(new ApiException("服务器返回error")); - // } - // } - // }); - // } - // }; - // } - -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/storage/ExternalStorage.java b/baselib/library/src/main/java/com/dhc/library/utils/storage/ExternalStorage.java deleted file mode 100644 index 894e894..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/storage/ExternalStorage.java +++ /dev/null @@ -1,194 +0,0 @@ -package com.dhc.library.utils.storage; - -import android.content.Context; -import android.os.Environment; -import android.os.StatFs; -import android.text.TextUtils; - -import java.io.File; -import java.io.IOException; - -/** package */ -class ExternalStorage { - /** - * 外部存储根目录 - */ - private String sdkStorageRoot = null; - - private static ExternalStorage instance; - - private ExternalStorage() { - - } - - synchronized public static ExternalStorage getInstance() { - if (instance == null) { - instance = new ExternalStorage(); - } - return instance; - } - - public void init(Context context, String sdkStorageRoot) { - if (!TextUtils.isEmpty(sdkStorageRoot)) { - File dir = new File(sdkStorageRoot); - if (!dir.exists()) { - dir.mkdirs(); - } - if (dir.exists() && !dir.isFile()) { - this.sdkStorageRoot = sdkStorageRoot; - if (!sdkStorageRoot.endsWith("/")) { - this.sdkStorageRoot = sdkStorageRoot + "/"; - } - } - } - - if (TextUtils.isEmpty(this.sdkStorageRoot)) { - loadStorageState(context); - } - - createSubFolders(); - } - - private void loadStorageState(Context context) { - String externalPath = Environment.getExternalStorageDirectory().getPath(); - this.sdkStorageRoot = externalPath + "/" + context.getPackageName() + "/"; - } - - private void createSubFolders() { - boolean result = true; - File root = new File(sdkStorageRoot); - if (root.exists() && !root.isDirectory()) { - root.delete(); - } - for (StorageType storageType : StorageType.values()) { - result &= makeDirectory(sdkStorageRoot + storageType.getStoragePath()); - } - if (result) { - createNoMediaFile(sdkStorageRoot); - } - } - - /** - * 创建目录 - * - * @param path - * @return - */ - private boolean makeDirectory(String path) { - File file = new File(path); - boolean exist = file.exists(); - if (!exist) { - exist = file.mkdirs(); - } - return exist; - } - - protected static String NO_MEDIA_FILE_NAME = ".nomedia"; - - private void createNoMediaFile(String path) { - File noMediaFile = new File(path + "/" + NO_MEDIA_FILE_NAME); - try { - if (!noMediaFile.exists()) { - noMediaFile.createNewFile(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * 文件全名转绝对路径(写) - * - * @param fileName - * 文件全名(文件名.扩展名) - * @return 返回绝对路径信息 - */ - public String getWritePath(String fileName, StorageType fileType) { - return pathForName(fileName, fileType, false, false); - } - - private String pathForName(String fileName, StorageType type, boolean dir, - boolean check) { - String directory = getDirectoryByDirType(type); - StringBuilder path = new StringBuilder(directory); - - if (!dir) { - path.append(fileName); - } - - String pathString = path.toString(); - File file = new File(pathString); - - if (check) { - if (file.exists()) { - if ((dir && file.isDirectory()) - || (!dir && !file.isDirectory())) { - return pathString; - } - } - - return ""; - } else { - return pathString; - } - } - - /** - * 返回指定类型的文件夹路径 - * - * @param fileType - * @return - */ - public String getDirectoryByDirType(StorageType fileType) { - return sdkStorageRoot + fileType.getStoragePath(); - } - - /** - * 根据输入的文件名和类型,找到该文件的全路径。 - * @param fileName - * @param fileType - * @return 如果存在该文件,返回路径,否则返回空 - */ - public String getReadPath(String fileName, StorageType fileType) { - if (TextUtils.isEmpty(fileName)) { - return ""; - } - - return pathForName(fileName, fileType, false, true); - } - - public boolean isSdkStorageReady() { - String externalRoot = Environment.getExternalStorageDirectory().getAbsolutePath(); - if (this.sdkStorageRoot.startsWith(externalRoot)) { - return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); - } else { - return true; - } - } - - /** - * 获取外置存储卡剩余空间 - * @return - */ - public long getAvailableExternalSize() { - return getResidualSpace(sdkStorageRoot); - } - - /** - * 获取目录剩余空间 - * @param directoryPath - * @return - */ - private long getResidualSpace(String directoryPath) { - try { - StatFs sf = new StatFs(directoryPath); - long blockSize = sf.getBlockSize(); - long availCount = sf.getAvailableBlocks(); - long availCountByte = availCount * blockSize; - return availCountByte; - } catch (Exception e) { - e.printStackTrace(); - } - return 0; - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/storage/StorageType.java b/baselib/library/src/main/java/com/dhc/library/utils/storage/StorageType.java deleted file mode 100644 index 6be11b3..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/storage/StorageType.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.dhc.library.utils.storage; - -public enum StorageType { - TYPE_LOG(DirectoryName.LOG_DIRECTORY_NAME), - TYPE_TEMP(DirectoryName.TEMP_DIRECTORY_NAME), - TYPE_FILE(DirectoryName.FILE_DIRECTORY_NAME), - TYPE_AUDIO(DirectoryName.AUDIO_DIRECTORY_NAME), - TYPE_IMAGE(DirectoryName.IMAGE_DIRECTORY_NAME), - TYPE_VIDEO(DirectoryName.VIDEO_DIRECTORY_NAME), - TYPE_THUMB_IMAGE(DirectoryName.THUMB_DIRECTORY_NAME), - TYPE_THUMB_VIDEO(DirectoryName.THUMB_DIRECTORY_NAME), - ; - private DirectoryName storageDirectoryName; - private long storageMinSize; - - public String getStoragePath() { - return storageDirectoryName.getPath(); - } - - public long getStorageMinSize() { - return storageMinSize; - } - - StorageType(DirectoryName dirName) { - this(dirName, StorageUtil.THRESHOLD_MIN_SPCAE); - } - - StorageType(DirectoryName dirName, long storageMinSize) { - this.storageDirectoryName = dirName; - this.storageMinSize = storageMinSize; - } - - enum DirectoryName { - AUDIO_DIRECTORY_NAME("audio/"), - DATA_DIRECTORY_NAME("data/"), - FILE_DIRECTORY_NAME("file/"), - LOG_DIRECTORY_NAME("log/"), - TEMP_DIRECTORY_NAME("temp/"), - IMAGE_DIRECTORY_NAME("image/"), - THUMB_DIRECTORY_NAME("thumb/"), - VIDEO_DIRECTORY_NAME("video/"), - ; - - private String path; - - public String getPath() { - return path; - } - - private DirectoryName(String path) { - this.path = path; - } - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/storage/StorageUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/storage/StorageUtil.java deleted file mode 100644 index 5d8a3fe..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/storage/StorageUtil.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.dhc.library.utils.storage; - -import android.content.Context; -import android.os.Build; -import android.os.Environment; -import android.text.TextUtils; - -import java.io.File; - -public class StorageUtil { - public final static long K = 1024; - public final static long M = 1024 * 1024; - // 外置存储卡默认预警临界值 - private static final long THRESHOLD_WARNING_SPACE = 100 * M; - // 保存文件时所需的最小空间的默认值 - public static final long THRESHOLD_MIN_SPCAE = 20 * M; - - public static void init(Context context, String rootPath) { - ExternalStorage.getInstance().init(context, rootPath); - } - - /** - * 获取文件保存路径,没有toast提示 - * - * @param fileName - * @param fileType - * @return 可用的保存路径或者null - */ - public static String getWritePath(String fileName, StorageType fileType) { - return getWritePath(null, fileName, fileType, false); - } - - /** - * 获取文件保存路径 - * - * @param fileName - * 文件全名 - * @param tip - * 空间不足时是否给出默认的toast提示 - * @return 可用的保存路径或者null - */ - private static String getWritePath(Context context, String fileName, StorageType fileType, boolean tip) { - String path = ExternalStorage.getInstance().getWritePath(fileName, fileType); - if (TextUtils.isEmpty(path)) { - return null; - } - File dir = new File(path).getParentFile(); - if (dir != null && !dir.exists()) { - dir.mkdirs(); - } - return path; - } - - /** - * 判断能否使用外置存储 - */ - public static boolean isExternalStorageExist() { - return ExternalStorage.getInstance().isSdkStorageReady(); - } - - - /** - * 判断外部存储是否存在,以及是否有足够空间保存指定类型的文件 - * - * @param context - * @param fileType - * @param tip 是否需要toast提示 - * @return false: 无存储卡或无空间可写, true: 表示ok - */ - public static boolean hasEnoughSpaceForWrite(Context context, StorageType fileType, boolean tip) { - if (!ExternalStorage.getInstance().isSdkStorageReady()) { - return false; - } - - long residual = ExternalStorage.getInstance().getAvailableExternalSize(); - if (residual < fileType.getStorageMinSize()) { - return false; - } else if (residual < THRESHOLD_WARNING_SPACE) { - } - - return true; - } - /** - * 根据输入的文件名和类型,找到该文件的全路径。 - * - * @param fileName - * @param fileType - * @return 如果存在该文件,返回路径,否则返回空 - */ - public static String getReadPath(String fileName, StorageType fileType) { - return ExternalStorage.getInstance().getReadPath(fileName, fileType); - } - - /** - * 获取文件保存路径,空间不足时有toast提示 - * - * @param context - * @param fileName - * @param fileType - * @return 可用的保存路径或者null - */ - public static String getWritePath(Context context, String fileName, StorageType fileType) { - return getWritePath(context, fileName, fileType, true); - } - - public static String getDirectoryByDirType(StorageType fileType) { - return ExternalStorage.getInstance().getDirectoryByDirType(fileType); - } - - public static String getSystemImagePath() { - if (Build.VERSION.SDK_INT > 7) { - String picturePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath(); - return picturePath + "/nim/"; - } else { - String picturePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath(); - return picturePath + "/nim/"; - } - } - - public static boolean isInvalidVideoFile(String filePath) { - return filePath.toLowerCase().endsWith(".3gp") - || filePath.toLowerCase().endsWith(".mp4"); - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/string/Base64Utils.java b/baselib/library/src/main/java/com/dhc/library/utils/string/Base64Utils.java deleted file mode 100644 index e69de29..0000000 diff --git a/baselib/library/src/main/java/com/dhc/library/utils/string/HexDump.java b/baselib/library/src/main/java/com/dhc/library/utils/string/HexDump.java deleted file mode 100644 index 28d12ea..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/string/HexDump.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.dhc.library.utils.string; - -import java.io.IOException; -import java.io.StringReader; - -public class HexDump { - class HexTablifier { - private int m_row = 8; - - private String m_pre = ""; - - private String m_post = "\n"; - - public HexTablifier() { - } - - public HexTablifier(int row) { - this(row, "", "\n"); - } - - public HexTablifier(int row, String pre) { - this(row, pre, "\n"); - } - - public HexTablifier(int row, String pre, String post) { - m_row = row; - m_pre = pre; - m_post = post; - } - - public String format(String hex) { - StringReader reader = new StringReader(hex); - StringBuilder builder = new StringBuilder(hex.length() * 2); - - try { - while (getHexLine(builder, reader)) { - } - } catch (IOException e) { - // 不应该有异常出现。 - } - - return builder.toString(); - } - - private boolean getHexLine(StringBuilder builder, StringReader reader) - throws IOException { - StringBuilder lineBuilder = new StringBuilder(); - boolean result = true; - - for (int i = 0; i < m_row; i++) { - result = getHexByte(lineBuilder, reader); - - if (result == false) - break; - } - - if (lineBuilder.length() > 0) { - builder.append(m_pre); - builder.append(lineBuilder); - builder.append(m_post); - } - - return result; - } - - private boolean getHexByte(StringBuilder builder, StringReader reader) - throws IOException { - char[] hexByte = new char[4]; - int bytesRead = reader.read(hexByte); - - if (bytesRead == -1) - return false; - - builder.append(hexByte, 0, bytesRead); - builder.append(" "); - - return bytesRead == 4; - } - } - - private static final char m_hexCodes[] = { '0', '1', '2', '3', '4', '5', - '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - - private static final int m_shifts[] = { 60, 56, 52, 48, 44, 40, 36, 32, 28, - 24, 20, 16, 12, 8, 4, 0 }; - - public static String tablify(byte[] bytes) { - return (new HexDump()).new HexTablifier().format(HexDump.toHex(bytes)); - } - - public static String tablify(byte[] bytes, int row) { - return (new HexDump()).new HexTablifier(row).format(HexDump - .toHex(bytes)); - } - - public static String tablify(byte[] bytes, int row, String pre) { - return (new HexDump()).new HexTablifier(row, pre).format(HexDump - .toHex(bytes)); - } - - public static String tablify(String hex, int row, String pre, String post) { - return (new HexDump()).new HexTablifier(row, pre, post).format(hex); - } - - private static String toHex(final long value, final int digitNum) { - StringBuilder result = new StringBuilder(digitNum); - - for (int j = 0; j < digitNum; j++) { - int index = (int) ((value >> m_shifts[j + (16 - digitNum)]) & 15); - result.append(m_hexCodes[index]); - } - - return result.toString(); - } - - public static String toHex(final byte value) { - return toHex(value, 2); - } - - public static String toHex(final short value) { - return toHex(value, 4); - } - - public static String toHex(final int value) { - return toHex(value, 8); - } - - public static String toHex(final long value) { - return toHex(value, 16); - } - - public static String toHex(final byte[] value) { - return toHex(value, 0, value.length); - } - - public static String toHex(final byte[] value, final int offset, - final int length) { - StringBuilder retVal = new StringBuilder(); - - int end = offset + length; - for (int x = offset; x < end; x++) - retVal.append(toHex(value[x])); - - return retVal.toString(); - } - - public static byte[] restoreBytes(String hex) { - byte[] bytes = new byte[hex.length() / 2]; - for (int i = 0; i < bytes.length; ++i) { - int c1 = charToNumber(hex.charAt(2 * i)); - int c2 = charToNumber(hex.charAt(2 * i + 1)); - if (c1 == -1 || c2 == -1) { - return null; - } - bytes[i] = (byte) ((c1 << 4) + c2); - } - - return bytes; - } - - private static int charToNumber(char c) { - if (c >= '0' && c <= '9') { - return c - '0'; - } else if (c >= 'a' && c <= 'f') { - return c - 'a' + 0xa; - } else if (c >= 'A' && c <= 'F') { - return c - 'A' + 0xA; - } else { - return -1; - } - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/string/MD5.java b/baselib/library/src/main/java/com/dhc/library/utils/string/MD5.java deleted file mode 100644 index 54e06f7..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/string/MD5.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.dhc.library.utils.string; - -import java.io.BufferedInputStream; -import java.io.FileInputStream; -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; - -public class MD5 { - - public static String getStringMD5(String value) { - if (value == null || value.trim().length() < 1) { - return null; - } - try { - return getMD5(value.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - public static String getMD5(byte[] source) { - try { - MessageDigest md5 = MessageDigest.getInstance("MD5"); - return HexDump.toHex(md5.digest(source)); - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - public static String getStreamMD5(String filePath) { - String hash=null; - byte[] buffer = new byte[4096]; - BufferedInputStream in=null; - try - { - MessageDigest md5 = MessageDigest.getInstance("MD5"); - in = new BufferedInputStream(new FileInputStream(filePath)); - int numRead = 0; - while ((numRead = in.read(buffer)) > 0) { - md5.update(buffer, 0, numRead); - } - in.close(); - hash = HexDump.toHex(md5.digest()); - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (in != null) { - try { - in.close(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - return hash; - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/string/SHA256Util.java b/baselib/library/src/main/java/com/dhc/library/utils/string/SHA256Util.java deleted file mode 100644 index 8ccd73e..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/string/SHA256Util.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.dhc.library.utils.string; - -import android.support.annotation.StringDef; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -/** - * 创建者 邓浩宸 - * 创建时间 2016/11/25 14:30 - * 描述 ${生成SHA256值} - */ -public class SHA256Util { - - public static final String MD5="MD5"; - public static final String SHA_1="SHA-1"; - public static final String SHA_256="SHA-256"; - public static final String SHA_384="SHA-384"; - - - public static String sign(String str, @SignTypeChecker String type){ - String s=Encrypt(str,type); - return s; - } - - public static String Encrypt(String strSrc, String encName) { - MessageDigest md = null; - String strDes = null; - byte[] bt = strSrc.getBytes(); - try { - md = MessageDigest.getInstance(encName); - md.update(bt); - strDes = bytes2Hex(md.digest()); // to HexString - } catch (NoSuchAlgorithmException e) { - return null; - } - return strDes; - } - public static String bytes2Hex(byte[] bts) { - String des = ""; - String tmp = null; - for (int i = 0; i < bts.length; i++) { - tmp = (Integer.toHexString(bts[i] & 0xFF)); - if (tmp.length() == 1) { - des += "0"; - } - des += tmp; - } - return des; - } - - - /** - * 替代枚举的方案,使用StringDef保证类型安全 - */ - @StringDef({MD5, SHA_1,SHA_256,SHA_384}) - @Retention(RetentionPolicy.SOURCE) - public @interface SignTypeChecker { - - } - -} - diff --git a/baselib/library/src/main/java/com/dhc/library/utils/string/StringUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/string/StringUtil.java deleted file mode 100644 index de92015..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/string/StringUtil.java +++ /dev/null @@ -1,483 +0,0 @@ -package com.dhc.library.utils.string; - -import android.text.TextUtils; - -import java.text.DecimalFormat; -import java.util.List; -import java.util.Locale; -import java.util.UUID; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class StringUtil { - - - public static String getPercentString(float percent) { - return String.format(Locale.US, "%d%%", (int) (percent * 100)); - } - - /** - * 删除字符串中的空白符 - * - * @param content - * @return String - */ - public static String removeBlanks(String content) { - if (content == null) { - return null; - } - StringBuilder buff = new StringBuilder(); - buff.append(content); - for (int i = buff.length() - 1; i >= 0; i--) { - if (' ' == buff.charAt(i) || ('\n' == buff.charAt(i)) || ('\t' == buff.charAt(i)) - || ('\r' == buff.charAt(i))) { - buff.deleteCharAt(i); - } - } - return buff.toString(); - } - - /** - * 获取32位uuid - * - * @return - */ - public static String get32UUID() { - return UUID.randomUUID().toString().replaceAll("-", ""); - } - - public static boolean isEmpty(String input) { - return TextUtils.isEmpty(input); - } - - /** - * 生成唯一号 - * - * @return - */ - public static String get36UUID() { - UUID uuid = UUID.randomUUID(); - String uniqueId = uuid.toString(); - return uniqueId; - } - - public static String makeMd5(String source) { - return MD5.getStringMD5(source); - } - - public static final String filterUCS4(String str) { - if (TextUtils.isEmpty(str)) { - return str; - } - - if (str.codePointCount(0, str.length()) == str.length()) { - return str; - } - - StringBuilder sb = new StringBuilder(); - - int index = 0; - while (index < str.length()) { - int codePoint = str.codePointAt(index); - index += Character.charCount(codePoint); - if (Character.isSupplementaryCodePoint(codePoint)) { - continue; - } - - sb.appendCodePoint(codePoint); - } - - return sb.toString(); - } - - /** - * counter ASCII character as one, otherwise two - * - * @param str - * @return count - */ - public static int counterChars(String str) { - // return - if (TextUtils.isEmpty(str)) { - return 0; - } - int count = 0; - for (int i = 0; i < str.length(); i++) { - int tmp = (int) str.charAt(i); - if (tmp > 0 && tmp < 127) { - count += 1; - } else { - count += 2; - } - } - return count; - } - - /** - * 是否符合邮箱格式 - * - * @param src 源字符串 - * @return 是否符合邮箱格式 - */ - public static boolean isEmail(String src) { - Pattern pattern = Pattern.compile("\\w+@(\\w+\\.){1,3}\\w+"); - return pattern.matcher(src).find(); - } - - /** - * 是否包含特殊字符(除字母、数字外的字符为特殊字符) - * - * @param str 源字符串 - * @return 是否包含特殊字符 - */ - public static boolean hasSpecialLetter(String str) { - Pattern pattern = Pattern.compile("[^a-zA-Z0-9]"); - Matcher mat = pattern.matcher(str); - return !mat.find(); - } - - /** - * 是否是手机号码,只做1开头和位数判断 - * - * @param src 源字符串 - * @return 是否是手机号码 - */ - public static boolean isPhoneNumber(String src) { - // Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$"); - // Matcher m = p.matcher(src); - Pattern p = Pattern.compile("^[1]\\d{10}$"); - Matcher m = p.matcher(src); - return m.matches(); - } - - /** - * 是否是中国移动手机号码(134 135 136 137 138 139 151 150 158 159) - * - * @param src 源字符串 - * @return 是否是中国移动手机号码 - */ - public static boolean isCmccNumber(String src) { - Pattern p = Pattern.compile("^((13[4-9])|(15[0-1])|(15[8-9]))\\d{8}$"); - Matcher m = p.matcher(src); - return m.matches(); - } - - /** - * 是否是密码 - * - * @param src 源字符串 - * @return 是否是密码 - */ - public static boolean isPassword(String src) { - Pattern p = Pattern.compile("^[A-Za-z0-9]*$"); - Matcher m = p.matcher(src); - return m.matches(); - } - - /** - * 是否是昵称和手机号 - * - * @param nickNameID - * @return - */ - public static boolean isNumberFormat(String nickNameID) { - Pattern p = Pattern.compile("^[0-9]*$"); - Matcher m = p.matcher(nickNameID); - return m.matches(); - } - - /** - * 中英文数字正则表达式(4-16位) - * - * @param str - * @return - */ - public static boolean isChineseEnglishFormat(String str) { - Pattern p = Pattern.compile("^[\\u4E00-\\u9FA5\\uF900-\\uFA2DA-Za-z0-9]+$"); - Matcher m = p.matcher(str); - str = str.replaceAll("[^\\x00-\\xff]", "**"); //匹配双字节字符 - int length = str.length(); - return m.matches() && length >= 4 && length <= 16; - } - - /** - * 截取一段字符的长度(汉、日、韩文字符长度为2),不区分中英文,如果数字不正好,则少取一个字符位 - * - * @param str 原始字符串 - * @param specialCharsLength 截取长度(汉、日、韩文字符长度为2) - * @return - */ - public static String trim(String str, int specialCharsLength) { - if (str == null || "".equals(str) || specialCharsLength < 1) { - return ""; - } - char[] chars = str.toCharArray(); - int charsLength = getCharsLength(chars, specialCharsLength); - return new String(chars, 0, charsLength); - } - - /** - * 获取一段字符的长度,输入长度中汉、日、韩文字符长度为2,输出长度中所有字符均长度为1 - * - * @param chars 一段字符 - * @param specialCharsLength 输入长度,汉、日、韩文字符长度为2 - * @return 输出长度,所有字符均长度为1 - */ - private static int getCharsLength(char[] chars, int specialCharsLength) { - int count = 0; - int normalCharsLength = 0; - for (int i = 0; i < chars.length; i++) { - int specialCharLength = getSpecialCharLength(chars[i]); - if (count <= specialCharsLength - specialCharLength) { - count += specialCharLength; - normalCharsLength++; - } else { - break; - } - } - return normalCharsLength; - } - - - /** - * 获取一段字符的长度,输入长度中汉、日、韩文字符长度为2,输出长度中所有字符均长度为1 - * - * @param str 一段字符 - * @return 输出长度,所有字符均长度为1 - */ - public static int getStringLength(String str) { - if (TextUtils.isEmpty(str)) { - return 0; - } - int normalCharsLength = 0; - char[] chars = str.toCharArray(); - for (int i = 0; i < chars.length; i++) { - normalCharsLength += getSpecialCharLength(chars[i]); - } - return normalCharsLength; - } - - /** - * 字符串截取,输入长度中汉、日、韩文字符长度为2,输出长度中所有字符均长度为1,超过长度尾部加上... - * - * @param str 一段字符 - * @param limitLength 长度限制,超出截取尾部加上... - * @return 输出长度,所有字符均长度为1 - */ - public static String subLength(String str, int limitLength) { - final int length = getStringLength(str); - String content = str; - if (length > limitLength) { - content = StringUtil.trim(str, limitLength) + "..."; - } - return content; - } - - /** - * 获取字符长度:汉、日、韩文字符长度为2,ASCII码等字符长度为1 - * - * @param c 字符 - * @return 字符长度 - */ - private static int getSpecialCharLength(char c) { - if (isAscill(c)) { - return 1; - } else { - return 2; - } - } - - /** - * 判断一个字符是Ascill字符还是其它字符(如汉,日,韩文字符) - * - * @param c, 需要判断的字符 - * @return boolean, 返回true,Ascill字符 - */ - private static boolean isAscill(char c) { - int k = 0x80; - return c / k == 0 ? true : false; - } - - /** - * 为字符串添加双引号 - * - * @param obj 字符串 - * @return 加入双引号后的完整字符串 - */ - public static String addQuotationMarks(String obj) { - return "\"" + obj + "\""; - } - - /** - * 保留1位小数 - * - * @param num - * @return - */ - public static String onlyOneFloat(double num) { - DecimalFormat decimalFormat = new DecimalFormat("0.0"); - return decimalFormat.format(num); - } - - /** - * 连接多个字符串标签 - * - * @param tags 所有字符标签 - * @param linker 标签之间的连接字符 - * @param isLastTagAppendLinker 最后一个标签末尾是否也需要追加linker - * @return 连接得到的字符串 - */ - public static String concatTags(List tags, String linker, boolean - isLastTagAppendLinker) { - if (tags != null) { - int size = tags.size(); - if (size > 0) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < size; i++) { - sb.append(tags.get(i)); - if (i != size - 1) { - sb.append(linker); - } else if (isLastTagAppendLinker) { - sb.append(linker); - } - } - return sb.toString(); - } else { - return ""; - } - } - return null; - } - - //转码 - - /** - * 将unicode转编码utf-8格式 - * - * @param theString - * @return - */ - public static String decodeUnicode(String theString) { - char aChar; - int len = theString.length(); - StringBuffer outBuffer = new StringBuffer(len); - for (int x = 0; x < len; ) { - aChar = theString.charAt(x++); - if (aChar == '\\') { - aChar = theString.charAt(x++); - if (aChar == 'u') { - // Read the xxxx - int value = 0; - for (int i = 0; i < 4; i++) { - aChar = theString.charAt(x++); - switch (aChar) { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - value = (value << 4) + aChar - '0'; - break; - case 'a': - case 'b': - case 'c': - case 'd': - case 'e': - case 'f': - value = (value << 4) + 10 + aChar - 'a'; - break; - case 'A': - case 'B': - case 'C': - case 'D': - case 'E': - case 'F': - value = (value << 4) + 10 + aChar - 'A'; - break; - default: - throw new IllegalArgumentException( - "Malformed \\uxxxx encoding."); - } - - } - outBuffer.append((char) value); - } else { - if (aChar == 't') - aChar = '\t'; - else if (aChar == 'r') - aChar = '\r'; - else if (aChar == 'n') - aChar = '\n'; - else if (aChar == 'f') - aChar = '\f'; - outBuffer.append(aChar); - } - } else - outBuffer.append(aChar); - } - return outBuffer.toString(); - } - - /** - * 半角转全角 - * @param input String. - * @return 全角字符串. - */ - public static String ToSBC(String input) { - char c[] = input.toCharArray(); - for (int i = 0; i < c.length; i++) { - if (c[i] == ' ') { - c[i] = '\u3000'; - } else if (c[i] < '\177') { - c[i] = (char) (c[i] + 65248); - - } - } - return new String(c); - } - - - /** - 转半角的函数(DBC case)

- 全角空格为12288,半角空格为32 - 其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 - * @param input 任意字符串 - * @return 半角字符串 - * - */ - public static String ToDBC(String input) { - char[] c = input.toCharArray(); - for (int i = 0; i < c.length; i++) { - if (c[i] == 12288) { - //全角空格为12288,半角空格为32 - c[i] = (char) 32; - continue; - } - if (c[i] > 65280 && c[i] < 65375) - //其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 - c[i] = (char) (c[i] - 65248); - } - return new String(c); - } - - /** - * 检验字符串只能为纯数字,正小数、正整数均可 - */ - public static boolean isNumber(String str){ - Pattern p = Pattern.compile("([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])"); - Matcher m = p.matcher(str); - return m.matches(); - } - - // 校验Tag Alias 只能是数字,英文字母和中文 - public static boolean isValidTagAndAlias(String s) { - Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_!@#$&*+=.|]+$"); - Matcher m = p.matcher(s); - return m.matches(); - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/string/UUIDGenerator.java b/baselib/library/src/main/java/com/dhc/library/utils/string/UUIDGenerator.java deleted file mode 100644 index e53ce98..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/string/UUIDGenerator.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.dhc.library.utils.string; - -import java.util.UUID; - -/** - * 创建者 邓浩宸 - * 创建时间 2016/11/25 14:43 - * 描述 ${生成UUID} - */ -public class UUIDGenerator { - - public static String getUUID() { - UUID uuid = UUID.randomUUID(); - String str = uuid.toString(); - // 去掉"-"符号 - String temp = str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24); - return str+","+temp; - } - //获得指定数量的UUID - public static String[] getUUID(int number) { - if (number < 10||number>40) { - return null; - } - String[] ss = new String[number]; - for (int i = 0; i < number; i++) { - ss[i] = getUUID(); - } - return ss; - } - -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/sys/DateUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/sys/DateUtil.java deleted file mode 100644 index d7def07..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/sys/DateUtil.java +++ /dev/null @@ -1,663 +0,0 @@ -package com.dhc.library.utils.sys; - -import android.text.TextUtils; - -import java.text.ParseException; -import java.text.ParsePosition; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; - -/** - * 创建者:zp - * 时间 :2017/3/10 0010 下午 4:07 - * 描述 :日期操作工具类. - */ - -public class DateUtil { - - /** - * 英文简写如:2016 - */ - public static String FORMAT_Y = "yyyy"; - - /** - * 英文简写如:12:01 - */ - public static String FORMAT_HM = "HH:mm"; - - /** - * 英文简写如:1-12 12:01 - */ - public static String FORMAT_MDHM = "MM-dd HH:mm"; - - /** - * 英文简写(默认)如:2016-12-01 - */ - public static String FORMAT_YMD = "yyyy-MM-dd"; - - /** - * 英文全称 如:2016-12-01 23:15 - */ - public static String FORMAT_YMDHM = "yyyy-MM-dd HH:mm"; - - /** - * 英文全称 如:2016-12-01 23:15:06 - */ - public static String FORMAT_YMDHMS = "yyyy-MM-dd HH:mm:ss"; - - /** - * 精确到毫秒的完整时间 如:yyyy-MM-dd HH:mm:ss.S - */ - public static String FORMAT_FULL = "yyyy-MM-dd HH:mm:ss.S"; - - /** - * 精确到毫秒的完整时间 如:yyyy-MM-dd HH:mm:ss.S - */ - public static String FORMAT_FULL_SN = "yyyyMMddHHmmssS"; - - /** - * 中文简写 如:2016年12月01日 - */ - public static String FORMAT_YMD_CN = "yyyy年MM月dd日"; - - /** - * 中文简写 如:2016年12月01日 12时 - */ - public static String FORMAT_YMDH_CN = "yyyy年MM月dd日 HH时"; - - /** - * 中文简写 如:2016年12月01日 12时12分 - */ - public static String FORMAT_YMDHM_CN = "yyyy年MM月dd日 HH时mm分"; - - /** - * 中文全称 如:2016年12月01日 23时15分06秒 - */ - public static String FORMAT_YMDHMS_CN = "yyyy年MM月dd日 HH时mm分ss秒"; - - /** - * 精确到毫秒的完整中文时间 - */ - public static String FORMAT_FULL_CN = "yyyy年MM月dd日 HH时mm分ss秒SSS毫秒"; - - public static Calendar calendar = null; - private static final String FORMAT = "yyyy-MM-dd HH:mm:ss"; - - - public static Date str2Date(String str) { - return str2Date(str, null); - } - - - public static Date str2Date(String str, String format) { - if (str == null || str.length() == 0) { - return null; - } - if (format == null || format.length() == 0) { - format = FORMAT; - } - Date date = null; - try { - SimpleDateFormat sdf = new SimpleDateFormat(format); - date = sdf.parse(str); - } catch (Exception e) { - e.printStackTrace(); - } - return date; - } - - - public static Calendar str2Calendar(String str) { - return str2Calendar(str, null); - } - - - public static Calendar str2Calendar(String str, String format) { - - Date date = str2Date(str, format); - if (date == null) { - return null; - } - Calendar c = Calendar.getInstance(); - c.setTime(date); - - return c; - } - - - public static String date2Str(Calendar c) {// yyyy-MM-dd HH:mm:ss - return date2Str(c, null); - } - - - public static String date2Str(Calendar c, String format) { - if (c == null) { - return null; - } - return date2Str(c.getTime(), format); - } - - - public static String date2Str(Date d) {// yyyy-MM-dd HH:mm:ss - return date2Str(d, null); - } - - - public static String date2Str(Date d, String format) {// yyyy-MM-dd HH:mm:ss - if (d == null) { - return null; - } - if (format == null || format.length() == 0) { - format = FORMAT; - } - SimpleDateFormat sdf = new SimpleDateFormat(format); - String s = sdf.format(d); - return s; - } - - - public static String getCurDateStr() { - Calendar c = Calendar.getInstance(); - c.setTime(new Date()); - return c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + - c.get(Calendar.DAY_OF_MONTH) + "-" + - c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + - ":" + c.get(Calendar.SECOND); - } - - - /** - * 获得当前日期的字符串格式 - * - * @param format 格式化的类型 - * @return 返回格式化之后的事件 - */ - public static String getCurDateStr(String format) { - Calendar c = Calendar.getInstance(); - return date2Str(c, format); - } - - - /** - * 将短时间格式字符串转换为时间 yyyy-MM-dd - * - * @param strDate - * @return - */ - public static Date strToDate(String strDate) { - SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); - ParsePosition pos = new ParsePosition(0); - Date strtodate = formatter.parse(strDate, pos); - return strtodate; - } - - /** - * @param time 当前的时间 - * @return 格式到秒 - */ - - public static String getMillon(long time) { - - return new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(time); - - } - /** - * @param time 当前的时间 - * @return 格式到秒 - */ - - public static String getMillon(long time,String format) { - return new SimpleDateFormat(format).format(time); - - } - - - /** - * @param time 当前的时间 - * @return 当前的天 - */ - public static String getDay(long time) { - - return new SimpleDateFormat("yyyy-MM-dd").format(time); - - } - - - /** - * @param time 时间 - * @return 返回一个毫秒 - */ - // 格式到毫秒 - public static String getSMillon(long time) { - - return new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS").format(time); - - } - - - /** - * 在日期上增加数个整月 - * - * @param date 日期 - * @param n 要增加的月数 - * @return 增加数个整月 - */ - public static Date addMonth(Date date, int n) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - cal.add(Calendar.MONTH, n); - return cal.getTime(); - - } - - - /** - * 在日期上增加天数 - * - * @param date 日期 - * @param n 要增加的天数 - * @return 增加之后的天数 - */ - public static Date addDay(Date date, int n) { - Calendar cal = Calendar.getInstance(); - cal.setTime(date); - cal.add(Calendar.DATE, n); - return cal.getTime(); - - } - - - /** - * 获取距现在某一小时的时刻 - * - * @param format 格式化时间的格式 - * @param h 距现在的小时 例如:h=-1为上一个小时,h=1为下一个小时 - * @return 获取距现在某一小时的时刻 - */ - public static String getNextHour(String format, int h) { - SimpleDateFormat sdf = new SimpleDateFormat(format); - Date date = new Date(); - date.setTime(date.getTime() + h * 60 * 60 * 1000); - return sdf.format(date); - - } - - - /** - * 获取时间戳 - * - * @return 获取时间戳 - */ - public static String getTimeString() { - SimpleDateFormat df = new SimpleDateFormat(FORMAT_FULL); - Calendar calendar = Calendar.getInstance(); - return df.format(calendar.getTime()); - - } - - /** - * 字符串转时间戳 - */ - public static long getTimeString(String time){ - SimpleDateFormat df = new SimpleDateFormat(FORMAT_YMD); - try { - return df.parse(time).getTime(); - } catch (ParseException e) { - e.printStackTrace(); - } - return 0; - } - - /** - * 功能描述:返回年 - * - * @param date Date 日期 - * @return 返回年数 - */ - public static int getYear(Date date) { - calendar = Calendar.getInstance(); - calendar.setTime(date); - return calendar.get(Calendar.YEAR); - } - - /** - * 功能描述:返回月 - * - * @param date Date 日期 - * @return 返回月份 - */ - public static int getMonth(Date date) { - calendar = Calendar.getInstance(); - calendar.setTime(date); - return calendar.get(Calendar.MONTH) + 1; - } - - - /** - * 功能描述:返回日 - * - * @param date Date 日期 - * @return 返回日份 - */ - public static int getDay(Date date) { - calendar = Calendar.getInstance(); - calendar.setTime(date); - return calendar.get(Calendar.DAY_OF_MONTH); - } - - - /** - * 功能描述:返回小 - * - * @param date 日期 - * @return 返回小时 - */ - public static int getHour(Date date) { - calendar = Calendar.getInstance(); - calendar.setTime(date); - return calendar.get(Calendar.HOUR_OF_DAY); - } - - - public static String getFormatYear(String data) { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); - try { - Date date = df.parse(data); - return df.format(date); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 功能描述:返回分 - * - * @param date 日期 - * @return 返回分钟 - */ - - public static int getMinute(Date date) { - calendar = Calendar.getInstance(); - calendar.setTime(date); - return calendar.get(Calendar.MINUTE); - } - - - /** - * 获得默认的 date pattern - * - * @return 默认的格式 - */ - public static String getDatePattern() { - - return FORMAT_YMDHMS; - } - - - /** - * 返回秒钟 - * - * @param date Date 日期 - * @return 返回秒钟 - */ - public static int getSecond(Date date) { - calendar = Calendar.getInstance(); - - calendar.setTime(date); - return calendar.get(Calendar.SECOND); - } - - - /** - * 使用预设格式提取字符串日期 - * - * @param strDate 日期字符串 - * @return 提取字符串的日期 - */ - public static Date parse(String strDate) { - return parse(strDate, getDatePattern()); - - } - - - /** - * 功能描述:返回毫 - * - * @param date 日期 - * @return 返回毫 - */ - public static long getMillis(Date date) { - calendar = Calendar.getInstance(); - calendar.setTime(date); - return calendar.getTimeInMillis(); - } - - - /** - * 按默认格式的字符串距离今天的天数 - * - * @param date 日期字符串 - * @return 按默认格式的字符串距离今天的天数 - */ - public static int countDays(String date) { - long t = Calendar.getInstance().getTime().getTime(); - Calendar c = Calendar.getInstance(); - c.setTime(parse(date)); - long t1 = c.getTime().getTime(); - return (int) (t / 1000 - t1 / 1000) / 3600 / 24; - - } - - - /** - * 使用用户格式提取字符串日期 - * - * @param strDate 日期字符串 - * @param pattern 日期格式 - * @return 提取字符串日期 - */ - public static Date parse(String strDate, String pattern) { - SimpleDateFormat df = new SimpleDateFormat(pattern); - try { - return df.parse(strDate); - } catch (ParseException e) { - e.printStackTrace(); - return null; - } - - } - - - /** - * 按用户格式字符串距离今天的天数 - * - * @param date 日期字符串 - * @param format 日期格式 - * @return 按用户格式字符串距离今天的天数 - */ - public static int countDays(String date, String format) { - long t = Calendar.getInstance().getTime().getTime(); - Calendar c = Calendar.getInstance(); - c.setTime(parse(date, format)); - long t1 = c.getTime().getTime(); - return (int) (t / 1000 - t1 / 1000) / 3600 / 24; - } - - - /** - * 将毫秒转化为分钟与秒数 - * - * @param duration 音乐时长 - * @return - */ - public static String timeParse(long duration) { - String time = ""; - long minute = duration / 60000; - long seconds = duration % 60000; - long second = Math.round((float) seconds / 1000); - if (minute < 10) { - time += "0"; - } - time += minute + "分"; - if (second < 10) { - time += "0"; - } - time += second + "秒"; - return time; - } - - /*获取星期几*/ - public static String getWeek() { - Calendar cal = Calendar.getInstance(); - int i = cal.get(Calendar.DAY_OF_WEEK); - switch (i) { - case 1: - return "星期日"; - case 2: - return "星期一"; - case 3: - return "星期二"; - case 4: - return "星期三"; - case 5: - return "星期四"; - case 6: - return "星期五"; - case 7: - return "星期六"; - default: - return ""; - } - } - - /** - * 根据一个日期,返回是星期几的字符串 - * - * @param sdate - * @return - */ - public static String getWeek(String sdate) { - // 再转换为时间 - Date date = DateUtil.parse(sdate); - Calendar c = Calendar.getInstance(); - c.setTime(date); - // int hour=c.get(Calendar.DAY_OF_WEEK); - // hour中存的就是星期几了,其范围 1~7 - // 1=星期日 7=星期六,其他类推 - return new SimpleDateFormat("EEEE").format(c.getTime()); - } - - public static String getWeekStr(String sdate) { - String str = ""; - str = DateUtil.getWeek(sdate); - if ("1".equals(str)) { - str = "星期日"; - } else if ("2".equals(str)) { - str = "星期一"; - } else if ("3".equals(str)) { - str = "星期二"; - } else if ("4".equals(str)) { - str = "星期三"; - } else if ("5".equals(str)) { - str = "星期四"; - } else if ("6".equals(str)) { - str = "星期五"; - } else if ("7".equals(str)) { - str = "星期六"; - } - return str; - } - - - public static String getAmOrPm() { - long time = System.currentTimeMillis(); - calendar = Calendar.getInstance(); - calendar.setTimeInMillis(time); - - int apm = calendar.get(Calendar.AM_PM); - if (apm == 1) { - return "下午"; - } else { - return "上午"; - } - } - public static String getAmOrPmStr(String s) { - Date date =DateUtil.parse(s); - long time= getMillis(date); - calendar = Calendar.getInstance(); - calendar.setTimeInMillis(time); - - int apm = calendar.get(Calendar.AM_PM); - if (apm == 1) { - return "下午"; - } else { - return "上午"; - } - } - - /** - * 分割字符串 - * @param time 时间字符串 - * @param split 分隔符 - * @return - */ - public static String[] splitTime(String time, String split){ - if (!TextUtils.isEmpty(time)){ - return time.split(split); - } - return null; - } - - /** - * 根据当前时间判断传入的时间大小,获取传入时间属于那一天 ‘今天’,‘昨天’ - * @param time 时间字符串 - * @return - */ - public static String getDayString(String time){ -// if (time == null || time.length() == 0){ -// return ""; -// } -// -// // 获取当前时间的天数 -// int currentDay = DateUtil.getDay(new Date()); -// // 获取当前时间的月数 -// int currentMonth = DateUtil.getMonth(new Date()); -// // 获取当前时间的年数 -// int currentYear = DateUtil.getFormatYear() -// -// // 获取传入时间的天数 -// int day = Integer.parseInt(splitTime(time," ")[0].split("-")[2]); -// -// int result = currentDay - day; -// -// switch (result){ -// case 0: -// return "今天"; -// case 1: -// return "昨天"; -// default: -// return splitTime(time," ")[0]; -// } - return time; - } - - - public static String dayStart(Date date){ - Calendar c1 =Calendar.getInstance(); - c1.setTime(date); - c1.set(Calendar.HOUR_OF_DAY, 0); - c1.set(Calendar.MINUTE, 0); - c1.set(Calendar.SECOND, 0); - return date2Str(c1,FORMAT_YMDHMS); - } - public static String dayEnd(Date date){ - Calendar c1 = Calendar.getInstance(); - c1.setTime(date); - c1.set(Calendar.HOUR_OF_DAY, 23); - c1.set(Calendar.MINUTE, 59); - c1.set(Calendar.SECOND, 59); - return date2Str(c1,FORMAT_YMDHMS); - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/sys/DensityUtils.java b/baselib/library/src/main/java/com/dhc/library/utils/sys/DensityUtils.java deleted file mode 100644 index a3301f0..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/sys/DensityUtils.java +++ /dev/null @@ -1,173 +0,0 @@ -package com.dhc.library.utils.sys; - -import android.content.Context; -import android.content.res.Resources; - -import java.lang.reflect.Field; - -/** - * 分辨率转换和屏幕参数工具类 - */ -public class DensityUtils { - - - public static int getImageMaxEdge() { - return (int) (165.0 / 320.0 * ScreenUtil.screenWidth); - } - - public static int getImageMinEdge() { - return (int) (76.0 / 320.0 * ScreenUtil.screenWidth); - } - - - /** - * dp to px, return by int - * - * @param context Context - * @param dpValue value in dp - * @return value in px, by int - */ - public static int dp2px(Context context, float dpValue) { - return (int) (dp2pxF(context, dpValue) + 0.5f); - } - - - - /** - * dp to px, return by float - * - * @param context Context - * @param dpValue value in dp - * @return value in px, by float - */ - public static float dp2pxF(Context context, float dpValue) { - final float scale = context.getResources().getDisplayMetrics().density; - return dpValue * scale; - } - - /** - * px to dp, return by int - * - * @param context Context - * @param pxValue value in px - * @return value in dp, by int - */ - public static int px2dp(Context context, float pxValue) { - return (int) (px2dpF(context, pxValue) + 0.5f); - } - - /** - * px to dp, return by float - * - * @param context Context - * @param pxValue value in px - * @return value in dp - */ - public static float px2dpF(Context context, float pxValue) { - final float scale = context.getResources().getDisplayMetrics().density; - return pxValue / scale; - } - - /** - * px to sp, return by int - * - * @param context Context - * @param pxValue value in px - * @return value in sp - */ - public static int px2sp(Context context, float pxValue) { - return (int) (px2spF(context, pxValue) + 0.5f); - } - - /** - * px to sp, return by float - * - * @param context Context - * @param pxValue value in px - * @return value in sp - */ - public static float px2spF(Context context, float pxValue) { - final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; - return pxValue / fontScale; - } - - /** - * sp to px, return by int - * - * @param context Context - * @param spValue value in sp - * @return value in px - */ - public static int sp2px(Context context, float spValue) { - return (int) (sp2pxF(context, spValue) + 0.5f); - } - - /** - * sp to px, return by float - * - * @param context Context - * @param spValue value in sp - * @return value in px - */ - public static float sp2pxF(Context context, float spValue) { - final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; - return spValue * fontScale + 0.5f; - } - - /** - * 获取屏幕宽度 - * - * @param context Context - * @return 屏幕宽度 - */ - public static int getScreenWidth(Context context) { - return context.getResources().getDisplayMetrics().widthPixels; - } - - /** - * 获取屏幕高度 - * - * @param context Context - * @return 屏幕高度 - */ - public static int getScreenHeight(Context context) { - return context.getResources().getDisplayMetrics().heightPixels; - } - - /** - * 获取状态栏高度 - * - * @param context Context - * @return 状态栏高度 - */ - public static int getStatusBarHeight(Context context) { - Class c; - Object obj; - Field field; - int statusBarHeight = 0; - try { - c = Class.forName("com.android.internal.R$dimen"); - obj = c.newInstance(); - field = c.getField("status_bar_height"); - int x = Integer.parseInt(field.get(obj).toString()); - statusBarHeight = context.getResources().getDimensionPixelSize(x); - } catch (Exception e) { - e.printStackTrace(); - } - return statusBarHeight; - } - - /** - * 获取导航栏高度 - * - * @param context Context - * @return 导航栏高度 - */ - public static int getNavigationBarHeight(Context context) { - Resources resources = context.getResources(); - int identifier = resources.getIdentifier("navigation_bar_height", "dimen", "android"); - return resources.getDimensionPixelOffset(identifier); - } - - -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/sys/NetworkUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/sys/NetworkUtil.java deleted file mode 100644 index e3bce7d..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/sys/NetworkUtil.java +++ /dev/null @@ -1,975 +0,0 @@ -package com.dhc.library.utils.sys; - -import android.app.Activity; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.database.Cursor; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.net.Uri; -import android.net.wifi.WifiInfo; -import android.net.wifi.WifiManager; -import android.os.Build; -import android.telephony.TelephonyManager; -import android.text.TextUtils; - - - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - - -public class NetworkUtil { - - public static final String TAG = "NetworkUtil"; - - public static final byte CURRENT_NETWORK_TYPE_NONE = 0; - - /* - * 根据APN区分网络类型 - */ - public static final byte CURRENT_NETWORK_TYPE_WIFI = 1;// wifi - - public static final byte CURRENT_NETWORK_TYPE_CTNET = 2;// ctnet - - public static final byte CURRENT_NETWORK_TYPE_CTWAP = 3;// ctwap - - public static final byte CURRENT_NETWORK_TYPE_CMWAP = 4;// cmwap - - public static final byte CURRENT_NETWORK_TYPE_UNIWAP = 5;// uniwap,3gwap - - public static final byte CURRENT_NETWORK_TYPE_CMNET = 6;// cmnet - - public static final byte CURRENT_NETWORK_TYPE_UNIET = 7;// uninet,3gnet - - /** - * 根据运营商区分网络类型 - */ - public static final byte CURRENT_NETWORK_TYPE_CTC = 10;// ctwap,ctnet - - public static final byte CURRENT_NETWORK_TYPE_CUC = 11;// uniwap,3gwap,uninet,3gnet - - public static final byte CURRENT_NETWORK_TYPE_CM = 12;// cmwap,cmnet - - /** - * apn值 - */ - private static final String CONNECT_TYPE_WIFI = "wifi"; - - private static final String CONNECT_TYPE_CTNET = "ctnet"; - - private static final String CONNECT_TYPE_CTWAP = "ctwap"; - - private static final String CONNECT_TYPE_CMNET = "cmnet"; - - private static final String CONNECT_TYPE_CMWAP = "cmwap"; - - private static final String CONNECT_TYPE_UNIWAP = "uniwap"; - - private static final String CONNECT_TYPE_UNINET = "uninet"; - - private static final String CONNECT_TYPE_UNI3GWAP = "3gwap"; - - private static final String CONNECT_TYPE_UNI3GNET = "3gnet"; - - private static final Uri PREFERRED_APN_URI = Uri.parse("content://telephony/carriers/preferapn"); - - public static byte curNetworkType = CURRENT_NETWORK_TYPE_NONE; - - /* - * - * 获取网络类型 - * - */ - public static int getNetType(Context context){ - NetworkInfo networkInfo = getActiveNetworkInfo(context); - if(networkInfo == null){ - return -1; - }else - return networkInfo.getType(); - } - - - /** - * 判断当前网络类型。WIFI,NET,WAP - * - * @param context - * @return - */ - public static byte getCurrentNetType(Context context) { - NetworkInfo networkInfo = getActiveNetworkInfo(context); - byte type = CURRENT_NETWORK_TYPE_NONE; - if (networkInfo != null) { - // String typeName = networkInfo.getTypeName(); - // XT800 - String typeName = networkInfo.getExtraInfo(); - if (TextUtils.isEmpty(typeName)) { - typeName = networkInfo.getTypeName(); - } - if (!TextUtils.isEmpty(typeName)) { - String temp = typeName.toLowerCase(); - if (temp.indexOf(CONNECT_TYPE_WIFI) > -1) {// wifi - type = CURRENT_NETWORK_TYPE_WIFI; - } else if (temp.indexOf(CONNECT_TYPE_CTNET) > -1) {// ctnet - type = CURRENT_NETWORK_TYPE_CTNET; - } else if (temp.indexOf(CONNECT_TYPE_CTWAP) > -1) {// ctwap - type = CURRENT_NETWORK_TYPE_CTWAP; - } else if (temp.indexOf(CONNECT_TYPE_CMNET) > -1) {// cmnet - type = CURRENT_NETWORK_TYPE_CMNET; - } else if (temp.indexOf(CONNECT_TYPE_CMWAP) > -1) {// cmwap - type = CURRENT_NETWORK_TYPE_CMWAP; - } else if (temp.indexOf(CONNECT_TYPE_UNIWAP) > -1) {// uniwap - type = CURRENT_NETWORK_TYPE_UNIWAP; - } else if (temp.indexOf(CONNECT_TYPE_UNI3GWAP) > -1) {// 3gwap - type = CURRENT_NETWORK_TYPE_UNIWAP; - } else if (temp.indexOf(CONNECT_TYPE_UNINET) > -1) {// uninet - type = CURRENT_NETWORK_TYPE_UNIET; - } else if (temp.indexOf(CONNECT_TYPE_UNI3GNET) > -1) {// 3gnet - type = CURRENT_NETWORK_TYPE_UNIET; - } - } - } - - if (type == CURRENT_NETWORK_TYPE_NONE) { - String apnType = getApnType(context); - if (apnType != null && apnType.equals(CONNECT_TYPE_CTNET)) {// ctnet - type = CURRENT_NETWORK_TYPE_CTNET; - } else if (apnType != null && apnType.equals(CONNECT_TYPE_CTWAP)) {// ctwap - type = CURRENT_NETWORK_TYPE_CTWAP; - } else if (apnType != null && apnType.equals(CONNECT_TYPE_CMWAP)) {// cmwap - type = CURRENT_NETWORK_TYPE_CMWAP; - } else if (apnType != null && apnType.equals(CONNECT_TYPE_CMNET)) {// cmnet - type = CURRENT_NETWORK_TYPE_CMNET; - } else if (apnType != null && apnType.equals(CONNECT_TYPE_UNIWAP)) {// uniwap - type = CURRENT_NETWORK_TYPE_UNIWAP; - } else if (apnType != null && apnType.equals(CONNECT_TYPE_UNI3GWAP)) {// 3gwap - type = CURRENT_NETWORK_TYPE_UNIWAP; - } else if (apnType != null && apnType.equals(CONNECT_TYPE_UNINET)) {// uninet - type = CURRENT_NETWORK_TYPE_UNIET; - } else if (apnType != null && apnType.equals(CONNECT_TYPE_UNI3GNET)) {// 3gnet - type = CURRENT_NETWORK_TYPE_UNIET; - } - } - curNetworkType = type; - - return type; - } - - /** - * 判断APNTYPE - * - * @param context - * @return - */ - /** - * @deprecated 4.0 - * doc: - * Since the DB may contain corp passwords, we should secure it. Using the same permission as writing to the DB as the read is potentially as damaging as a write - */ - public static String getApnType(Context context) { - - String apntype = "nomatch"; - Cursor c = context.getContentResolver().query(PREFERRED_APN_URI, null, null, null, null); - if (c != null) { - if (c.moveToFirst()) { - String user = c.getString(c.getColumnIndex("user")); - if (user != null && user.startsWith(CONNECT_TYPE_CTNET)) { - apntype = CONNECT_TYPE_CTNET; - } else if (user != null && user.startsWith(CONNECT_TYPE_CTWAP)) { - apntype = CONNECT_TYPE_CTWAP; - } else if (user != null && user.startsWith(CONNECT_TYPE_CMWAP)) { - apntype = CONNECT_TYPE_CMWAP; - } else if (user != null && user.startsWith(CONNECT_TYPE_CMNET)) { - apntype = CONNECT_TYPE_CMNET; - } else if (user != null && user.startsWith(CONNECT_TYPE_UNIWAP)) { - apntype = CONNECT_TYPE_UNIWAP; - } else if (user != null && user.startsWith(CONNECT_TYPE_UNINET)) { - apntype = CONNECT_TYPE_UNINET; - } else if (user != null && user.startsWith(CONNECT_TYPE_UNI3GWAP)) { - apntype = CONNECT_TYPE_UNI3GWAP; - } else if (user != null && user.startsWith(CONNECT_TYPE_UNI3GNET)) { - apntype = CONNECT_TYPE_UNI3GNET; - } - } - c.close(); - c = null; - } - - return apntype; - } - - /** - * 判断是否有网络可用 - * - * @param context - * @return - */ - public static boolean isNetAvailable(Context context) { - NetworkInfo networkInfo = getActiveNetworkInfo(context); - if (networkInfo != null) { - return networkInfo.isAvailable(); - } else { - return false; - } - } - - /** - * 此判断不可靠 - * - * @param context - * @return - */ - public static boolean isNetworkConnected(Context context) { - NetworkInfo networkInfo = getActiveNetworkInfo(context); - if (networkInfo != null) { - boolean a = networkInfo.isConnected(); - return a; - } else { - return false; - } - } - - /** - * 获取可用的网络信息 - * - * @param context - * @return - */ - private static NetworkInfo getActiveNetworkInfo(Context context) { - try { - ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - return cm.getActiveNetworkInfo(); - } catch (Exception e) { - return null; - } - } - - public static boolean isWifiOr3G(Context context) { - if (isWifi(context)) { - return true; - } else { - return is3G(context); - } - } - - public static boolean is2G(Context context) { - return !isWifiOr3G(context); - } - - public static boolean is3G(Context context) { - int type = getNetworkClass(context); - if (type == NETWORK_CLASS_3_G || type == NETWORK_CLASS_4_G) { - return true; - } else { - return false; - } - } - - /** - * 当前网络是否是wifi网络 - * - * @param context - * @return - */ - public static boolean isWifi(Context context) { - try { - ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - NetworkInfo ni = cm.getActiveNetworkInfo(); - if (ni != null) { - if (ni.getType() == ConnectivityManager.TYPE_WIFI) { - return true; - } else { - return false; - } - } else { - return false; - } - } catch (Exception e) { - return false; - } - } - - public static boolean getNetworkConnectionStatus(Context context) { - ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - if (manager == null) { - return false; - } - - NetworkInfo info = manager.getActiveNetworkInfo(); - if (info == null) { - return false; - } - - TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); - if (tm == null) { - return false; - } - - if ((tm.getDataState() == TelephonyManager.DATA_CONNECTED || tm.getDataState() == TelephonyManager.DATA_ACTIVITY_NONE) - && info.isAvailable()) { - return true; - } else { - return false; - } - } - - public static String getNetworkProxyInfo(Context context) { - String proxyHost = android.net.Proxy.getDefaultHost(); - int proxyPort = android.net.Proxy.getDefaultPort(); - String szport = String.valueOf(proxyPort); - String proxyInfo = null; - - ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - if (manager == null) { - return null; - } else { - NetworkInfo info = manager.getActiveNetworkInfo(); - if (info != null) { - String typeName = info.getTypeName().toLowerCase(); - if (typeName != null && typeName.equals("wifi")) { - return null; - } - } else { - return null; - } - } - - if (proxyHost != null && (0 < proxyPort && proxyPort < 65535)) { - proxyInfo = proxyHost + ":" + szport; - return proxyInfo; - } else { - return null; - } - } - - public static String getNetworkProxyUrl(Context context) { - if (isWifi(context)) { - return null; - } - - String proxyHost = android.net.Proxy.getDefaultHost(); - return proxyHost; - } - - public static String getNetworkProxyUrl() { - /** - * 当网络为wifi时,直接返回空代理: 当ctwap,cmwap,uniwap,3gwap开启时同时开启wifi网络 - * ,通过下面的getDefaultHost接口将得到对应wap网络代理ip ,这是错误的,所以在此判断当前网络是否为wifi - */ - if (curNetworkType == CURRENT_NETWORK_TYPE_WIFI) { - return null; - } - - String proxyHost = android.net.Proxy.getDefaultHost(); - return proxyHost; - } - - public static int getNetworkProxyPort() { - int proxyPort = android.net.Proxy.getDefaultPort(); - return proxyPort; - } - - public static boolean isCtwap(Context context) { - if (getApnType(context).equals(CONNECT_TYPE_CTWAP)) { - return true; - } else { - return false; - } - } - - public static boolean isUniwap(Context context) { - if (getApnType(context).equals(CONNECT_TYPE_UNIWAP)) { - return true; - } else { - return false; - } - } - - public static boolean isCmwap(Context context) { - if (getApnType(context).equals(CONNECT_TYPE_CMWAP)) { - return true; - } else { - return false; - } - } - - /** - * 判断是否是电信网络(ctwap,ctnet) - * - * @return - */ - public static boolean isCtcNetwork(Context context) { - byte type = getCurrentNetType(context); - - return isCtcNetwork(type); - } - - public static boolean isCtcNetwork(String apnName) { - if (apnName == null) { - return false; - } - - if (apnName.equals(CONNECT_TYPE_CTWAP) || apnName.equals(CONNECT_TYPE_CTNET)) { - return true; - } else { - return false; - } - } - - public static boolean isCtcNetwork(byte type) { - if (type == CURRENT_NETWORK_TYPE_CTWAP || type == CURRENT_NETWORK_TYPE_CTNET) { - return true; - } else { - return false; - } - } - - /** - * 判断是否是联通网络(uniwap,uninet,3gwap,3gnet) - * - * @return - */ - public static boolean isCucNetwork(Context context) { - byte type = getCurrentNetType(context); - - return isCucNetwork(type); - } - - public static boolean isCucNetwork(String apnName) { - if (apnName == null) { - return false; - } - - if (apnName.equals(CONNECT_TYPE_UNIWAP) || apnName.equals(CONNECT_TYPE_UNINET) - || apnName.equals(CONNECT_TYPE_UNI3GWAP) || apnName.equals(CONNECT_TYPE_UNI3GNET)) { - return true; - } else { - return false; - } - } - - public static boolean isCucNetwork(byte type) { - if (type == CURRENT_NETWORK_TYPE_UNIWAP || type == CURRENT_NETWORK_TYPE_UNIET) { - return true; - } else { - return false; - } - } - - /** - * 判断是否是移动网络(cmwap,cmnet) - * - * @return - */ - public static boolean isCmbNetwork(Context context) { - byte type = getCurrentNetType(context); - - return isCmbNetwork(type); - } - - public static boolean isCmbNetwork(String apnName) { - if (apnName == null) { - return false; - } - - if (apnName.equals(CONNECT_TYPE_CMWAP) || apnName.equals(CONNECT_TYPE_CMNET)) { - return true; - } else { - return false; - } - } - - public static boolean isCmbNetwork(byte type) { - if (type == CURRENT_NETWORK_TYPE_CMWAP || type == CURRENT_NETWORK_TYPE_CMNET) { - return true; - } else { - return false; - } - } - - /** - * 获取网络运营商类型(中国移动,中国联通,中国电信,wifi) - * - * @param context - * @return - */ - public static byte getNetworkOperators(Context context) { - if (isWifi(context)) { - return CURRENT_NETWORK_TYPE_WIFI; - } else if (isCtcNetwork(context)) { - return CURRENT_NETWORK_TYPE_CTC; - } else if (isCmbNetwork(context)) { - return CURRENT_NETWORK_TYPE_CM; - } else if (isCucNetwork(context)) { - return CURRENT_NETWORK_TYPE_CUC; - } else { - return CURRENT_NETWORK_TYPE_NONE; - } - } - - public static byte getNetworkOperators(byte type) { - if (type == CURRENT_NETWORK_TYPE_NONE) { - return CURRENT_NETWORK_TYPE_NONE; - } else if (type == CURRENT_NETWORK_TYPE_WIFI) { - return CURRENT_NETWORK_TYPE_WIFI; - } else if (type == CURRENT_NETWORK_TYPE_CTNET || type == CURRENT_NETWORK_TYPE_CTWAP) { - return CURRENT_NETWORK_TYPE_CTC; - } else if (type == CURRENT_NETWORK_TYPE_CMWAP || type == CURRENT_NETWORK_TYPE_CMNET) { - return CURRENT_NETWORK_TYPE_CM; - } else if (type == CURRENT_NETWORK_TYPE_UNIWAP || type == CURRENT_NETWORK_TYPE_UNIET) { - return CURRENT_NETWORK_TYPE_CUC; - } else { - return CURRENT_NETWORK_TYPE_NONE; - } - } - - /** - * 是否需要设置代理(网络请求,一般用于wap网络,但有些机型设置代理会导致系统异常) - * - * @return - */ - public static boolean isNeedSetProxyForNetRequest() { // #00044 + - if (Build.MODEL.equals("SCH-N719") || Build.MODEL.equals("SCH-I939D")) { - return false; - } else { - return true; - } - } - - /** - * get mac address of wifi if wifi is active - */ - - public static String getActiveMacAddress(Context context) { - WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); - - WifiInfo info = wifi.getConnectionInfo(); - - if (info != null) { - return info.getMacAddress(); - } - - return ""; - } - - public static String getNetworkInfo(Context context) { - String info = ""; - ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - if (connectivity != null) { - NetworkInfo activeNetInfo = connectivity.getActiveNetworkInfo(); - if (activeNetInfo != null) { - if (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) { - info = activeNetInfo.getTypeName(); - } else { - StringBuilder sb = new StringBuilder(); - TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); - sb.append(activeNetInfo.getTypeName()); - sb.append(" ["); - if (tm != null) { - // Result may be unreliable on CDMA networks - sb.append(tm.getNetworkOperatorName()); - sb.append("#"); - } - sb.append(activeNetInfo.getSubtypeName()); - sb.append("]"); - info = sb.toString(); - } - } - } - return info; - } - - public enum NetworkSpeedMode { - LOW, NORMAL, HIGH, UNKNOWN - } - - /** - * 网络类型 - */ - public static final int NETWORK_CLASS_UNKNOWN = 0; - - public static final int NETWORK_CLASS_2_G = 1; - - public static final int NETWORK_CLASS_3_G = 2; - - public static final int NETWORK_CLASS_4_G = 3; - - public static final int NETWORK_CLASS_WIFI = 10; - - /** - * 仅判断Mobile网络的慢速.蓝牙等其他网络不做判断. - * - * @param context - * @return - */ - public static NetworkSpeedMode getNetworkSpeedModeInMobile(Context context) { - ConnectivityManager connectivityManager = (ConnectivityManager) context - .getSystemService(Context.CONNECTIVITY_SERVICE); - if (connectivityManager != null) { - NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); - if (networkInfo != null) { - if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { - switch (networkInfo.getSubtype()) { - case TelephonyManager.NETWORK_TYPE_IDEN: // ~25 kbps - return NetworkSpeedMode.LOW; - case TelephonyManager.NETWORK_TYPE_CDMA: // ~ 14-64 kbps - return NetworkSpeedMode.LOW; - case TelephonyManager.NETWORK_TYPE_1xRTT: // ~ 50-100 kbps - return NetworkSpeedMode.LOW; - case TelephonyManager.NETWORK_TYPE_EDGE: // ~ 50-100 kbps - return NetworkSpeedMode.LOW; - case TelephonyManager.NETWORK_TYPE_GPRS: // ~ 100 kbps - return NetworkSpeedMode.LOW; - - case TelephonyManager.NETWORK_TYPE_EVDO_0: // ~ 400-1000 - // kbps - return NetworkSpeedMode.NORMAL; - case TelephonyManager.NETWORK_TYPE_EVDO_A: // ~ 600-1400 - // kbps - return NetworkSpeedMode.NORMAL; - case TelephonyManager.NETWORK_TYPE_HSPA: // ~ 700-1700 kbps - return NetworkSpeedMode.NORMAL; - case TelephonyManager.NETWORK_TYPE_UMTS: // ~ 400-7000 kbps - return NetworkSpeedMode.NORMAL; - case 14: // TelephonyManager.NETWORK_TYPE_EHRPD: // ~ 1-2 - // Mbps - return NetworkSpeedMode.NORMAL; - case 12: // TelephonyManager.NETWORK_TYPE_EVDO_B: // ~ 5 - // Mbps - return NetworkSpeedMode.NORMAL; - - case TelephonyManager.NETWORK_TYPE_HSDPA: // ~ 2-14 Mbps - return NetworkSpeedMode.HIGH; - case TelephonyManager.NETWORK_TYPE_HSUPA: // ~ 1-23 Mbps - return NetworkSpeedMode.HIGH; - case 15: // TelephonyManager.NETWORK_TYPE_HSPAP: // ~ 10-20 - // Mbps - return NetworkSpeedMode.HIGH; - case 13: // TelephonyManager.NETWORK_TYPE_LTE: // ~ 10+ Mbps - return NetworkSpeedMode.HIGH; - - case TelephonyManager.NETWORK_TYPE_UNKNOWN: - return NetworkSpeedMode.NORMAL; - default: - break; - } - } - } - } - return NetworkSpeedMode.UNKNOWN; - } - - /** - * 获取在Mobile网络下的网络类型. 2G,3G,4G - * - * @param context - * @return - */ - public static int getNetworkClass(Context context) { - ConnectivityManager connectivityManager = (ConnectivityManager) context - .getSystemService(Context.CONNECTIVITY_SERVICE); - if (connectivityManager != null) { - NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); - if (networkInfo != null) { - if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { - switch (networkInfo.getSubtype()) { - case TelephonyManager.NETWORK_TYPE_GPRS: - case TelephonyManager.NETWORK_TYPE_EDGE: - case TelephonyManager.NETWORK_TYPE_CDMA: - case TelephonyManager.NETWORK_TYPE_1xRTT: - case TelephonyManager.NETWORK_TYPE_IDEN: - return NETWORK_CLASS_2_G; - case TelephonyManager.NETWORK_TYPE_UMTS: - case TelephonyManager.NETWORK_TYPE_EVDO_0: - case TelephonyManager.NETWORK_TYPE_EVDO_A: - case TelephonyManager.NETWORK_TYPE_HSDPA: - case TelephonyManager.NETWORK_TYPE_HSUPA: - case TelephonyManager.NETWORK_TYPE_HSPA: - case 12: // TelephonyManager.NETWORK_TYPE_EVDO_B: - case 14: // TelephonyManager.NETWORK_TYPE_EHRPD: - case 15: // TelephonyManager.NETWORK_TYPE_HSPAP: - return NETWORK_CLASS_3_G; - case 13: // TelephonyManager.NETWORK_TYPE_LTE: - return NETWORK_CLASS_4_G; - default: - return NETWORK_CLASS_UNKNOWN; - } - } else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { - return NETWORK_CLASS_WIFI; - } - } - } - return NETWORK_CLASS_UNKNOWN; - } - - public static String getNetworkTypeName(Context context) { - String networkName = "UNKNOWN"; - ConnectivityManager connectivityManager = (ConnectivityManager) context - .getSystemService(Context.CONNECTIVITY_SERVICE); - if (connectivityManager != null) { - NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); - if (networkInfo != null) { - networkName = getNetworkTypeName(networkInfo.getType()); - if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { - networkName += "#" + getNetworkTypeNameInMobile(networkInfo.getSubtype()); - } - } - } - return networkName; - } - - private static String getNetworkTypeNameInMobile(int type) { - switch (type) { - case TelephonyManager.NETWORK_TYPE_GPRS: - return "GPRS"; - case TelephonyManager.NETWORK_TYPE_EDGE: - return "EDGE"; - case TelephonyManager.NETWORK_TYPE_UMTS: - return "UMTS"; - case TelephonyManager.NETWORK_TYPE_HSDPA: - return "HSDPA"; - case TelephonyManager.NETWORK_TYPE_HSUPA: - return "HSUPA"; - case TelephonyManager.NETWORK_TYPE_HSPA: - return "HSPA"; - case TelephonyManager.NETWORK_TYPE_CDMA: - return "CDMA"; - case TelephonyManager.NETWORK_TYPE_EVDO_0: - return "CDMA - EvDo rev. 0"; - case TelephonyManager.NETWORK_TYPE_EVDO_A: - return "CDMA - EvDo rev. A"; - case TelephonyManager.NETWORK_TYPE_EVDO_B: - return "CDMA - EvDo rev. B"; - case TelephonyManager.NETWORK_TYPE_1xRTT: - return "CDMA - 1xRTT"; - case TelephonyManager.NETWORK_TYPE_LTE: - return "LTE"; - case TelephonyManager.NETWORK_TYPE_EHRPD: - return "CDMA - eHRPD"; - case TelephonyManager.NETWORK_TYPE_IDEN: - return "iDEN"; - case TelephonyManager.NETWORK_TYPE_HSPAP: - return "HSPA+"; - default: - return "UNKNOWN"; - } - } - - private static String getNetworkTypeName(int type) { - switch (type) { - case ConnectivityManager.TYPE_MOBILE: - return "MOBILE"; - case ConnectivityManager.TYPE_WIFI: - return "WIFI"; - case ConnectivityManager.TYPE_MOBILE_MMS: - return "MOBILE_MMS"; - case ConnectivityManager.TYPE_MOBILE_SUPL: - return "MOBILE_SUPL"; - case ConnectivityManager.TYPE_MOBILE_DUN: - return "MOBILE_DUN"; - case ConnectivityManager.TYPE_MOBILE_HIPRI: - return "MOBILE_HIPRI"; - case ConnectivityManager.TYPE_WIMAX: - return "WIMAX"; - case ConnectivityManager.TYPE_BLUETOOTH: - return "BLUETOOTH"; - case ConnectivityManager.TYPE_DUMMY: - return "DUMMY"; - case ConnectivityManager.TYPE_ETHERNET: - return "ETHERNET"; - case 10: // ConnectivityManager.TYPE_MOBILE_FOTA: - return "MOBILE_FOTA"; - case 11: // ConnectivityManager.TYPE_MOBILE_IMS: - return "MOBILE_IMS"; - case 12: // ConnectivityManager.TYPE_MOBILE_CBS: - return "MOBILE_CBS"; - case 13: // ConnectivityManager.TYPE_WIFI_P2P: - return "WIFI_P2P"; - default: - return Integer.toString(type); - } - } - - //中国电信 - public static final int ISP_CTCC = 0; - //中国联通 - public static final int ISP_CUCC = 1; - //中国移动 - public static final int ISP_CMCC = 2; - //中国铁通 - public static final int ISP_CTT = 3; - //其他 - public static final int ISP_OTHERS = -1; - - public static String getSimOperator(Context context) { - TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); - if(tm != null){ - return tm.getSimOperator(); - } - return null; - } - - public static String getNetworkOperator(Context context) { - TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); - if(tm != null){ - return tm.getNetworkOperator(); - } - return null; - } - - - public interface LinkNetWorkType { - public static final int UNKNOWN = 0; - public static final int WIFI = 1; - public static final int WWAN = 2; - public static final int _2G = 3; - public static final int _3G = 4; - public static final int _4G = 5; - } - public static int getNetworkTypeForLink(Context context) { - try { - ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - NetworkInfo ni = cm.getActiveNetworkInfo(); - if (ni != null) { - if (ni.getType() == ConnectivityManager.TYPE_WIFI) { - return LinkNetWorkType.WIFI; - } else { - if (ni.getType() == ConnectivityManager.TYPE_MOBILE) { - switch (ni.getSubtype()) { - case TelephonyManager.NETWORK_TYPE_GPRS: - case TelephonyManager.NETWORK_TYPE_EDGE: - case TelephonyManager.NETWORK_TYPE_CDMA: - case TelephonyManager.NETWORK_TYPE_1xRTT: - case TelephonyManager.NETWORK_TYPE_IDEN: - return LinkNetWorkType._2G; - case TelephonyManager.NETWORK_TYPE_UMTS: - case TelephonyManager.NETWORK_TYPE_EVDO_0: - case TelephonyManager.NETWORK_TYPE_EVDO_A: - case TelephonyManager.NETWORK_TYPE_HSDPA: - case TelephonyManager.NETWORK_TYPE_HSUPA: - case TelephonyManager.NETWORK_TYPE_HSPA: - case 12: // TelephonyManager.NETWORK_TYPE_EVDO_B: - case 14: // TelephonyManager.NETWORK_TYPE_EHRPD: - case 15: // TelephonyManager.NETWORK_TYPE_HSPAP: - return LinkNetWorkType._3G; - case 13: // TelephonyManager.NETWORK_TYPE_LTE: - return LinkNetWorkType._4G; - default: - return LinkNetWorkType._2G; - } - } - } - } - } catch (Exception e) { - return LinkNetWorkType.UNKNOWN; - } - return LinkNetWorkType.UNKNOWN; - } - - - - /** - * 检测网络是否连接 - */ - public static boolean isNetConnected(Context context) { - ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - if (cm != null) { - NetworkInfo[] infos = cm.getAllNetworkInfo(); - if (infos != null) { - for (NetworkInfo ni : infos) { - if (ni.isConnected()) { - return true; - } - } - } - } - return false; - } - - /** - * 检测wifi是否连接 - */ - public static boolean isWifiConnected(Context context) { - ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - if (cm != null) { - NetworkInfo networkInfo = cm.getActiveNetworkInfo(); - if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { - return true; - } - } - return false; - } - - /** - * 检测3G是否连接 - */ - public static boolean is3gConnected(Context context) { - ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - if (cm != null) { - NetworkInfo networkInfo = cm.getActiveNetworkInfo(); - if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { - return true; - } - } - return false; - } - - /** - * 判断网址是否有效 - */ - public static boolean isLinkAvailable(String link) { - Pattern pattern = Pattern.compile("^(http://|https://)?((?:[A-Za-z0-9]+-[A-Za-z0-9]+|[A-Za-z0-9]+)\\.)+([A-Za-z]+)[/\\?\\:]?.*$", Pattern.CASE_INSENSITIVE); - Matcher matcher = pattern.matcher(link); - if (matcher.matches()) { - return true; - } - return false; - } - - /** - * 判断网络是否连接 - * - * @param context - * @return - */ - public static boolean isConnected(Context context) { - NetworkInfo networkInfo = getConnectivityManager(context).getActiveNetworkInfo(); - return networkInfo != null && networkInfo.isConnected(); - } - - - private static ConnectivityManager getConnectivityManager(Context context) { - return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - } - /** - * 判断是否是WIFI连接 - * - * @param context - * @return - */ - public static boolean isWIFI(Context context) { - - ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); - if (connectivityManager == null) - return false; - return connectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI; - } - - /** - * 打开网络设置界面 - */ - public static void openSetting(Activity activity) { - Intent intent = new Intent("/"); - ComponentName cm = new ComponentName("com.android.settings", - "com.android.settings.WirelessSettings"); - intent.setComponent(cm); - intent.setAction("android.intent.action.VIEW"); - activity.startActivityForResult(intent, 0); - } - - - - -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/sys/ScreenUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/sys/ScreenUtil.java deleted file mode 100644 index 8ae6806..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/sys/ScreenUtil.java +++ /dev/null @@ -1,173 +0,0 @@ -package com.dhc.library.utils.sys; - -import android.app.Dialog; -import android.content.Context; -import android.content.res.Resources; -import android.util.DisplayMetrics; -import android.util.Log; -import android.view.Window; -import android.view.WindowManager; -import android.widget.PopupWindow; - -import com.dhc.library.utils.AppContext; - -import java.lang.reflect.Field; - -public class ScreenUtil { - private static final String TAG = "Demo.ScreenUtil"; - - private static double RATIO = 0.85; - - public static int screenWidth; - public static int screenHeight; - public static int screenMin;// 宽高中,小的一边 - public static int screenMax;// 宽高中,较大的值 - - public static float density; - public static float scaleDensity; - public static float xdpi; - public static float ydpi; - public static int densityDpi; - - public static int dialogWidth; - public static int statusbarheight; - public static int navbarheight; - - static { - init(AppContext.get()); - } - - public static int dip2px(float dipValue) { - return (int) (dipValue * density + 0.5f); - } - - public static int px2dip(float pxValue) { - return (int) (pxValue / density + 0.5f); - } - - public static int sp2px(float spValue) { - return (int) (spValue * scaleDensity + 0.5f); - } - - public static int getDialogWidth() { - dialogWidth = (int) (screenMin * RATIO); - return dialogWidth; - } - - public static void init(Context context) { - if (null == context) { - return; - } - DisplayMetrics dm = context.getApplicationContext().getResources().getDisplayMetrics(); - screenWidth = dm.widthPixels; - screenHeight = dm.heightPixels; - screenMin = (screenWidth > screenHeight) ? screenHeight : screenWidth; - density = dm.density; - scaleDensity = dm.scaledDensity; - xdpi = dm.xdpi; - ydpi = dm.ydpi; - densityDpi = dm.densityDpi; - - Log.d(TAG, "screenWidth=" + screenWidth + " screenHeight=" + screenHeight + " density=" + density); - } - - public static int getDisplayWidth() { - if (screenWidth == 0) { - GetInfo(AppContext.get()); - } - return screenWidth; - } - - public static int getDisplayHeight() { - if (screenHeight == 0) { - GetInfo(AppContext.get()); - } - return screenHeight; - } - - public static void GetInfo(Context context) { - if (null == context) { - return; - } - DisplayMetrics dm = context.getApplicationContext().getResources().getDisplayMetrics(); - screenWidth = dm.widthPixels; - screenHeight = dm.heightPixels; - screenMin = (screenWidth > screenHeight) ? screenHeight : screenWidth; - screenMax = (screenWidth < screenHeight) ? screenHeight : screenWidth; - density = dm.density; - scaleDensity = dm.scaledDensity; - xdpi = dm.xdpi; - ydpi = dm.ydpi; - densityDpi = dm.densityDpi; - statusbarheight = getStatusBarHeight(context); - navbarheight = getNavBarHeight(context); - Log.d(TAG, "screenWidth=" + screenWidth + " screenHeight=" + screenHeight + " density=" + density); - } - - public static int getStatusBarHeight(Context context) { - if (statusbarheight == 0) { - try { - Class c = Class.forName("com.android.internal.R$dimen"); - Object o = c.newInstance(); - Field field = c.getField("status_bar_height"); - int x = (Integer) field.get(o); - statusbarheight = context.getResources().getDimensionPixelSize(x); - } catch (Exception e) { - e.printStackTrace(); - } - } - if (statusbarheight == 0) { - statusbarheight = ScreenUtil.dip2px(25); - } - return statusbarheight; - } - - public static int getNavBarHeight(Context context) { - Resources resources = context.getResources(); - int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android"); - if (resourceId > 0) { - return resources.getDimensionPixelSize(resourceId); - } - return 0; - } - - /** - * 设置dialog大小占屏幕的宽高 - * @param widthRatio 宽度比例 - * @param heightRatio 高度比例 - * @param isTrue 高度和宽度是否相等 - * @param type -> 1: 和宽度相等 - * -> 2: 和高度相等 - */ - public static void setWindowDisplay(Dialog mDialog, Context mContext, double widthRatio, double heightRatio, boolean isTrue, int type){ - Window dialogWindow = mDialog.getWindow(); - WindowManager.LayoutParams params = dialogWindow.getAttributes(); - DisplayMetrics metrics = mContext.getResources().getDisplayMetrics(); // 获取屏幕宽、高 - - if (isTrue){ - if (type == 1){ - params.width = (int) (metrics.widthPixels * widthRatio); - params.height = (int) (metrics.widthPixels * widthRatio); - }else{ - params.width = (int) (metrics.heightPixels * heightRatio); - params.height = (int) (metrics.heightPixels * heightRatio); - } - }else{ - params.width = (int) (metrics.widthPixels * widthRatio); - params.height = (int) (metrics.heightPixels * heightRatio); - } - - dialogWindow.setAttributes(params); - } - - /** - * 设置dialog大小占屏幕的宽高 - * @param widthRatio 宽度比例 - * @param heightRatio 高度比例 - */ - public static void setWindowDisplay(PopupWindow mWindows, Context mContext, double widthRatio, double heightRatio){ - DisplayMetrics metrics = mContext.getResources().getDisplayMetrics(); // 获取屏幕宽、高 - mWindows.setWidth((int) (metrics.widthPixels * widthRatio)); - mWindows.setHeight((int) (metrics.heightPixels * heightRatio)); - } -} diff --git a/baselib/library/src/main/java/com/dhc/library/utils/sys/TimeUtil.java b/baselib/library/src/main/java/com/dhc/library/utils/sys/TimeUtil.java deleted file mode 100644 index f4d981c..0000000 --- a/baselib/library/src/main/java/com/dhc/library/utils/sys/TimeUtil.java +++ /dev/null @@ -1,313 +0,0 @@ -package com.dhc.library.utils.sys; - -import java.math.BigDecimal; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Locale; -import java.util.TimeZone; - -public class TimeUtil { - - public static boolean isEarly(int days, long time) { - return (currentTimeMillis() - time) > (days * 24 * 3600 * 1000); - } - - public static int currentTimeSecond() { - return (int) (System.currentTimeMillis() / 1000); - } - - public static long currentTimeMillis() { - return System.currentTimeMillis(); - } - - public static long[] getTsTimes() { - long[] times = new long[2]; - - Calendar calendar = Calendar.getInstance(); - - times[0] = calendar.getTimeInMillis() / 1000; - - calendar.set(Calendar.HOUR_OF_DAY, 0); - calendar.set(Calendar.MINUTE, 0); - calendar.set(Calendar.SECOND, 0); - - times[1] = calendar.getTimeInMillis() / 1000; - - return times; - } - - public static String getFormatDatetime(int year, int month, int day) { - SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); - return formatter.format(new GregorianCalendar(year, month, day).getTime()); - } - - public static Date getDateFromFormatString(String formatDate) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - try { - return sdf.parse(formatDate); - } catch (ParseException e) { - e.printStackTrace(); - } - - return null; - } - - public static String getNowDatetime() { - SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); - return (formatter.format(new Date())); - } - - public static int getNow() { - return (int) ((new Date()).getTime() / 1000); - } - - public static String getNowDateTime(String format) { - Date date = new Date(); - - SimpleDateFormat df = new SimpleDateFormat(format, Locale.getDefault()); - return df.format(date); - } - - public static String getDateString(long milliseconds) { - return getDateTimeString(milliseconds, "yyyyMMdd"); - } - - - - public static String getTimeString(long milliseconds) { - return getDateTimeString(milliseconds, "HHmmss"); - } - - public static String getBeijingNowTimeString(String format) { - TimeZone timezone = TimeZone.getTimeZone("Asia/Shanghai"); - - Date date = new Date(currentTimeMillis()); - SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault()); - formatter.setTimeZone(timezone); - - GregorianCalendar gregorianCalendar = new GregorianCalendar(); - gregorianCalendar.setTimeZone(timezone); - String prefix = gregorianCalendar.get(Calendar.AM_PM) == Calendar.AM ? "上午" : "下午"; - - return prefix + formatter.format(date); - } - - public static String getBeijingNowTime(String format) { - TimeZone timezone = TimeZone.getTimeZone("Asia/Shanghai"); - - Date date = new Date(currentTimeMillis()); - SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault()); - formatter.setTimeZone(timezone); - - return formatter.format(date); - } - - public static String getDateTimeString(long milliseconds, String format) { - Date date = new Date(milliseconds); - SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault()); - return formatter.format(date); - } - - - public static String getFavoriteCollectTime(long milliseconds) { - String showDataString = ""; - Date today = new Date(); - Date date = new Date(milliseconds); - Date firstDateThisYear = new Date(today.getYear(), 0, 0); - if (!date.before(firstDateThisYear)) { - SimpleDateFormat dateformatter = new SimpleDateFormat("MM-dd", Locale.getDefault()); - showDataString = dateformatter.format(date); - } else { - SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); - showDataString = dateformatter.format(date); - } - return showDataString; - } - - public static String getTimeShowString(long milliseconds, boolean abbreviate) { - String dataString; - String timeStringBy24; - - Date currentTime = new Date(milliseconds); - Date today = new Date(); - Calendar todayStart = Calendar.getInstance(); - todayStart.set(Calendar.HOUR_OF_DAY, 0); - todayStart.set(Calendar.MINUTE, 0); - todayStart.set(Calendar.SECOND, 0); - todayStart.set(Calendar.MILLISECOND, 0); - Date todaybegin = todayStart.getTime(); - Date yesterdaybegin = new Date(todaybegin.getTime() - 3600 * 24 * 1000); - Date preyesterday = new Date(yesterdaybegin.getTime() - 3600 * 24 * 1000); - - if (!currentTime.before(todaybegin)) { - dataString = "今天"; - } else if (!currentTime.before(yesterdaybegin)) { - dataString = "昨天"; - } else if (!currentTime.before(preyesterday)) { - dataString = "前天"; - } else if (isSameWeekDates(currentTime, today)) { - dataString = getWeekOfDate(currentTime); - } else { - SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); - dataString = dateformatter.format(currentTime); - } - - SimpleDateFormat timeformatter24 = new SimpleDateFormat("HH:mm", Locale.getDefault()); - timeStringBy24 = timeformatter24.format(currentTime); - - if (abbreviate) { - if (!currentTime.before(todaybegin)) { - return getTodayTimeBucket(currentTime); - } else { - return dataString; - } - } else { - return dataString + " " + timeStringBy24; - } - } - - /** - * 根据不同时间段,显示不同时间 - * - * @param date - * @return - */ - public static String getTodayTimeBucket(Date date) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - SimpleDateFormat timeformatter0to11 = new SimpleDateFormat("KK:mm", Locale.getDefault()); - SimpleDateFormat timeformatter1to12 = new SimpleDateFormat("hh:mm", Locale.getDefault()); - int hour = calendar.get(Calendar.HOUR_OF_DAY); - if (hour >= 0 && hour < 5) { - return "凌晨 " + timeformatter0to11.format(date); - } else if (hour >= 5 && hour < 12) { - return "上午 " + timeformatter0to11.format(date); - } else if (hour >= 12 && hour < 18) { - return "下午 " + timeformatter1to12.format(date); - } else if (hour >= 18 && hour < 24) { - return "晚上 " + timeformatter1to12.format(date); - } - return ""; - } - - /** - * 根据日期获得星期 - * - * @param date - * @return - */ - public static String getWeekOfDate(Date date) { - String[] weekDaysName = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; - // String[] weekDaysCode = { "0", "1", "2", "3", "4", "5", "6" }; - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1; - return weekDaysName[intWeek]; - } - - public static boolean isSameDay(long time1, long time2) { - return isSameDay(new Date(time1), new Date(time2)); - } - - public static boolean isSameDay(Date date1, Date date2) { - Calendar cal1 = Calendar.getInstance(); - Calendar cal2 = Calendar.getInstance(); - cal1.setTime(date1); - cal2.setTime(date2); - - boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && - cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR); - return sameDay; - } - - /** - * 判断两个日期是否在同一周 - * - * @param date1 - * @param date2 - * @return - */ - public static boolean isSameWeekDates(Date date1, Date date2) { - Calendar cal1 = Calendar.getInstance(); - Calendar cal2 = Calendar.getInstance(); - cal1.setTime(date1); - cal2.setTime(date2); - int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR); - if (0 == subYear) { - if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)) - return true; - } else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) { - // 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周 - if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)) - return true; - } else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) { - if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)) - return true; - } - return false; - } - - public static long getSecondsByMilliseconds(long milliseconds) { - long seconds = new BigDecimal((float) ((float) milliseconds / (float) 1000)).setScale(0, - BigDecimal.ROUND_HALF_UP).intValue(); - // if (seconds == 0) { - // seconds = 1; - // } - return seconds; - } - - public static String secToTime(int time) { - String timeStr = null; - int hour = 0; - int minute = 0; - int second = 0; - if (time <= 0) - return "00:00"; - else { - minute = time / 60; - if (minute < 60) { - second = time % 60; - timeStr = unitFormat(minute) + ":" + unitFormat(second); - } else { - hour = minute / 60; - if (hour > 99) - return "99:59:59"; - minute = minute % 60; - second = time - hour * 3600 - minute * 60; - timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second); - } - } - return timeStr; - } - - public static String unitFormat(int i) { - String retStr = null; - if (i >= 0 && i < 10) - retStr = "0" + Integer.toString(i); - else retStr = "" + i; - return retStr; - } - - public static String getElapseTimeForShow(int milliseconds) { - StringBuilder sb = new StringBuilder(); - int seconds = milliseconds / 1000; - if (seconds < 1) - seconds = 1; - int hour = seconds / (60 * 60); - if (hour != 0) { - sb.append(hour).append("小时"); - } - int minute = (seconds - 60 * 60 * hour) / 60; - if (minute != 0) { - sb.append(minute).append("分"); - } - int second = (seconds - 60 * 60 * hour - 60 * minute); - if (second != 0) { - sb.append(second).append("秒"); - } - return sb.toString(); - } -} diff --git a/baselib/library/src/main/res/anim/fade_in.xml b/baselib/library/src/main/res/anim/fade_in.xml deleted file mode 100644 index cb37f3a..0000000 --- a/baselib/library/src/main/res/anim/fade_in.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - \ No newline at end of file diff --git a/baselib/library/src/main/res/anim/fade_out.xml b/baselib/library/src/main/res/anim/fade_out.xml deleted file mode 100644 index dd7f62a..0000000 --- a/baselib/library/src/main/res/anim/fade_out.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - \ No newline at end of file diff --git a/baselib/library/src/main/res/anim/login_in_below.xml b/baselib/library/src/main/res/anim/login_in_below.xml deleted file mode 100644 index e97a68e..0000000 --- a/baselib/library/src/main/res/anim/login_in_below.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - diff --git a/baselib/library/src/main/res/anim/login_out_below.xml b/baselib/library/src/main/res/anim/login_out_below.xml deleted file mode 100644 index ba9e724..0000000 --- a/baselib/library/src/main/res/anim/login_out_below.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - diff --git a/baselib/library/src/main/res/anim/no_anim.xml b/baselib/library/src/main/res/anim/no_anim.xml deleted file mode 100644 index df908cb..0000000 --- a/baselib/library/src/main/res/anim/no_anim.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - \ No newline at end of file diff --git a/baselib/library/src/main/res/anim/not.xml b/baselib/library/src/main/res/anim/not.xml deleted file mode 100644 index b498961..0000000 --- a/baselib/library/src/main/res/anim/not.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - diff --git a/baselib/library/src/main/res/anim/pop_exit_no_anim.xml b/baselib/library/src/main/res/anim/pop_exit_no_anim.xml deleted file mode 100644 index 94b5f68..0000000 --- a/baselib/library/src/main/res/anim/pop_exit_no_anim.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - \ No newline at end of file diff --git a/baselib/library/src/main/res/anim/step_in_right.xml b/baselib/library/src/main/res/anim/step_in_right.xml deleted file mode 100644 index a2f32c2..0000000 --- a/baselib/library/src/main/res/anim/step_in_right.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - diff --git a/baselib/library/src/main/res/anim/step_out_right.xml b/baselib/library/src/main/res/anim/step_out_right.xml deleted file mode 100644 index 204a8f6..0000000 --- a/baselib/library/src/main/res/anim/step_out_right.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - diff --git a/baselib/library/src/main/res/layout/layout_library_base.xml b/baselib/library/src/main/res/layout/layout_library_base.xml deleted file mode 100644 index 04e3fe1..0000000 --- a/baselib/library/src/main/res/layout/layout_library_base.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - diff --git a/baselib/library/src/main/res/mipmap-xxhdpi/ic_noconnect.png b/baselib/library/src/main/res/mipmap-xxhdpi/ic_noconnect.png deleted file mode 100644 index 016f161fddf3db9346f3bebe5250814a1dd968a8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 14898 zcmV-2I?ct2P)86Y;0_p zWHMm=2lkGKXYN$b7BLVVO_Jd|qZU{29Yh z>0qd#V1HcZhh>grIJTAZ9zF+fj>>#g<{xD)gg<3CDisW%M)%454>CU@vop{4ACvhR znXi`lMVXJuoDP4^a8w!?aLrRPKQHsI3jl(SgEHSms#QxZF_ZBf$&gWnqrAW{L~VfC zW&Z)jtUc2*oOF!eq`xq~L*^!p=^tkVL})CBqs+hnWBH?AAb3Fm?++dU0C;}%^#DM; zMP@yX>7QiP5a9^N9)kgNrkBR=iEV$3Mjc^KBobzMdD+a*&pZFG7ErXdwwlJKCI=w4 zwy*|(@MkhtX^;Fs=4|-$hNE1;P)l0@UZaQ~Jz8I1Hh1UNQp=g)CW*9WCOLWVCEwCtHa5RDlcy)DkO3>Aq#sDZTi-y4H z5I|(1Oz%ojrbxuq5Y{ot>~7W?OOR_U!N%ukrS-0f5=O$G=yEzga%N+nl8}0FFtS zcL=H?t>w`r0W6rfFb&!tP399q@h z-kyyz{e>KtWbp1;nfU*poC|3kNDe&A*>Bv$!2J}R)4VP}DmG0maaAVx=LOC&4>em3 z!BE_>OfcN`f&sHW7BhW)eU9g7b#>KEo$%2TUdnV?0DvPa=dN)-c2FuDr!Jzzhe~sMNVjn>oU*FJSX!Nf@N)Ag8{}Wgf8L{Hmtl5wjzV! zvR4hOut#OJZx-!vczD=cx_HsKzVmu?yVJ!>nc#NCa~lv|4I#(HPm=QTYjPSYnd6O)jhFIk)szEaQF<}YI1~p`oGh%s* zsw`fw@s3*0W6XHm)Fm29so-otdJVSg-cQ>C#`hIIp7(g}%AYSj_S2tkd(j4m3J`d9 zi*Wjr_ulJpdw|CF_~>yM5JKH^yyd)@uFztK+kcn&KK`iN>;cR*xyJO=lq29?I^z{u zy=S#GK(%Z@*!Q9u0`Gx#0L4OLAV3pkwrqg+#p};cP@vaofNIcdfzQ1jnYc;s+fEQ5 zHW+koMzsYDJ9yV(!s!-ZIC+}iUv4r z40y3_-ncO}Gd+DxG}5>nHzU`WlQ}8J%*fOL)r>V21m!Yf1Vsmdae)8t;QuvF4=(&-q|0+@`1V3Mc)mI`ALlOse=}# zAc|SDSTU$x&cC3hcwFYsWS*gRoh=umyPyx8&B(MVmTtAwWV<_e?l^P=e-{B;5DoIU z2w|%j>rnL%0CRTWOsNwz6(|_~f7wHsf&z1n;4`@o?kjb>de5)#5iQi&H!v`AsILzp z>Kg){MbI={Z(?F%+hR~b-lrs~+5~Cd1ip35VE0;&arTxPon+iRDWmfj$%?<3w4^c(l)$%roF~Et~oEqgARdq`B6YdwQFi>Yg-z#(^%;6Z8^|;afbmhTtg%mFuKSwx1L3+Ikw= z@qGh^9DpLWYqVVi{-_A$d*tQM3Lrir+G2Pm9*?$A=z>;VYy+(ofkq5OqsYFo2MZty z!nxU5$FPU%*4|_7p=EV4kI8HnfX<3$85IDo!EWj9?sl#Z%?7H6^Fni|Eu!~Qq4A0& zZ6E*xfwkYu{DaK11jGylRkcjC2viDo1)5i+86o(Ln70V7!*+ zTp*>}cVLLptMGo~mWcU)aifM=dqQJ=79?e7{$XF&b;xC&18w@8TS_#J|%R2H#H*6iJhPYip(fFucyVX&((d?-D80 zW+j3FD=W&vd|u|~WWL?F+dd=Nyi^+TUX>LVRH!DP0D!tW@%IMW5cyE1839C0R(Y)M z(O^MU%GAjfFttMr*H&X+?+xJS@9%fO02>9LL!AfvF!w3Rc)=*a@q5y#J6uTGP2n+& zh)L(My~enK!$lhW8QHj$}h$N z9`8^VnGnF7C=IS$7IaJ4k51NeR&y&f&}z<@3!G!CMXb-WMf0gbAok&lVj5asqJ z9qyyCPUCx&Ua4C&#IN!Ds@?&GLiVi2M7rskT_Y&U77P)t1fWEpp+1qFWRKIwQx!Xot{dSix(&l*xGZ5UWQi z!MrV;6UH_kaSb>KBKtpG95e>Ov=@zAA^jpLjxH*if0gfOrQLaw3+ob%?A3Av148Z( z$@~XWqJC5O&M~YkC<6Ad2>DlKrTvu{sn_NI2LudBa8td~BPY@=w!?~OI(5U|1?l2Rx<^N8Xg^J@vC2iWxxfXtgVgC> zF0?bnGO&vgatEJ&6Afcjv^%kbFYg>z6nt?{iNHK9!nDNI`g+pkNVU9Pm7h@!dIEzM zEB^KC*R!X8GwCoP!iwzGW5>XB zA3)TSGQrP2#no>;&_l+kHPXaw@6ug3R_TgWEwRMku+gMT?Bp}L$Vike=&rlXQi1`z z`E4@)qj5X$oGOq9E^uXiSmsw{{)Q@b-KH8aNa3Xs0a_Np8s+;A(y;QUOaO!kG#(d4 z5Hoq1?A3ge+d-W;gixjoLR(F(Xj7(j&&@cLOTmEqxXZy{8{D_)lKm46?OGbh`N~lZ zJxyRFy_AiyLOf1|(4>0^g!hsfwG;?~=V)L708em*&1JxC_ozwd^uNirP3-h?P?MgX z9tQ}h;i{A=>a&+xD{e4>(4|brk3%D+HY)jO2zWLgv?vokOWZwDu+Xqsf)X%8DivkpEhp$DMXO#^ZWwhG>(5oZSeoNGAw5@LZKO2 zUCp2ZiQ{h&RN#!AUKOi?s}WwIdualTapXb+x@rK7gnrU2LG5-l8G& zoJ&hfDb29Y0&v9`OQcQDQOnlQz^==4!H&_}bd=|qrptG|m|(yUjh$)#WZbyHNCBQA z_?v%9o8TMdjngJex6S}CC?J$FbrBSPE?Nf=S|k7hxsfYnf|rTOeVWUZVP)#$s&vN& zgdZ3}niQxh7EQVW#}&$0A3>3i$Elkhr+#|0uH{0TazWh?=@7c@yrTeZu*?sKBrk00 zc+wPamlIZze>3TNr?2;PVF%Pz59>%EU-`iZZpdWTH#}0B+J z!I-0lxI$onKA{rFtMdfK5NVTch5ZF7SwWhimTs?)P$T@A$uG37n@M0Ge}x9}izd$? ziE0LL_kdk?OLW@-U|Qunx(yUe?rW5D0RZz03)v|X4d6T|Q$1ItdfGr^a@=~T84C71 zVQ&R?#Le(KZR2CEVf&(IS)TGEye1^2aPwH$a&p!IVi;H`?S}<8mDKzpmS0 z2&?$zMV+*=-&xvZEu>EQ(xxNy{4LOK-OL3Ho%E344-#Fi@=%7l6jhoi7MqtG=fuVy2GD^6-J5RUi3SDI1 zlli}7{+#@8M?*_O!hnVlXDMx|fLJ7F>#gKEcCtjpIQAI#B z<>7H^ByH-pJd!JZ1~j}e57AIQou{D;Aw&VD@6&L+TnHud)p1<0)!5bNc7+SiK$6&_ z{A_<`+&IKGqgu<*9O~_LR{hb@Q74y4_c{Bm-j2|-vC4(>=gm>3Ze*|_unN6j?iGv5 zPvq}cn5GApXBPdV$u~av=G^z?h`J9u})9q41w`C#_iG+%kljh zFm53W`Ubs!Mpvg}G?YJS(uHPo9f%nJ(gMOlu|BnK=1&y}24zAt8g*cW_itE5%B%uq zc#7!ecP(MN&(Cd&^W!`K1fJivy-ZoU2O+)u;)M(5_&xVHnkxvP^8a>u?|a1fK2%>{ ze={DBCy{w8ub~P^)TGl8HV6i-u(xi~r7Cr5&o=Gh7B}fq@(TpYf+@dxPQ@OZl)F17 z-I)lU&XFA758%9+nxc-fdkGcwkTCUO<#_8P1M?)-y@HIBk%n$^5+xs|7t(2=s}q1+%|a(-@Z^ZK=Gj-BGZoH3m{>GNn$2>UcSw07OmsjaFec$`-GTQxZb zpekro(ZTZxI(v@f>Ggyi@-P-p*bM)bhVqd-PJk8aH?$4DUrbu$y9_Y%Qw0rME62yj zoyy@TR))&q019fW!Z1z=b2PdrqBbh;h4gic;PnOVad1k|z{`YXRt#Ocw_MN$A=NO> zo@(_n`2Z;5-cO{qrY0))7hPUnjtY=dB_t#68@w~>nRb~;t-;#P1#E!7AGG@Gxaz%& z6X^{n=;3N4C>Hk-7?RWwSGf>q4X9l0h&CGHHF(2&O@3*#HyAtk9_@sM-Tb7wPr=?^ ziIvq`IUGD5!iyDJD}+N(V+{>s0+R2Dv0E+2)W~bEks0xph{1ai&rr$)kOifGdjoTz zOd6PL;=XNTm5)(C0B|t82Zx5twX0X1;sH*FqMdE{(drTn85S;ZVnpk&Q)tFax^Arg ztu-Vj?T zlL#}?w-sPpD3g1TucmPJR9kU~pcY)(Fhv1@()$q~z!m#zv*=bGJt+fZ1)x$75FmY| z7)upugm02AT{G$CIJuO`Tm%?CW_+?ftpSetlyM`;-!^WDyzDZQ?Xs3SwTz_DnEsWO zmDBS08WBFMj>k|})vn9r)c{UiBmo4#wL}}j0bYi{oE9>M4FS3Yfv>h)wf1#T#J~Za z*cqTpCD0Ilqn4cc5N(cA)F6ZO%pBt1H+Gv2?*bqus3GFkXADXk0K<6+U^q;^+2eCC zRtF^3{ZHBm;}!B{L})A?5WzYv0{`CXs;W=P{~r>edz%Pr*UIW@6doztYve65Dsmh4ieJv3*swoFbr`|wNG*ZA4)&f}xV}@Q% zc-^#LMNL55;xT|>fMwB z&C^_E)va3zLnFu9 zs5%UeXi*@YW{B$}ja3YkvL{JXhQFT?%B`^mnguom?RmDPRepS2C zz@?_P_WNSjJo5aRGiRVFkCY|!4t;hU(x>d-~%{=cWw>?V3FSot3D)h*V6)J?zKtn@A zj^KLxUE7gr7`r!b-ZXb6CQ@0on$>E2YQpO3531#82&QiM0Rol2<$RaLuKAuA{9l&m z=aC|UyeR=j1WhC4wK_Q#v)0NCcJBu7(6W(E`Fzn7N!1`(yi72v z5w~cv%FuYV2y&K$Mje#*9FglZi6)tndAmLqOY+(qLcLbS)^QT{2h4O=+90^9l>|Pq<5Abq&Av2>0N&z7>YdVx#B?+pqlrm34)Ftx?~|} zt0II;BH*`0C?^ob7XDsudv>;{B-T@ffP*^ufxyqp1otUo9!_A6{pA8ET(iu>a(+;q z3Axrp|G>Z|jD3{O)C%C5oM>N*t1`H-R-J&SIFW;}q!UMDEt9?oW9QW3>Z7d5~wc$;fl29dma2H|Q1iL%^ukGB#Sp z+e6KI<@pCiqpU%z$orp_Yi>X*07#%)NIL-_ozxLIH$a*N{F?Ht;}AdNt0}xA)WCzL zuzILUW$&j43ib*DdcQMnqm!9XGvsd^_nLI$^oRJx))ja@ZFT`}jcnWR(6{_;u8@~S z5EmefOdbxq34p-Lo>Y2-N2ITVHo@CvUq44c=w>1<@}@VUMq>|&*7PACSTLFtxEh*V?(%%?=hv^UuTSo&m z0MaMEK(!hx;5_hLOb`UfZT~WX@G@O}nU^q2Gg$mx0g;t5Ie-wF6}J-aa`G~1E>jjS z69F+mTMxo{$7MyXYZgW|x{#t+8r;Olr&2eu-OVV^F;DIAB(=r7*;+X}U%N9#+vHWG zz4HXbdI$!0wfHzaMeiX$E`$<6I1oX6gp}xa)DAf}#R~v~0%DZs%1oKqa8WZ+^YSu@ z@HUH4j$EZkb`4R_dm2|eL9=!7e*m+)r^g8kc!^;aehx4^j*@TOQwL7;|yRhmTS`FN|~1O zpiD*sb3&Pr?OL6gGPRm?O7bMNVNyYbeHAq+3oOTekkQg+aAQKQc1sF^0I zHR}ra{aQ(zy7~S&Q(&>VN(KXH5n=^@PmORiPi>&RiO@dWJb4BP@K=~X%- zF3{0{duqzl&Wmz!IYkYlMGn^Q1~6b1_yAp|5Au1wOVnA~1P>dxdfyBDadxz#L|MI0 zYasIs6;0J$# zK=@a>Os7qe)G8A8lvZQ_gH4&VWP0EaU(fcp`BJ6?bD12x1xK%fp90+bA3+o8wF9^=&1m-xKHY%MsDi>#<&UBlmbt`v4eslf17 zx=cS@fPFAUD)hhUCVk!%vG=bnklIzJtGn9~URyWndBC-petz5v!8c$~b8*DX?~EBw8COzuIuDCy?_ zDVHW5Rx}u51OlSTe{1rq*atQH5&?jU96wO6$!^@Jma=pJAi@B5Bnk{eNVG>pHFv{# ziU`c+N|^u#XbBV;uu5TO4$K)hbptVj*6ft&04Y<_qD;Pkz_p=mU?Vxy5E-#kQx0t^ zg2zeii941Zu}0c-Fb^A1D`z+G91~_2GhlZU4EV*6xrmB=AL7cD&&mQX#s4vGlauF5 z;a$*8H%O6~ymQA)OiVbBa8tsL&`v(OdRlv@6%e@ZBmArpKjE(P#352EwR^xe%A~J2 z>EEDCj8tbB2e_g}NSQJ=3|Eg6&IymxoX{p*OFd3msA4W-onEK2q&ppSOXnJ_YvOm> zOq*oaT(7$chHe_k4+YVOfC2P>pSHm-Oh99a-O>(@O2Vpb?S)1H9^8`H|BP*)*c}Jj zqPyaF+>E?`6rFld<5gx?&}t7a6O37C9Z)kTWg;j~2g-DSTDXRkDR7Un*W(23 z)7#hQ+#l=-++S)pU*Thu#;~@fGQ7WBGmz^Eip!)+%asNO7|hs%@P-_@;s#YJjAUe# zqQ67QBa(LgB~TJguf|Fa;e`h#ZdJm=V?Bji-Zv`~;Ei%GLPro^2VHV%Cds+-p-h^t z-A2lkAyVB=o}T0ab0?dIP$~zoIlU`n*i{9KP^kksPv^M0Z_*xU&x1Ar*cXEAp>hVp zG1?0!P4?}WAgQQQfK-ZysSeAk5P@9@4+EgMC0b&h-W~|{nwzl-ZhK2Wv?j-IqfF|D zjL_AInJZ;77G;{_b*nQ|CJ36g^cpic^xD=qhhry+ErI_dD(-h5I~X^)@U2mcb>`r0 z!m$@gnMW%P35LeqV*-W^ z?w0Gc=}yG5Q9zjhq*QVr4ftFFb50xr$$gnAlWK@+3ejXPfKc!|p?CTlHIp5&Ogr+AW|vCS>?RmA)%Oh`PrdwKDu}ke9)IN&1V=ExA!wwn(Ms=3DtJ^4(00OBSIZ~!ROR%Q1 zeJ%%Z0&DyPHHJ9deNXX& zp}hUGrgCa`W~WinXtM}?zX;Azd47)w(xCABUJ;$%+PbMBk*)C{I!gScFt*|SEN;qLD3LhsIDQx)FA@YEOtcG(&Azx zBHR4~16#aQ-eO~@?uXZ|UAyMcu3U-?;1P65d(73bE|Zp#@$vF~f-Ca3_*-OO*{sGZ zyEGEC2d>jdKFZf`(7AGLw|~%5RmZqO9vN|c_b`;LQkJSA+B-TNVZX-yZ$Z=~^_+hPAkMw=iUSC^ zZtco_o`HM+9PbnTx-XT{_YBSOGvk);QLV9Bsvo#iW3^NtY8S>Jy<#f-{WSJEs2$o( zKn{P(E5n!syiIsMboj8lE6rNvRYTzKNVmpo*RNks?PU%Oe$gH4^pX(pKtrG{uQqmzBgdjKS+Fq=7;qa$GeWZ1VjT!4EYXe*m7`&9pF-nGpQt8>7 zR@+>qMA(c2L;32}t7e6iDH_mY&ZbO=K>!eF%L~e+l+0(`tCUIJ_boZkU8f=LMleLE z31ADLG|l^EqQw>V;5L-t`dIdp6#66q;V6ZH!NIC(Ylod(*L9l>fy#Lh`Wz?|a*NKN zJGaH{8bFy&%4?s87Yvk1{(m(D!~PziLGPp{I7LlRyUW+q%5f-P6Q@@#fm96FJW3%Lc2OG)(<6jBt`CwY7hB-xIOq9%nE=r8CvzS!tjSEE;W@3d=;7V6!gz-y@#tfFvFf?jCK^a_u|+~iDpCInOHf3#Wz5gVGY zR~&oB2ew>Pg;sXg|^BVLHU1I;Z z4gmy2^M(QfMFz4_COJk^H;x=V>QE+i=X$ec#h`C*YHa*~sI9Kmm6adMdw(p)T-dLM z^?n6I6Scu#Q5(E&hvysTNG3=Udn{cK^HGxG{=u0PbK%+UM$VRjm2W{>%LcLT>t9oYM0DM`T3Xj8z}Z87?3RY z4&w%r9^msrhW0CfV4{>gikBgm{tl_ns@dHl1<*cUCA~s*k^XIzi5r1B0SI}1@H9F^Gm)^ETKh!hH>CL@xHXmY;pQmpis zsRhv82RZbp+4KTw(yk>Ls=%R!5jNvHJLt5xv`fRr`FXUc);6PBizZhKwb5;wnKlU7 zngV+k@E#-w;ygid2zEKG5ju8wEs^LG(A3B=3uxwUDzx|Wegi`-Y0($BdJdWV3K?(G z{rMDm`j=$>l(s=h3g4!{Ai~`2w%zrnWlYj$!3$bL$k+A&pkM>oTSzkjLa(n|NRj$s zx4`n2!gLCcH8r7pPS@J%Dt7N75;!Y=yJ5<(PutxD2G|21BBw_DpfgV(K-hmvDuSI< zkDGK^`;z^zTQq||7_>qjGz6lO7-0IAEU=>5DYpux#*&?IeN z>*Lc`K-7^kwfIq{h*BmIS_n6aj~Ut)St%3tJd4fY^r&F{s4bL^kGyGVZe@#j+*Z7ZfC`<5kbR>Zr4(>00CO}2p4Je#q0CaHW2(S0R-L; zK-i7jGf^f)vr%jH^5x5BAb;_YRDsZ|Q+X{dh;t{$v!FPMS8bbFy0AP-W zxOvm8iiU8we>M$4KK@?Lo~7S!jAB1tEFBh)EBBH7}_#??Cb>9%yN{CM2q?bFlKj=MF+(l0(XgjU&}pqFXTYgF5TIm8H{ zDReJ{pAo%{GO;fO?x}^HP=f+0f>;xq*3YsuU`)-6R6Uqa<<*} z3mEqOu!R%lWe}}~Q4NFJ$IE1Eh&tL-EkPh_v;dKBE>m1nH(>bt#}uNxKAatia<(Bt zFjP2Ys?AK9v@uBoDN|!s%0w?yF8v{JAJ7m0grgxynF0U-?Epgsai5#z2#6326-t@l zyGOJdu1k@$ev~OrFOyOxpZ7#9%Ct;dZ!H8vIEqG@ z(5t$&rNzk+%0QVE5HV7g=4_NH7Y*U1OfaeePNxuBFl7Q54iX4gO&MjlhF~cDsHZR- zqG0s#v4^jN+ru@grD(EJCTIw_T(#o14`tdQAf~7p27DkE&y>>u7LZcF{&ngP+JdIv#KSkaV_CVh@0UM1p1p<%H zKJ$!u&1+xlfFd9|4CD0=^fuvI*cG_7Pc zoC1W8hQRgTWYT-5zi0M%Ur9)lc6UJN-_BL|Q^qZ5c7zlG8ljdzh?sPLh-P|SPzeK( zb=|-dB~TWNK$)Ozrg;woUZdIu1Sk`pJB5z1%4gUyw~aE%Or>rFQ>K1?AGn{-d{72(%OYJT2JfKo1IBTda7J>|54a`A^(f!k*Fs_7qjcP4_sTIj%+iVEK zz+7{43J@EfW-5VRCIEuTeNJ26%w8tVFT>|LZ}zCtMhJ%88K~xmN_Z$+bDzm?TWXNe zJxEGZYtqs7K)NzDIhoq03_O0f zxlFc(NCoB)sm>mlQ#Ug-)+-?xDsyOGxPRhf)h>e$g8MSPPDwvNXsfIi;ryt_8sOE* zjWT(RYG{aMR{qXPnV9Ac%Ct(#1TRy-{^%-d*L7;XsZ!YxAsC7`M(8zqpV@i;hg|3_ zf^&#TTs0ZCv+630+#xLt=A#`9IriF%o0zFsCdCyZ)nhPZl}vS^5uQ7vGA4T1ad z>kVN60@@F08)r<3Vi3_#hKn|!4c==!fvjB|@G_y~{_6vOT)JFQZTnBpKI_nws^I+x zhScjfGQVQnN+R1hyWMyZC1SdJdYtr&OqDQFJLa&&i>87Nfg%HrJrdOD-E|n;XFRoK zLok&8I6&j}WQnhPn$uSksSsiXhZpGOmtJy!p$2ilfKmM<0r3;klr3P;GBf~Ie}BK} zu>cW7#q2Glpi8I#g04gBVqp6IFbx8>tpE$fhAM6QUuow;MBvVi`Bs*l%{f0c8k= zA`0XQos}|CLu8{& zsSB*EIK|Tfz<|$m+<3YcgRYN@ znMRyIi1IoQnhaY=2Zx57^G=98VAo}GK;R-F-6~6t*Q(<_V}oEU$$p1WGwggsC?HjP zbp2}1tV_J^e*h5B3mTLu%C4R{j5sv}YSv!xvma8FNzOL_4FSr;yeQQkn>@~WE|18c z!gkYujX=02`sq!CnxQg=ZkE~DqwC|k36o>hKnSW62^OvngBO)8HYl7q40x3ur%?-f zc+!tDsj&_~KqbO6C4dOIOtU8hTuCvKxz(X1N;r?-Btcc zglexK|EeSfqeIQG^MTcCl7?mX9$bHp*U!1qgwi53M!$9IR;pyBm)~a?NCUxEP2^!< zzs89mFkoW!N21^oEB65q$Zv|V_gnxFpzW}CW6YGOzg`H2;;hV9C?Lo7;Q9c<)qIRh z-6{&3;p&wu4ppjScb+^3uK86O@SpJlLMfBlDY!fIxb9g~Kv_*qgQyD556Xoy{WB@kg&@jgJ<0VtaRLFoxJ%YtCe#c&ADdjo zF4JzPFEJ1=bCu4UO4xnmP#!W8?C;M;nZ88>{vTxC6J$f=G0<4%2ga?Enk zz0U9N`!auL_MmJ`2!`Sfcs|fl_suf@e3!pl>^nF^UR|)QqPyX=tV@Af!3zk`8>D@s zSq$n#o#q1JO;^#)L=)63$bov2pKDKQu!dkLu7HBFJZjv0n$x>@trv}3bPKd>M_VE_ zKo-=Ns(`V;MFHs>*m#7d_3*L{QDa6)>rjdN3KtQ4op zQ0xH#`i^nCm=@jBQp8rZ0O`}DO`uB+e5|F=&(XGs6C8=X{_#RE6o1^LcLf7gGENj( zBYd4;7%w6McI&%Xr)_hm5`MT447)Q>wc=rN-@i7lyRm%-=bPd=|BYa{S*#mPRon|l z2!>rYsK3P390h*=(zrE=@*Rj_z-xrvX3td0DjR|!9NqycgB@bG=_P?tjgm5`{D5M+ zt)Aatja+(yU_wCcd2;U;%pTPs4Z#qOVhsp50#Qg;fXC!Mf?}9}z{Z>^3i><&bcMqI k91YN=5D2?J{=WbN04mh($ diff --git a/baselib/library/src/main/res/mipmap-xxhdpi/ic_pagenofound.png b/baselib/library/src/main/res/mipmap-xxhdpi/ic_pagenofound.png deleted file mode 100644 index 12a9259e34fcf5205018e90e6bb6dd8d51e99cca..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3812 zcmZ`+c{CK<`&UYcBxRbWOq4X1yfH&z>`Oy~$kw8evF~{qjIBbb$u^U*FJmc;Eo3K4 zXe>i^rm;_UrZ8lF^PcZN-*dk2?~i+*`+V-Re4cyGbIx;L8yo8J^IqWP;Naj#+|f2+ z%Leuu;pSrRMm5HKYyo_(WBJ_F1NGd`#@n7lTT8+jrE{<`R)CM z2A_3#KSG{ivY4Qi&R{zW@u6KaL!g_H#U%hdQ;*zNI0$Tj?gFYuTyw_mR47dqsBFW0 zpjfBF?9T@Bio{FYNx}T&EY*iw2P5&Hf~p2D(pVF-1TO*)VW+#1b2WCg*17k0)4-ys zKP5bv&;uno84eYt)-ql|`u(u6rca3cIdt0Fj3Ttv2}e&ptY zb8h1ov6ZyoO-bq$LNnkI4Lgs%BB<`SsBDi9wjkeDvA8PML~%7Urz^X3xDfo)?`SJU zgL+*pbm<`l^cEj&?@TP}nU%W&E{v8pJF&Yh?6Nj|cSI#WS;D>C7Se}~FUq6eaEGEK z$Rd;~s~uD5$k|mbAA02e8d7*+AB2;Ft@kH&huJKb5l#^>?c_1nG}@wT0Wfb5X;rIe zwO&dRvWWCK@`|Kl09A}h34`~BR784vS}_^B{3|Io`}Yn(;pHPSSSY}m%XylA@^3## z4XS{bRsDAbPf5f{ky}HM<(h? zw<8t_P|kBWELY|FV=j6im+OnMPiU3CTp-w`m)ntA!ABthO3CL`I-lL1gp{ODw=#7M zusqx@V=Z^VnmE5t8P8lNiXG|7T$N23i@2iD6S1q~02$2JLF4-Fg!94Bb21oiAG9^% zm|89I>L1&5i}Itw#0}AjO%*|XqdV7=W#5Eg zaS<*PiRkxnX$8r>T2GYHa~OMGs(-}l+;ccsjlYzXrhRj(`@=^&L9G zie54{<)Fy&JDCQB2Q~MjSRRE7eeA|6Bt*jgiFEZ6Y~NYenahdb?TK>87-YAz5OfwM zyQPbRo_TKC;b=W_@Ie0737T4Q&-3#2qsZ+h$Herx8~Zv0Jgn2%Ty~>^Z)>Kne?^Cm za5W!DrP;H>)+6z+E?Ki|`Ycr+zIB;EefV4QWA z;!3X*ASo_Y-1uz~9Q!TxXOoTQsGdBIGLjP3C;)B^B2UjayIadF`OL~BIqatlo#3p7 zYfc^m5lNzOShb_lG1qMgub8}P>v)X1qC@Dq?W<6asx%0uA#_R6d6;{2;S7tsu@k@A zV?u2oH(DXNx-IU6AoZVs|8f~q%lzX=72hpr+kc)?BL-a#V1S_6Ax88b4X|v(IXN<;%!Hj|E)QO z_KuK!hu(z=+w$dO`cIIazG`1ag^jLVy73y09Y0#Mr`9qmtk^mQ!Th>qxqVwpIW`P@ z`87%NN6Ys^ajm*u^y5_srVO(O22P|C_gr*-gPLk0ffL!W0Wke1m;P#;?&){Oy)6utIb)DK!cwwp5@>I zIISh=@pTMy1ybd;=OYz-vEQvCc4}RZKG-QY8`WA&H9NSKDaKIHsH<{hB%r{y1HiAI34NxpLWPfp}T1&TCN#B&+1Z6UXtk0NA8=KM4H(B)ZE zcnIbbv8fK#Ip;p><&w>CqV)Bn0?2Q>8X^=dBOOfjGej)=$|AF-v|!3NJfa>hHo^h` zq8OnDHz7E`+eU3l$neIfWpuxSlqT~N-7RIbt$$&UAOh-%SyhnKWWHfTr9+W@h4iwr zm7VdjT!F%YH9e1sHpvKu^7aD4H!U7(kNDIZ{Xvn^i4Zop-T zU3&1?lh+VJz??C?s>5B#Kw29T(ov-hRT5_AyM zrMmnosrJSex;=#R$MTX4V!Nz*Y{ptjD5Vn?SV=*JF1)>fV4ZVncrWOK=EF0S0I-8|yaanD!P-?pgW zWw0v*K76^QPD3p><@09f=B~*7gxRor>IPlEhU#+xRDfEd`vMp5$F-Z4`&C1;S!pl$ z-Hh=*9_bWL=@NA1klj?0Sm|W0yXcx3!;GtW`~{VAP#d~;giC$@b9C-)B-hRP)KC-pLy?^#bhn|N1ipT2(;=_k|!(J zpoxUzsXiV*Ymg1WY(9PWqwdI*@VAVhD`l9;Z`2x+vnv)L!HS_+fX?ov0X=)KMSqOb z*V&~L_+wYSz686agQF<;$nCasIaYlj_i(K2o+>Tk7mb5|Dk?m&5@_Sp&)&Sb%NaM^(#osTPT^y$J(2 zD;;y6s1pRgqu{ao2XEZC{R=J#Lv9hyLb2M zloC~CP%(ioPhU|kOgum9t4S5A&KxZNfcU1Gk*aYJm)Mw|c@cO;8S{tVIk`oi!(aa= zU`B-CbV?+a=Tcg&rr6NMd(7u(LwW7VpHGdFRw``5-SoUpnim%o{m50{q%H4OMH|rv z7f*$J2QS!5ohdS^__*F}Y0)3LYX^d;5=mSIT^TF(%k!jk4}~Ra$Am^l6o|wk)QD9W z_b)cp->Ie=~iP+W-In diff --git a/baselib/library/src/main/res/values/styles.xml b/baselib/library/src/main/res/values/styles.xml deleted file mode 100644 index d2d2771..0000000 --- a/baselib/library/src/main/res/values/styles.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/baselib/library/src/test/java/com/fanyu/library/ExampleUnitTest.java b/baselib/library/src/test/java/com/fanyu/library/ExampleUnitTest.java deleted file mode 100644 index af48f1a..0000000 --- a/baselib/library/src/test/java/com/fanyu/library/ExampleUnitTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.fanyu.library; - -import android.util.Log; - -import org.junit.Test; - -import io.reactivex.Observable; -import io.reactivex.ObservableEmitter; -import io.reactivex.ObservableOnSubscribe; -import io.reactivex.Observer; -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.Disposable; -import io.reactivex.functions.Function; -import io.reactivex.schedulers.Schedulers; - -import static org.junit.Assert.assertEquals; - -/** - * Example local unit test, which will execute on the development machine (host). - * - * @see Testing documentation - */ -public class ExampleUnitTest { - private String TAG="1111"; - - @Test - public void addition_isCorrect() throws Exception { - assertEquals(4, 2 + 2); - - - } - - @Test - public void randomTest() { - Observable.create(new ObservableOnSubscribe() { - @Override - public void subscribe(ObservableEmitter e) throws Exception { - Log.e(TAG, "===create: " + Thread.currentThread().getName()); - e.onNext("1"); - } - - }).subscribeOn(AndroidSchedulers.mainThread()) - .observeOn(Schedulers.io()) - .map(new Function() { - @Override - public Integer apply(String s) throws Exception { - Log.e(TAG, "===String -> Integer: " + Thread.currentThread().getName()); - return Integer.valueOf(s); - } - }) - .observeOn(AndroidSchedulers.mainThread()) - .flatMap(new Function>() { - @Override - public Observable apply(final Integer integer) throws Exception { - Log.e(TAG, "===Integer->Observable: " + Thread.currentThread().getName()); - return Observable.create(new ObservableOnSubscribe() { - @Override - public void subscribe(ObservableEmitter e) throws Exception { - Log.e(TAG, "===Observable call: " + Thread.currentThread().getName()); - for (int i = 0; i < integer; i++) { - e.onNext(i + ""); - } - e.onComplete(); - } - }); - } - - }) - .observeOn(Schedulers.io()) - .map(new Function() { - @Override - public Long apply(String s) throws Exception { - Log.e(TAG, "===String->Long: " + Thread.currentThread().getName()); - return Long.parseLong(s); - } - - }) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(new Observer() { - @Override - public void onSubscribe(Disposable d) { - - } - - @Override - public void onNext(Long aLong) { - Log.e(TAG, "===onNext: " + Thread.currentThread().getName()); - } - - @Override - public void onError(Throwable e) { - - } - - @Override - public void onComplete() { - - } - }); - - } - -} \ No newline at end of file diff --git a/baselib/uikit/build.gradle b/baselib/uikit/build.gradle index 8063e15..cb7d72c 100644 --- a/baselib/uikit/build.gradle +++ b/baselib/uikit/build.gradle @@ -59,42 +59,42 @@ dependencies { // exclude group: 'com.android.support', module: 'support-annotations' // }) //test - testApi rootProject.ext.dependencies["junit"] + testCompile rootProject.ext.dependencies["junit"] //ui - api(rootProject.ext.dependencies["appcompat-v7"]) { + compile(rootProject.ext.dependencies["appcompat-v7"]) { exclude module: 'support-annotations' exclude module: 'support-v4' } - api(rootProject.ext.dependencies["support-v4"]) { + compile(rootProject.ext.dependencies["support-v4"]) { exclude module: 'support-annotations' } - api(rootProject.ext.dependencies["design"]) { + compile(rootProject.ext.dependencies["design"]) { exclude module: 'support-annotations' } - api rootProject.ext.dependencies["recyclerview-v7"] - api rootProject.ext.dependencies["palette-v7"] - api(rootProject.ext.dependencies["cardview-v7"]) { + compile rootProject.ext.dependencies["recyclerview-v7"] + compile rootProject.ext.dependencies["palette-v7"] + compile(rootProject.ext.dependencies["cardview-v7"]) { exclude module: 'support-annotations' } - api rootProject.ext.dependencies["percent"] - api 'com.android.support.constraint:constraint-layout:1.0.2' - api rootProject.ext.dependencies["marqueelibrary"] - api( rootProject.ext.dependencies["vlayout"]) { + compile rootProject.ext.dependencies["percent"] + compile 'com.android.support.constraint:constraint-layout:1.0.2' + compile rootProject.ext.dependencies["marqueelibrary"] + compile(rootProject.ext.dependencies["vlayout"]) { transitive = true } - api rootProject.ext.dependencies["zxing"] - api rootProject.ext.dependencies["banner"] - api rootProject.ext.dependencies["ultra-ptr"] - api rootProject.ext.dependencies["flowlayout"] - api rootProject.ext.dependencies["photoview"] - api rootProject.ext.dependencies["PickerView"] - api rootProject.ext.dependencies["switchbutton"] - api rootProject.ext.dependencies["countdownview"] - api rootProject.ext.dependencies["MagicIndicator"] - api rootProject.ext.dependencies["FlycoDialog_Lib"] - api rootProject.ext.dependencies["glide-transformations"] - api rootProject.ext.dependencies["zxing-android-embedded"] - api rootProject.ext.dependencies["circular-progress-button-v7"] - api rootProject.ext.dependencies["BaseRecyclerViewAdapterHelper"] + compile rootProject.ext.dependencies["zxing"] + compile rootProject.ext.dependencies["banner"] + compile rootProject.ext.dependencies["ultra-ptr"] + compile rootProject.ext.dependencies["flowlayout"] + compile rootProject.ext.dependencies["photoview"] + compile rootProject.ext.dependencies["PickerView"] + compile rootProject.ext.dependencies["switchbutton"] + compile rootProject.ext.dependencies["countdownview"] + compile rootProject.ext.dependencies["MagicIndicator"] + compile rootProject.ext.dependencies["FlycoDialog_Lib"] + compile rootProject.ext.dependencies["glide-transformations"] + compile rootProject.ext.dependencies["zxing-android-embedded"] + compile rootProject.ext.dependencies["circular-progress-button-v7"] + compile rootProject.ext.dependencies["BaseRecyclerViewAdapterHelper"] } diff --git a/businesslib/businessComponent/build.gradle b/businesslib/businessComponent/build.gradle index f1abf0d..a226176 100644 --- a/businesslib/businessComponent/build.gradle +++ b/businesslib/businessComponent/build.gradle @@ -1,3 +1,5 @@ +import com.sun.org.apache.xalan.internal.xsltc.cmdline.Compile + apply plugin: 'com.android.library' android { @@ -26,11 +28,11 @@ android { } dependencies { - implementation fileTree(dir: 'libs', include: ['*.jar']) +compile fileTree(dir: 'libs', include: ['*.jar']) - api project(':imageloader') - api project(':library') - api project(':uikit') - api project(':rxbus2') - api project(':timberhelper') + compile project(':imageloader') + compile project(':uikit') + compile 'com.dhc.lib:mvp:1.0.1' + compile 'com.dhc.rxbus:rxbus2:1.0.0' + compile 'com.dhc.timberhelper:timberhelper:1.0.0' } diff --git a/girls/build.gradle b/girls/build.gradle index 5af0e6e..96529ad 100644 --- a/girls/build.gradle +++ b/girls/build.gradle @@ -36,8 +36,8 @@ android { manifest.srcFile 'src/main/release/AndroidManifest.xml' java { exclude 'src/main/debug/**' - exclude '**/debug/**.java' - exclude 'src/main/**/res/layout/activity_debug.xml' +// exclude '**/debug/**.java' +// exclude 'src/main/**/res/layout/activity_debug.xml' } } } @@ -85,7 +85,7 @@ dependencies { testCompile rootProject.ext.dependencies["junit"] - implementation project(':businessComponent') + providedCompile project(':businessComponent') provided rootProject.ext.lib_atlas_core //dagger2的apt注解 diff --git a/girls/src/main/java/com/dhc/flyabbit/gank/ui/GankFragment.java b/girls/src/main/java/com/dhc/flyabbit/gank/ui/GankFragment.java index d5df0c8..5a52204 100644 --- a/girls/src/main/java/com/dhc/flyabbit/gank/ui/GankFragment.java +++ b/girls/src/main/java/com/dhc/flyabbit/gank/ui/GankFragment.java @@ -1,6 +1,7 @@ package com.dhc.flyabbit.gank.ui; import android.os.Bundle; +import android.support.v7.widget.Toolbar; import android.view.View; import com.alibaba.android.arouter.facade.annotation.Route; @@ -48,7 +49,7 @@ private void initTitle() { ToolBarOptions options = new ToolBarOptions() .isNeedNavigate(false).titleString("干货集中营"); // setToolBar(R.id.toolbar, options); - new ToolbarUtil().setToolBar(_mActivity, $(R.id.toolbar),options,false); + new ToolbarUtil().setToolBar(_mActivity, (Toolbar) $(R.id.toolbar),options,false); } diff --git a/home/build.gradle b/home/build.gradle index 2fb9120..3d4cd76 100644 --- a/home/build.gradle +++ b/home/build.gradle @@ -30,20 +30,20 @@ android { resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.1' } } -// sourceSets { -// main { -// if (isApp.toBoolean()) { -// manifest.srcFile 'src/main/debug/AndroidManifest.xml' -// } else { -// manifest.srcFile 'src/main/release/AndroidManifest.xml' -// java { -// exclude 'src/main/debug/**' + sourceSets { + main { + if (isApp.toBoolean()) { + manifest.srcFile 'src/main/debug/AndroidManifest.xml' + } else { + manifest.srcFile 'src/main/release/AndroidManifest.xml' + java { + exclude 'src/main/debug/**' // exclude '**/debug/**.java' // exclude 'src/main/**/res/layout/activity_debug.xml' -// } -// } -// } -// } + } + } + } + } defaultConfig { minSdkVersion rootProject.ext.android.minSdkVersion targetSdkVersion rootProject.ext.android.targetSdkVersion @@ -87,7 +87,7 @@ dependencies { testCompile rootProject.ext.dependencies["junit"] - implementation project(':businessComponent') + providedCompile project(':businessComponent') //dagger2的apt注解 annotationProcessor rootProject.ext.dependencies["dagger-compiler"] diff --git a/my/build.gradle b/my/build.gradle index 8c14226..97be30b 100644 --- a/my/build.gradle +++ b/my/build.gradle @@ -31,20 +31,20 @@ android { resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.1' } } -// sourceSets { -// main { -// if (isApp.toBoolean()) { -// manifest.srcFile 'src/main/debug/AndroidManifest.xml' -// } else { -// manifest.srcFile 'src/main/release/AndroidManifest.xml' -// java { -// exclude 'src/main/debug/**' + sourceSets { + main { + if (isApp.toBoolean()) { + manifest.srcFile 'src/main/debug/AndroidManifest.xml' + } else { + manifest.srcFile 'src/main/release/AndroidManifest.xml' + java { + exclude 'src/main/debug/**' // exclude '**/debug/**.java' // exclude 'src/main/**/res/layout/activity_debug.xml' -// } -// } -// } -// } + } + } + } + } defaultConfig { minSdkVersion rootProject.ext.android.minSdkVersion targetSdkVersion rootProject.ext.android.targetSdkVersion @@ -85,15 +85,15 @@ android { } dependencies { - implementation fileTree(dir: 'libs', include: ['*.jar']) + compile fileTree(dir: 'libs', include: ['*.jar']) - androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', { + androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) - testImplementation rootProject.ext.dependencies["junit"] + testCompile rootProject.ext.dependencies["junit"] - implementation project(':businessComponent') + providedCompile project(':businessComponent') //dagger2的apt注解 annotationProcessor rootProject.ext.dependencies["dagger-compiler"] diff --git a/photoview/build.gradle b/photoview/build.gradle index 730650e..b9297d3 100644 --- a/photoview/build.gradle +++ b/photoview/build.gradle @@ -39,7 +39,8 @@ dependencies { testCompile rootProject.ext.dependencies["junit"] - providedCompile project(':library') + + providedCompile project(':businessComponent') //dagger2的apt注解 annotationProcessor rootProject.ext.dependencies["dagger-compiler"] diff --git a/settings.gradle b/settings.gradle index 5a9bb41..6d7f8ea 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,11 +1,7 @@ -include ':app', ':library', ':imageloader', ':uikit', ':home', ':my', ':girls', ':rxbus2', - ':timberhelper', ':businessComponent' ,':activitygroupcompat', ':photoview' +include ':app', ':imageloader', ':uikit', ':home', ':my', ':girls', ':businessComponent' ,':activitygroupcompat', ':photoview' -project(':library').projectDir = new File('baselib\\library') project(':businessComponent').projectDir = new File('businesslib/businessComponent') -project(':rxbus2').projectDir = new File('baselib/rxbus2') -project(':timberhelper').projectDir = new File('baselib/timberhelper') project(':activitygroupcompat').projectDir = new File('baselib/activitygroupcompat') project(':imageloader').projectDir = new File('baselib/imageloader') project(':uikit').projectDir = new File('baselib/uikit') From 6e287e90d01f809a79f2f3fc092b486cb9e78e9c Mon Sep 17 00:00:00 2001 From: denghc Date: Fri, 30 Mar 2018 13:28:40 +0800 Subject: [PATCH 5/5] update mvp lib --- app/build.gradle | 17 +- .../main/java/com/dhc/flyabbit/app/App.java | 11 +- baselib/imageloader/build.gradle | 4 - baselib/uikit/build.gradle | 8 - .../com/dhc/lib/widget/KairuHouseHeader.java | 150 ------------- build-gradle/.gitignore | 1 - build-gradle/LICENSE | 201 ------------------ build-gradle/build.gradle | 39 ---- build-gradle/gradle.properties | 18 -- .../groovy/com.dd.buildgradle/ComBuild.groovy | 173 --------------- .../ComCodeTransform.groovy | 182 ---------------- .../com.dd.buildgradle/ConvertUtils.groovy | 59 ----- .../exten/ComExtension.groovy | 18 -- .../com.dd.comgradle.properties | 1 - build.gradle | 5 +- businesslib/businessComponent/build.gradle | 2 +- girls/build.gradle | 4 - gradle.properties | 14 +- home/build.gradle | 4 - my/build.gradle | 2 +- 20 files changed, 25 insertions(+), 888 deletions(-) delete mode 100644 baselib/uikit/src/main/java/com/dhc/lib/widget/KairuHouseHeader.java delete mode 100644 build-gradle/.gitignore delete mode 100644 build-gradle/LICENSE delete mode 100644 build-gradle/build.gradle delete mode 100644 build-gradle/gradle.properties delete mode 100644 build-gradle/src/main/groovy/com.dd.buildgradle/ComBuild.groovy delete mode 100644 build-gradle/src/main/groovy/com.dd.buildgradle/ComCodeTransform.groovy delete mode 100644 build-gradle/src/main/groovy/com.dd.buildgradle/ConvertUtils.groovy delete mode 100644 build-gradle/src/main/groovy/com.dd.buildgradle/exten/ComExtension.groovy delete mode 100644 build-gradle/src/main/resources/META-INF/gradle-plugins/com.dd.comgradle.properties diff --git a/app/build.gradle b/app/build.gradle index 25e71f7..7b038f4 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -32,6 +32,7 @@ android { } } + multiDexEnabled true testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { @@ -43,7 +44,12 @@ android { proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } + debug { + ndk { + abiFilters "x86","armeabi" + } + } } @@ -69,13 +75,6 @@ android { // } -// compileOptions { -// -// sourceCompatibility JavaVersion.VERSION_1_8 -// -// targetCompatibility JavaVersion.VERSION_1_8 -// -// } dexOptions { jumboMode true //jenkins上使用有问题 @@ -110,6 +109,7 @@ atlas { // preLaunch = 'com.taobao.demo.DemoPreLaunch' classInject false // dataBindingBundles = ['com.taobao.databindbundle'] + autoPackageId } manifestOptions { @@ -149,11 +149,10 @@ dependencies { //阿里的Arouter的注解 annotationProcessor rootProject.ext.dependencies["arouter-compiler"] compile project(':businessComponent') - + compile project(':activitygroupcompat') bundleCompile project(':my') bundleCompile project(':home') bundleCompile project(':girls') bundleCompile project(':photoview') - compile project(':activitygroupcompat') } diff --git a/app/src/main/java/com/dhc/flyabbit/app/App.java b/app/src/main/java/com/dhc/flyabbit/app/App.java index 9eabf76..0a0b937 100644 --- a/app/src/main/java/com/dhc/flyabbit/app/App.java +++ b/app/src/main/java/com/dhc/flyabbit/app/App.java @@ -7,6 +7,7 @@ import android.content.res.Configuration; import android.graphics.Color; import android.support.annotation.NonNull; +import android.support.multidex.MultiDex; import android.support.v7.app.AppCompatDelegate; import android.taobao.atlas.bundleInfo.AtlasBundleInfoManager; import android.taobao.atlas.framework.Atlas; @@ -19,6 +20,7 @@ import com.alibaba.android.arouter.launcher.ARouter; import com.dhc.businesscomponent.Constants; import com.dhc.businesscomponent.data.LoginInfoBean; +import com.dhc.flyabbit.di.component.DaggerHActivityComponent; import com.dhc.flyabbit.presenter.DownLoadPresenter; import com.dhc.flyabbit.presenter.contract.IDownLoadContract; import com.dhc.lib.imageload.ImageLoaderManager; @@ -62,6 +64,7 @@ public static synchronized BaseApplication getInstance() { @Inject DownLoadPresenter downLoadPresenter; + static { AppCompatDelegate.setDefaultNightMode( AppCompatDelegate.MODE_NIGHT_NO); @@ -78,6 +81,9 @@ public void onCreate() { if (mApplicationLikeMoudle3!=null) AsLibUtil.addAsLIbChild(mApplicationLikeMoudle3); AsLibUtil.doCreateAsLibrary(this); + DaggerHActivityComponent.builder() + .appComponent(getAppComponent()) + .build().inject(this); if (downLoadPresenter != null) downLoadPresenter.attachView(this); // https://bundle-1253245619.cos.ap-guangzhou.myqcloud.com/libcom_dhc_filyabbit.so @@ -212,5 +218,8 @@ public void showError(String code, String msg) { public LoginInfoBean provideAccount(String accountJson) { return new GsonBuilder().create().fromJson(accountJson, LoginInfoBean.class); } - + protected void attachBaseContext(Context base) { + super.attachBaseContext(base); + MultiDex.install(this); + } } diff --git a/baselib/imageloader/build.gradle b/baselib/imageloader/build.gradle index cbde468..98288b5 100644 --- a/baselib/imageloader/build.gradle +++ b/baselib/imageloader/build.gradle @@ -22,10 +22,6 @@ android { proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } -// compileOptions { -// sourceCompatibility JavaVersion.VERSION_1_8 -// targetCompatibility JavaVersion.VERSION_1_8 -// } } dependencies { diff --git a/baselib/uikit/build.gradle b/baselib/uikit/build.gradle index cb7d72c..5953ae4 100644 --- a/baselib/uikit/build.gradle +++ b/baselib/uikit/build.gradle @@ -1,5 +1,4 @@ apply plugin: 'com.android.library' -apply plugin: 'me.tatarka.retrolambda' android { compileSdkVersion rootProject.ext.android.compileSdkVersion @@ -44,13 +43,6 @@ android { aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false -// compileOptions { -// sourceCompatibility JavaVersion.VERSION_1_8 -// targetCompatibility JavaVersion.VERSION_1_8 -// } -// retrolambda { -// javaVersion JavaVersion.VERSION_1_7 -// } } dependencies { diff --git a/baselib/uikit/src/main/java/com/dhc/lib/widget/KairuHouseHeader.java b/baselib/uikit/src/main/java/com/dhc/lib/widget/KairuHouseHeader.java deleted file mode 100644 index 67be593..0000000 --- a/baselib/uikit/src/main/java/com/dhc/lib/widget/KairuHouseHeader.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.dhc.lib.widget; - -import android.content.Context; -import android.content.res.TypedArray; -import android.util.AttributeSet; -import android.view.LayoutInflater; -import android.view.View; -import android.view.animation.LinearInterpolator; -import android.view.animation.RotateAnimation; -import android.widget.FrameLayout; - - -import com.dhc.lib.uikit.R; - -import in.srain.cube.views.ptr.PtrFrameLayout; -import in.srain.cube.views.ptr.PtrUIHandler; -import in.srain.cube.views.ptr.indicator.PtrIndicator; - -/** - * 创建者 邓浩宸 - * 创建时间 2016/9/2 9:28 - * 描述 ${recycle刷新头部} - *

- * 更新者 $Author$ - * 更新时间 $Date$ - * 更新描述 ${TODO} - */ -public class KairuHouseHeader extends FrameLayout implements PtrUIHandler { - private int mRotateAniTime = 100; - private RotateAnimation mFlipAnimation; - private RotateAnimation mReverseFlipAnimation; - private View mRotateView; - private View mProgressBar; - - - public KairuHouseHeader(Context context) { - super(context); - initViews(null); - } - - public KairuHouseHeader(Context context, AttributeSet attrs) { - super(context, attrs); - initViews(attrs); - } - - public KairuHouseHeader(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - initViews(attrs); - } - - protected void initViews(AttributeSet attrs) { - TypedArray arr = getContext().obtainStyledAttributes(attrs, R.styleable.KaiRuPtrClassicHeader, 0, 0); - if (arr != null) { - mRotateAniTime = arr.getInt(R.styleable.KaiRuPtrClassicHeader_kairu_ptr_rotate_ani_time, mRotateAniTime); - } - buildAnimation(); - View header = LayoutInflater.from(getContext()).inflate(R.layout.layout_cube_ptr_default_header, this); - - mRotateView = header.findViewById(R.id.ptr_classic_header_rotate_view); - - mProgressBar = header.findViewById(R.id.ptr_classic_header_rotate_view_progressbar); - - resetView(); - } - - @Override - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - } - - - - private void buildAnimation() { - mFlipAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); - mFlipAnimation.setInterpolator(new LinearInterpolator()); - mFlipAnimation.setDuration(mRotateAniTime); - mFlipAnimation.setFillAfter(true); - - mReverseFlipAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); - mReverseFlipAnimation.setInterpolator(new LinearInterpolator()); - mReverseFlipAnimation.setDuration(mRotateAniTime); - mReverseFlipAnimation.setFillAfter(true); - } - - private void resetView() { - hideRotateView(); - mProgressBar.setVisibility(INVISIBLE); - } - - private void hideRotateView() { - mRotateView.clearAnimation(); - mRotateView.setVisibility(INVISIBLE); - } - - @Override - public void onUIReset(PtrFrameLayout frame) { - resetView(); - } - - @Override - public void onUIRefreshPrepare(PtrFrameLayout frame) { - - - mProgressBar.setVisibility(INVISIBLE); - - mRotateView.setVisibility(VISIBLE); - } - - @Override - public void onUIRefreshBegin(PtrFrameLayout frame) { - hideRotateView(); - mProgressBar.setVisibility(VISIBLE); - - } - - @Override - public void onUIRefreshComplete(PtrFrameLayout frame) { - - hideRotateView(); - mProgressBar.setVisibility(INVISIBLE); - } - - - - @Override - public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) { - - final int mOffsetToRefresh = frame.getOffsetToRefresh(); - final int currentPos = ptrIndicator.getCurrentPosY(); - final int lastPos = ptrIndicator.getLastPosY(); - - if (currentPos < mOffsetToRefresh && lastPos >= mOffsetToRefresh) { - if (isUnderTouch && status == PtrFrameLayout.PTR_STATUS_PREPARE) { - if (mRotateView != null) { - mRotateView.clearAnimation(); - mRotateView.startAnimation(mReverseFlipAnimation); - } - } - } else if (currentPos > mOffsetToRefresh && lastPos <= mOffsetToRefresh) { - if (isUnderTouch && status == PtrFrameLayout.PTR_STATUS_PREPARE) { - if (mRotateView != null) { - mRotateView.clearAnimation(); - mRotateView.startAnimation(mFlipAnimation); - } - } - } - } - - -} diff --git a/build-gradle/.gitignore b/build-gradle/.gitignore deleted file mode 100644 index 796b96d..0000000 --- a/build-gradle/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/build-gradle/LICENSE b/build-gradle/LICENSE deleted file mode 100644 index 716855a..0000000 --- a/build-gradle/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2017 Luojilab - - 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. \ No newline at end of file diff --git a/build-gradle/build.gradle b/build-gradle/build.gradle deleted file mode 100644 index 2591cc0..0000000 --- a/build-gradle/build.gradle +++ /dev/null @@ -1,39 +0,0 @@ -apply plugin: 'groovy' -apply plugin: 'maven' -//apply from: '../maven.gradle' -//apply plugin: 'com.novoda.bintray-release'//添加 -dependencies { - compile "com.android.tools.build:gradle:3.0.1" - compile group: 'org.javassist', name: 'javassist', version: '3.20.0-GA' - //gradle sdk - compile gradleApi() - //groovy sdk - compile localGroovy() -} - - -//这是上传jcenter使用,不用关心 -//publish { -// userOrg = 'chengzichen'//bintray.com用户名 -// groupId = 'com.dhc.component'//jcenter上的路径 -// artifactId = 'component-plugin'//项目名称 -// publishVersion = '1.0.0'//版本号 -// desc = 'Oh hi, this is component , show android-component-plugin'//描述,不重要 -// website = 'https://github.com/chengzichen/Flyabbit'//网站,不重要 -//} - - -//本地上传 -//uploadArchives { -// configuration = configurations.archives -// repositories { -// mavenDeployer { -// repository(url: 'file:\\C:\\Android\\gradle\\m2repository') -// pom.project { -// version"1.0.0"//版本号 -// artifactId "component-plugin" -// groupId 'com.dhc.component' -// } -// } -// } -//} diff --git a/build-gradle/gradle.properties b/build-gradle/gradle.properties deleted file mode 100644 index a1ef27f..0000000 --- a/build-gradle/gradle.properties +++ /dev/null @@ -1,18 +0,0 @@ -MAVEN_URL= http://192.168.50.232:8081/nexus/content/repositories/KrAndroidMy/ -MAVEN_SNAPSHOT_URL = http://192.168.50.232:8081/nexus/content/repositories/KrAndroidMy-snapshot/ -#对应maven的groupId值 -GROUP=com.dhc.component -#登录nexus oss的用户名 -NEXUS_USERNAME=haochen -#登录nexus oss的密码 -NEXUS_PASSWORD= -# groupid -GROUP_ID =com.dhc.component -# type -TYPE = jar -# description -DESCRIPTION = dependences lib -#artifactId -ARTIFACT_ID = component-plugin -#archives file -ARCHIVES_FILE = component-plugin.jar \ No newline at end of file diff --git a/build-gradle/src/main/groovy/com.dd.buildgradle/ComBuild.groovy b/build-gradle/src/main/groovy/com.dd.buildgradle/ComBuild.groovy deleted file mode 100644 index 8714f0e..0000000 --- a/build-gradle/src/main/groovy/com.dd.buildgradle/ComBuild.groovy +++ /dev/null @@ -1,173 +0,0 @@ -package com.dd.buildgradle - -import com.dd.buildgradle.exten.ComExtension -import org.gradle.api.Plugin -import org.gradle.api.Project - -class ComBuild implements Plugin { - - //默认是app,直接运行assembleRelease的时候,等同于运行app:assembleRelease - String compilemodule = "app" - - void apply(Project project) { - project.extensions.create('combuild', ComExtension) - - String taskNames = project.gradle.startParameter.taskNames.toString() - System.out.println("taskNames is " + taskNames) - String module = project.path.replace(":", "") - System.out.println("current module is " + module) - AssembleTask assembleTask = getTaskInfo(project.gradle.startParameter.taskNames) - if (assembleTask.isAssemble) { - fetchMainModulename(project, assembleTask) - System.out.println("compilemodule is " + compilemodule) - } - - if (!project.hasProperty("isRunAlone")) { - throw new RuntimeException("you should set isRunAlone in " + module + "'s gradle.properties") - } - - //对于isRunAlone==true的情况需要根据实际情况修改其值, - // 但如果是false,则不用修改 - boolean isRunAlone = Boolean.parseBoolean((project.properties.get("isRunAlone"))) - String mainmodulename = project.rootProject.property("mainmodulename") - if (isRunAlone && assembleTask.isAssemble) { - //对于要编译的组件和主项目,isRunAlone修改为true,其他组件都强制修改为false - //这就意味着组件不能引用主项目,这在层级结构里面也是这么规定的 - if (module.equals(compilemodule) || module.equals(mainmodulename)) { - isRunAlone = true - } else { - isRunAlone = false - } - } - project.setProperty("isRunAlone", isRunAlone) - - //根据配置添加各种组件依赖,并且自动化生成组件加载代码 - if (isRunAlone) { - project.apply plugin: 'com.android.application' - if (!module.equals(mainmodulename)) { - project.android.sourceSets { - main { - manifest.srcFile 'src/main/debug/AndroidManifest.xml' - } - } - } - System.out.println("apply plugin is " + 'com.android.application') - if (assembleTask.isAssemble && module.equals(compilemodule)) { - compileComponents(assembleTask, project) - project.android.registerTransform(new ComCodeTransform(project)) - } - } else { - project.apply plugin: 'com.android.library' - if (!module.equals(mainmodulename)) { - project.android.sourceSets { - main { - manifest.srcFile 'src/main/release/AndroidManifest.xml' - java { - exclude 'src/main/debug/**' - exclude '**/debug/**.java' - exclude 'src/main/**/res/layout/activity_debug.xml' - } - } - } - } - System.out.println("apply plugin is " + 'com.android.library') - } - - } - - /** - * 根据当前的task,获取要运行的组件,规则如下: - * assembleRelease ---app - * app:assembleRelease :app:assembleRelease ---app - * sharecomponent:assembleRelease :sharecomponent:assembleRelease ---sharecomponent - * @param assembleTask - */ - private void fetchMainModulename(Project project, AssembleTask assembleTask) { - if (!project.rootProject.hasProperty("mainmodulename")) { - throw new RuntimeException("you should set compilemodule in rootproject's gradle.properties") - } - - if (assembleTask.modules.size() > 0 && assembleTask.modules.get(0) != null - && assembleTask.modules.get(0).trim().length() > 0 - && !assembleTask.modules.get(0).equals("all")) { - compilemodule = assembleTask.modules.get(0) - - } else { - compilemodule = project.rootProject.property("mainmodulename") - } - if (compilemodule == null || compilemodule.trim().length() <= 0) { - compilemodule = "app" - } - } - - private AssembleTask getTaskInfo(List taskNames) { - AssembleTask assembleTask = new AssembleTask() - for (String task : taskNames) { - if (task.toUpperCase().contains("ASSEMBLE") - || task.contains("aR") - || task.toUpperCase().contains("TINKER") - || task.toUpperCase().contains("INSTALL") - || task.toUpperCase().contains("RESGUARD")) { - if (task.toUpperCase().contains("DEBUG")) { - assembleTask.isDebug = true - } - assembleTask.isAssemble = true - String[] strs = task.split(":") - assembleTask.modules.add(strs.length > 1 ? strs[strs.length - 2] : "all") - break - } - } - return assembleTask - } - - /** - * 自动添加依赖,只在运行assemble任务的才会添加依赖,因此在开发期间组件之间是完全感知不到的,这是做到完全隔离的关键 - * 支持两种语法:module或者groupId:artifactId:version(@aar),前者之间引用module工程,后者使用maven中已经发布的aar - * @param assembleTask - * @param project - */ - private void compileComponents(AssembleTask assembleTask, Project project) { - String components - if (assembleTask.isDebug) { - components = (String) project.properties.get("debugComponent") - } else { - components = (String) project.properties.get("compileComponent") - } - - if (components == null || components.length() == 0) { - System.out.println("there is no add dependencies ") - return - } - String[] compileComponents = components.split(",") - if (compileComponents == null || compileComponents.length == 0) { - System.out.println("there is no add dependencies ") - return - } - for (String str : compileComponents) { - System.out.println("comp is " + str) - if (str.contains(":")) { - /** - * 示例语法:groupId:artifactId:version(@aar) - * compileComponent=com.luojilab.reader:readercomponent:1.0.0 - * 注意,前提是已经将组件aar文件发布到maven上,并配置了相应的repositories - */ - project.dependencies.add("compile", str) - System.out.println("add dependencies lib : " + str) - } else { - /** - * 示例语法:module - * compileComponent=readercomponent,sharecomponent - */ - project.dependencies.add("compile", project.project(':' + str)) - System.out.println("add dependencies project : " + str) - } - } - } - - private class AssembleTask { - boolean isAssemble = false - boolean isDebug = false - List modules = new ArrayList<>() - } - -} \ No newline at end of file diff --git a/build-gradle/src/main/groovy/com.dd.buildgradle/ComCodeTransform.groovy b/build-gradle/src/main/groovy/com.dd.buildgradle/ComCodeTransform.groovy deleted file mode 100644 index d0e9607..0000000 --- a/build-gradle/src/main/groovy/com.dd.buildgradle/ComCodeTransform.groovy +++ /dev/null @@ -1,182 +0,0 @@ -package com.dd.buildgradle - -import com.android.build.api.transform.* -import com.android.build.gradle.internal.pipeline.TransformManager -import javassist.* -import org.apache.commons.codec.digest.DigestUtils -import org.apache.commons.io.FileUtils -import org.gradle.api.Project - -class ComCodeTransform extends Transform { - - private Project project - ClassPool classPool - String applicationName - - ComCodeTransform(Project project) { - this.project = project - } - - @Override - void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException { - getRealApplicationName(transformInvocation.getInputs()) - classPool = new ClassPool() - project.android.bootClasspath.each { - classPool.appendClassPath((String) it.absolutePath) - } - def box = ConvertUtils.toCtClasses(transformInvocation.getInputs(), classPool) - - //要收集的application,一般情况下只有一个 - List applications = new ArrayList<>() - //要收集的applicationlikes,一般情况下有几个组件就有几个applicationlike - List activators = new ArrayList<>() - - for (CtClass ctClass : box) { - if (isApplication(ctClass)) { - applications.add(ctClass) - continue - } - if (isActivator(ctClass)) { - activators.add(ctClass) - } - } - for (CtClass ctClass : applications) { - System.out.println("application is " + ctClass.getName()) - } - for (CtClass ctClass : activators) { - System.out.println("applicationlike is " + ctClass.getName()) - } - - transformInvocation.inputs.each { TransformInput input -> - //对类型为jar文件的input进行遍历 - input.jarInputs.each { JarInput jarInput -> - //jar文件一般是第三方依赖库jar文件 - // 重命名输出文件(同目录copyFile会冲突) - def jarName = jarInput.name - def md5Name = DigestUtils.md5Hex(jarInput.file.getAbsolutePath()) - if (jarName.endsWith(".jar")) { - jarName = jarName.substring(0, jarName.length() - 4) - } - //生成输出路径 - def dest = transformInvocation.outputProvider.getContentLocation(jarName + md5Name, - jarInput.contentTypes, jarInput.scopes, Format.JAR) - //将输入内容复制到输出 - FileUtils.copyFile(jarInput.file, dest) - - } - //对类型为“文件夹”的input进行遍历 - input.directoryInputs.each { DirectoryInput directoryInput -> - boolean isRegisterCompoAuto = project.extensions.combuild.isRegisterCompoAuto - if (isRegisterCompoAuto) { - String fileName = directoryInput.file.absolutePath - File dir = new File(fileName) - dir.eachFileRecurse { File file -> - String filePath = file.absolutePath - String classNameTemp = filePath.replace(fileName, "") - .replace("\\", ".") - .replace("/", ".") - if (classNameTemp.endsWith(".class")) { - String className = classNameTemp.substring(1, classNameTemp.length() - 6) - if (className.equals(applicationName)) { - injectApplicationCode(applications.get(0), activators, fileName) - } - } - } - } - def dest = transformInvocation.outputProvider.getContentLocation(directoryInput.name, - directoryInput.contentTypes, - directoryInput.scopes, Format.DIRECTORY) - // 将input的目录复制到output指定目录 - FileUtils.copyDirectory(directoryInput.file, dest) - } - } - } - - - private void getRealApplicationName(Collection inputs) { - applicationName = project.extensions.combuild.applicationName - if (applicationName == null || applicationName.isEmpty()) { - throw new RuntimeException("you should set applicationName in combuild") - } - } - - - private void injectApplicationCode(CtClass ctClassApplication, List activators, String patch) { - System.out.println("injectApplicationCode begin") - ctClassApplication.defrost() - try { - CtMethod attachBaseContextMethod = ctClassApplication.getDeclaredMethod("onCreate", null) - attachBaseContextMethod.insertAfter(getAutoLoadComCode(activators)) - } catch (CannotCompileException | NotFoundException e) { - StringBuilder methodBody = new StringBuilder() - methodBody.append("protected void onCreate() {") - methodBody.append("super.onCreate();") - methodBody. - append(getAutoLoadComCode(activators)) - methodBody.append("}") - ctClassApplication.addMethod(CtMethod.make(methodBody.toString(), ctClassApplication)) - } catch (Exception e) { - - } - ctClassApplication.writeFile(patch) - ctClassApplication.detach() - - System.out.println("injectApplicationCode success ") - } - - private String getAutoLoadComCode(List activators) { - StringBuilder autoLoadComCode = new StringBuilder() - for (CtClass ctClass : activators) { - autoLoadComCode.append("new " + ctClass.getName() + "()" + ".onCreate();") - } - - return autoLoadComCode.toString() - } - - - private boolean isApplication(CtClass ctClass) { - try { - if (applicationName != null && applicationName.equals(ctClass.getName())) { - return true - } - } catch (Exception e) { - println "class not found exception class name: " + ctClass.getName() - } - return false - } - - private boolean isActivator(CtClass ctClass) { - try { - for (CtClass ctClassInter : ctClass.getInterfaces()) { - if ("com.luojilab.component.componentlib.applicationlike.IApplicationLike".equals(ctClassInter.name)) { - return true - } - } - } catch (Exception e) { - println "class not found exception class name: " + ctClass.getName() - } - - return false - } - - @Override - String getName() { - return "ComponentCode" - } - - @Override - Set getInputTypes() { - return TransformManager.CONTENT_CLASS - } - - @Override - Set getScopes() { - return TransformManager.SCOPE_FULL_PROJECT - } - - @Override - boolean isIncremental() { - return false - } - -} \ No newline at end of file diff --git a/build-gradle/src/main/groovy/com.dd.buildgradle/ConvertUtils.groovy b/build-gradle/src/main/groovy/com.dd.buildgradle/ConvertUtils.groovy deleted file mode 100644 index cd06dbe..0000000 --- a/build-gradle/src/main/groovy/com.dd.buildgradle/ConvertUtils.groovy +++ /dev/null @@ -1,59 +0,0 @@ -package com.dd.buildgradle - -import com.android.SdkConstants -import com.android.build.api.transform.TransformInput -import javassist.ClassPool -import javassist.CtClass - -import java.util.jar.JarEntry -import java.util.jar.JarFile -import java.util.regex.Matcher - -class ConvertUtils { - static List toCtClasses(Collection inputs, ClassPool classPool) { - List classNames = new ArrayList<>() - List allClass = new ArrayList<>() - inputs.each { - it.directoryInputs.each { - def dirPath = it.file.absolutePath - classPool.insertClassPath(it.file.absolutePath) - org.apache.commons.io.FileUtils.listFiles(it.file, null, true).each { - if (it.absolutePath.endsWith(SdkConstants.DOT_CLASS)) { - def className = it.absolutePath.substring(dirPath.length() + 1, it.absolutePath.length() - SdkConstants.DOT_CLASS.length()).replaceAll(Matcher.quoteReplacement(File.separator), '.') - if (classNames.contains(className)) { - throw new RuntimeException("You have duplicate classes with the same name : " + className + " please remove duplicate classes ") - } - classNames.add(className) - } - } - } - - it.jarInputs.each { - classPool.insertClassPath(it.file.absolutePath) - def jarFile = new JarFile(it.file) - Enumeration classes = jarFile.entries() - while (classes.hasMoreElements()) { - JarEntry libClass = classes.nextElement() - String className = libClass.getName() - if (className.endsWith(SdkConstants.DOT_CLASS)) { - className = className.substring(0, className.length() - SdkConstants.DOT_CLASS.length()).replaceAll('/', '.') - if (classNames.contains(className)) { - throw new RuntimeException("You have duplicate classes with the same name : " + className + " please remove duplicate classes ") - } - classNames.add(className) - } - } - } - } - classNames.each { - try { - allClass.add(classPool.get(it)) - } catch (javassist.NotFoundException e) { - println "class not found exception class name: $it " - } - } - return allClass - } - - -} \ No newline at end of file diff --git a/build-gradle/src/main/groovy/com.dd.buildgradle/exten/ComExtension.groovy b/build-gradle/src/main/groovy/com.dd.buildgradle/exten/ComExtension.groovy deleted file mode 100644 index d92ee1c..0000000 --- a/build-gradle/src/main/groovy/com.dd.buildgradle/exten/ComExtension.groovy +++ /dev/null @@ -1,18 +0,0 @@ -package com.dd.buildgradle.exten - -public class ComExtension { - - /** - * 是否自动注册组件,true则会使用字节码插入的方式自动注册代码 - * false的话,需要手动使用反射的方式来注册 - */ - boolean isRegisterCompoAuto = false; - - /** - * 当前组件的applicationName,用于字节码插入。 - * 当isRegisterCompoAuto==true的时候是必须的 - */ - String applicationName - - -} \ No newline at end of file diff --git a/build-gradle/src/main/resources/META-INF/gradle-plugins/com.dd.comgradle.properties b/build-gradle/src/main/resources/META-INF/gradle-plugins/com.dd.comgradle.properties deleted file mode 100644 index 5b3471c..0000000 --- a/build-gradle/src/main/resources/META-INF/gradle-plugins/com.dd.comgradle.properties +++ /dev/null @@ -1 +0,0 @@ -implementation-class=com.dd.buildgradle.ComBuild \ No newline at end of file diff --git a/build.gradle b/build.gradle index 8297990..de05b2d 100644 --- a/build.gradle +++ b/build.gradle @@ -1,4 +1,3 @@ -// Top-level build file where you can add configuration options common to all sub-projects/modules. apply from: "version.gradle" buildscript { repositories { @@ -20,11 +19,9 @@ buildscript { dependencies { // classpath 'com.android.tools.build:gradle:3.0.1' classpath "com.taobao.android:atlasplugin:2.3.3.rc41" - classpath 'me.tatarka:gradle-retrolambda:3.2.5' +// classpath group: 'me.tatarka', name: 'gradle-retrolambda', version: '3.7.0' // classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' // classpath 'com.novoda:bintray-release:0.3.4' - // NOTE: Do not place your application dependencies here; they belong - // in the individual module build.gradle files } } diff --git a/businesslib/businessComponent/build.gradle b/businesslib/businessComponent/build.gradle index a226176..54f2455 100644 --- a/businesslib/businessComponent/build.gradle +++ b/businesslib/businessComponent/build.gradle @@ -32,7 +32,7 @@ compile fileTree(dir: 'libs', include: ['*.jar']) compile project(':imageloader') compile project(':uikit') - compile 'com.dhc.lib:mvp:1.0.1' + compile 'com.dhc.lib:mvp:1.0.3' compile 'com.dhc.rxbus:rxbus2:1.0.0' compile 'com.dhc.timberhelper:timberhelper:1.0.0' } diff --git a/girls/build.gradle b/girls/build.gradle index 96529ad..4c03e81 100644 --- a/girls/build.gradle +++ b/girls/build.gradle @@ -68,10 +68,6 @@ android { abortOnError false } -// compileOptions { -// sourceCompatibility JavaVersion.VERSION_1_8 -// targetCompatibility JavaVersion.VERSION_1_8 -// } aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false } diff --git a/gradle.properties b/gradle.properties index 6dd3212..fe6f028 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. -org.gradle.jvmargs=-Xmx1536m +org.gradle.jvmargs=-Xmx3536m # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit @@ -23,12 +23,6 @@ android.useDeprecatedNdk=true android.enableAapt2=false - -mainmodulename=app -bintrayRepo=compbuild -publishedGroupId=com.luojilab.ddcomponent -siteUrl=https://github.com/luojilab/DDComponentForAndroid -gitUrl=https://github.com/luojilab/DDComponentForAndroid.git -developerId=mqzhang -developerName=mqzhang -developerEmail=zhmqq0527@gmail.com \ No newline at end of file +org.gradle.parallel=true +org.gradle.daemon=true +android.keepTimestampsInApk=true diff --git a/home/build.gradle b/home/build.gradle index 3d4cd76..bc61bf9 100644 --- a/home/build.gradle +++ b/home/build.gradle @@ -70,10 +70,6 @@ android { abortOnError false } -// compileOptions { -// sourceCompatibility JavaVersion.VERSION_1_8 -// targetCompatibility JavaVersion.VERSION_1_8 -// } aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false } diff --git a/my/build.gradle b/my/build.gradle index 97be30b..ff5822b 100644 --- a/my/build.gradle +++ b/my/build.gradle @@ -8,7 +8,7 @@ if (isApp.toBoolean()) { group = 'com.dhc.flyabbit' version = '1.0.0' -apply plugin: 'me.tatarka.retrolambda' +//apply plugin: 'me.tatarka.retrolambda' atlas { bundleConfig {