Skip to content

Commit

Permalink
未进行全局设置时通过反射获取Application
Browse files Browse the repository at this point in the history
  • Loading branch information
MrZhousf committed Nov 30, 2017
1 parent f00a06b commit d524689
Show file tree
Hide file tree
Showing 11 changed files with 101 additions and 27 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,23 +50,23 @@
<dependency>
<groupId>com.zhousf.lib</groupId>
<artifactId>okhttp3</artifactId>
<version>2.9.2.2</version>
<version>2.9.3</version>
<type>pom</type>
</dependency>
```
### Gradle
```
compile 'com.zhousf.lib:okhttp3:2.9.2.2'
compile 'com.zhousf.lib:okhttp3:2.9.3'
```
若项目已包含support-annotations或出现support-annotations版本冲突请采用下面方式进行依赖:
```
compile ('com.zhousf.lib:okhttp3:2.9.2.2'){
compile ('com.zhousf.lib:okhttp3:2.9.3'){
exclude(module: 'support-annotations')
}
```
若项目已包含Gson或出现Gson版本冲突请采用下面方式进行依赖:
```
compile ('com.zhousf.lib:okhttp3:2.9.2.2'){
compile ('com.zhousf.lib:okhttp3:2.9.3'){
exclude(module:'gson')
}
```
Expand All @@ -82,7 +82,7 @@ compile ('com.zhousf.lib:okhttp3:2.9.2.2'){
```
compileSdkVersion 23
targetSdkVersion 23
minSdkVersion 14
minSdkVersion 13
```


Expand Down
2 changes: 1 addition & 1 deletion app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ android {

dependencies {
// compile project(':okhttp3')
compile ('com.zhousf.lib:okhttp3:2.9.2.2'){
compile ('com.zhousf.lib:okhttp3:2.9.3'){
exclude(module:'gson')
}
compile fileTree(include: ['*.jar'], dir: 'libs')
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/java/base/BaseProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class BaseProvider extends ContentProvider {
@Override
public boolean onCreate() {
//获取Application上下文
initOkHttp(this.getContext());
initOkHttp(getContext());
return false;
}

Expand Down
6 changes: 5 additions & 1 deletion app/src/main/java/base/networkstate/NetSpeedService.java
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,9 @@ public int getScreenWidth(Context context) {
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
if(wm != null){
wm.getDefaultDisplay().getMetrics(outMetrics);
}
return outMetrics.widthPixels;
}

Expand All @@ -227,6 +229,8 @@ public boolean isNetworkAvailable(Context context){
if (context != null) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm == null)
return false;
final NetworkInfo network = cm.getActiveNetworkInfo();
if(network != null && network.getState() == NetworkInfo.State.CONNECTED){
return true;
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/base/networkstate/NetworkStateReceiver.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ public static BroadcastReceiver getBroadcastReceiver(){
public void onReceive(Context context, Intent intent) {
if(broadcastReceiver == null)
broadcastReceiver = NetworkStateReceiver.this;
if(intent.getAction() == null)
return ;
if (intent.getAction().equalsIgnoreCase(ANDROID_NET_CHANGE_ACTION)) {
boolean isNetworkAvailable = NetworkUtil.isNetworkAvailable(context);
String networkType = NetworkUtil.getNetworkType(context);
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/base/networkstate/TrafficUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,10 @@ public static long getNetworkTxBytes() {
* 获取当前网速
*/
public double getNetSpeed() {
//获取总的流量情况
long curRxBytes = getNetworkRxBytes();
//获取当前应用的流量情况
// long curRxBytes = getTrafficInfo();
if (preRxBytes == 0)
preRxBytes = curRxBytes;
long bytes = curRxBytes - preRxBytes;
Expand Down
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
project.ext.sdkVersion = 23
project.ext.buildTools = '25.0.0'
project.ext.minSdkVersion = 14
project.ext.minSdkVersion = 13
buildscript {
repositories {
jcenter()
Expand Down
2 changes: 1 addition & 1 deletion okhttp3/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ android {
targetSdkVersion rootProject.sdkVersion
minSdkVersion rootProject.minSdkVersion
versionCode 1
versionName "2.9.2.2"
versionName "2.9.3"
}

buildTypes {
Expand Down
56 changes: 56 additions & 0 deletions okhttp3/src/main/java/com/okhttplib/OkApplication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.okhttplib;

import android.annotation.SuppressLint;
import android.app.Application;

import java.lang.reflect.Method;

/**
* Author : zhousf
* Description : 通过反射获取Application上下文
* Date : 2017/11/29.
*/
public class OkApplication{

@SuppressLint("StaticFieldLeak")
private static Application application;

public static Application get(){
if(application == null){
synchronized (OkApplication.class){
if(application == null){
new OkApplication();
}
}
}
return application;
}

@SuppressWarnings("all")
private OkApplication(){
Object activityThread;
try {
Class acThreadClass = Class.forName("android.app.ActivityThread");
if(acThreadClass == null)
return;
Method acThreadMethod = acThreadClass.getMethod("currentActivityThread");
if(acThreadMethod == null){
return;
}
acThreadMethod.setAccessible(true);
activityThread = acThreadMethod.invoke(null);
Method applicationMethod = activityThread.getClass().getMethod("getApplication");
if(applicationMethod == null){
return;
}
Object app = applicationMethod.invoke(activityThread);
application = (Application) app;
} catch (Throwable e){
e.printStackTrace();
}
}




}
35 changes: 24 additions & 11 deletions okhttp3/src/main/java/com/okhttplib/OkHttpUtil.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package com.okhttplib;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
Expand All @@ -20,6 +22,7 @@
import com.okhttplib.helper.OkHttpHelper;
import com.okhttplib.interceptor.ExceptionInterceptor;
import com.okhttplib.interceptor.ResultInterceptor;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
Expand All @@ -28,6 +31,7 @@
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CookieJar;
import okhttp3.Interceptor;
Expand Down Expand Up @@ -57,27 +61,37 @@
* 支持请求结果拦截以及异常处理拦截
* 支持单例客户端,提高网络请求速率
*
* 引入版本com.squareup.okhttp3:okhttp:3.7.0
* 引入版本com.squareup.okhttp3:okhttp:3.8.1
* @author zhousf
*/
public class OkHttpUtil implements OkHttpUtilInterface{

private final String TAG = getClass().getSimpleName();
public static Context context;
@SuppressLint("StaticFieldLeak")
private static Context context;
private static Builder builderGlobal;
private static OkHttpClient httpClient;
private static ScheduledExecutorService executorService;
private Builder builder;
private int cacheSurvivalTime = 0;//缓存存活时间(秒)
private @CacheType int cacheType = FORCE_NETWORK;//缓存类型

private Context getContext(){
if(context == null){
context = OkApplication.get();
}
return context;
}

/**
* 初始化:请在Application中调用
* @param context 上下文
*/
public static Builder init(Context context){
OkHttpUtil.context = context;
((Application)OkHttpUtil.context).registerActivityLifecycleCallbacks(new BaseActivityLifecycleCallbacks());
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2) {
((Application)OkHttpUtil.context).registerActivityLifecycleCallbacks(new BaseActivityLifecycleCallbacks());
}
return BuilderGlobal();
}

Expand Down Expand Up @@ -457,10 +471,11 @@ public void setDefaultClient(OkHttpClient client){
httpClient = client;
}

@SuppressWarnings("all")
public boolean isNetworkAvailable() {
if(context == null)
if(getContext() == null)
return true;
ConnectivityManager cm = (ConnectivityManager) context
ConnectivityManager cm = (ConnectivityManager) getContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo net = cm.getActiveNetworkInfo();
return net != null && net.getState() == NetworkInfo.State.CONNECTED;
Expand All @@ -471,7 +486,7 @@ private OkHttpUtil(Builder builder) {
this.builder = builder;
this.cacheType = builder.cacheType;
this.cacheSurvivalTime = builder.cacheSurvivalTime;
if(null == context)
if(null == getContext())
this.cacheType = CacheType.FORCE_NETWORK;
if(null == executorService)
executorService = new ScheduledThreadPoolExecutor(20);
Expand Down Expand Up @@ -522,12 +537,9 @@ private HelperInfo packageHelperInfo(HttpInfo info){
}
}
if(httpsCertificate != null){
if(OkHttpUtil.context == null){
throw new IllegalArgumentException("请初始化OkHttpUtil");
}
InputStream inputStream = null;
try {
inputStream = context.getAssets().open(httpsCertificate);
inputStream = getContext().getAssets().open(httpsCertificate);
} catch (IOException e) {
e.printStackTrace();
}
Expand Down Expand Up @@ -640,6 +652,7 @@ private void initDefaultConfig(){
setShowHttpLog(true);
setShowLifecycleLog(false);
setDownloadFileDir(Environment.getExternalStorageDirectory().getPath()+"/okHttp_download/");
setCachedDir(new File(Environment.getExternalStorageDirectory().getPath()+"/okHttp_cache"));
setIsGzip(false);
setResponseEncoding(Encoding.UTF_8);
setRequestEncoding(Encoding.UTF_8);
Expand Down Expand Up @@ -879,7 +892,7 @@ private static String parseRequestTag(Object object){
public boolean deleteCache() {
try {
if(httpClient != null && httpClient.cache() != null)
httpClient.cache().delete();
httpClient.cache().delete();
} catch (Exception e){
e.printStackTrace();
return false;
Expand Down
8 changes: 2 additions & 6 deletions okhttp3/src/main/java/com/okhttplib/helper/BaseHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,17 +65,14 @@ abstract class BaseHelper {
private @CacheType int cacheType;//缓存类型
OkHttpClient httpClient;
private String TAG;
public String timeStamp;
String timeStamp;
private boolean showHttpLog;
public String requestTag;//请求标识
HelperInfo helperInfo;
HttpInfo httpInfo;
private List<ResultInterceptor> resultInterceptors;//请求结果拦截器
private List<ExceptionInterceptor> exceptionInterceptors;//请求链路异常拦截器

BaseHelper() {
}

BaseHelper(HelperInfo helperInfo) {
this.helperInfo = helperInfo;
this.httpInfo = helperInfo.getHttpInfo();
Expand Down Expand Up @@ -336,7 +333,7 @@ public X509Certificate[] getAcceptedIssuers() {
/**
* 添加请求头参数
*/
Request.Builder addHeadsToRequest(HttpInfo info, Request.Builder requestBuilder){
void addHeadsToRequest(HttpInfo info, Request.Builder requestBuilder){
if(null != info.getHeads() && !info.getHeads().isEmpty()){
StringBuilder log = new StringBuilder("Heads: ");
for (String key : info.getHeads().keySet()) {
Expand All @@ -349,7 +346,6 @@ Request.Builder addHeadsToRequest(HttpInfo info, Request.Builder requestBuilder)
}
showLog(log.toString());
}
return requestBuilder;
}

HttpInfo retInfo(HttpInfo info, int code){
Expand Down

0 comments on commit d524689

Please sign in to comment.