retrofit2+rxjava
将retrofit2和rxjava的配置配置到application
package cn.yuebai.yuebaidealer.config; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.content.Context; import android.os.Build; import android.support.multidex.MultiDex; import android.util.DisplayMetrics; import android.view.WindowManager; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.leakcanary.LeakCanary; import com.squareup.leakcanary.RefWatcher; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.concurrent.TimeUnit; import cn.yuebai.yuebaidealer.BuildConfig; import cn.yuebai.yuebaidealer.util.log.LoggingInterceptor; import okhttp3.Cache; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * 基本配置 * * @author ZhaoYazhi * @time 16/4/12 */ public class MyApplication extends Application { private final String TAG = "MyApplication"; private static Context mContext; private OkHttpClient mHttpClient; private Gson mGson; private Retrofit mRetrofit; //LeakCanary展现Android中的内存泄露 https://github.com/SOFTPOWER1991/leakcanarySample_androidStudio private RefWatcher refWatcher; // APIS private final HashMap<Class, Object> apis = new HashMap<>(); private List<Activity> activityList = new ArrayList<Activity>(); // 单例模式 private static MyApplication instance; /** * 单例模式中获取唯一的MyApp实例 * * @return */ public static MyApplication getInstance() { if (null == instance) { instance = new MyApplication(); } return instance; } @Override public void onCreate() { super.onCreate(); mContext = getApplicationContext(); //设置该CrashHandler为程序的默认处理器 UnCeHandler catchExcep = new UnCeHandler(this); Thread.setDefaultUncaughtExceptionHandler(catchExcep); refWatcher = LeakCanary.install(this);//LeakCanary展现Android中的内存泄露 this.init(); } private void init() { initGson(); initHttpClient(); initRetrofit(); } public static MyApplication from(Context context) { Context application = context.getApplicationContext(); if (application instanceof MyApplication) { return (MyApplication) application; } else { throw new IllegalArgumentException("context must be from ImApp"); } } public static Context getContext() { return mContext; } private String buildAcceptLanguage() { Locale locale = Locale.getDefault(); return String.format("%s-%s,%s;q=0.8,en-US;q=0.6,en;q=0.4", locale.getLanguage(), locale.getCountry(), locale.getLanguage()); } /** * 使高版本API的代码在低版本SDK不报错,4.0 * http://www.tuicool.com/articles/BreuUz * * @return */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private String buildUserAgent() { String userAgent = String.format("Retrofit %s Android (%d/%s)", BuildConfig.VERSION_NAME, Build.VERSION.SDK_INT, Build.VERSION.RELEASE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { DisplayMetrics metrics = new DisplayMetrics(); WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE); wm.getDefaultDisplay().getRealMetrics(metrics); userAgent += String.format(" (%d; %dx%d)", metrics.densityDpi, metrics.widthPixels, metrics.heightPixels); } return userAgent; } /** * 初始化goson */ private void initGson() { mGson = new GsonBuilder() // .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); } /** * 初始化okhttp,拦截器 */ private void initHttpClient() { mHttpClient = new OkHttpClient(); mHttpClient.networkInterceptors() .add(chain -> chain.proceed(chain.request().newBuilder() .header("Accept-Language", buildAcceptLanguage()) .header("User-Agent", buildUserAgent()) .build())); mHttpClient.newBuilder().connectTimeout(AppConfig.CONNECT_TIME_OUT, TimeUnit.SECONDS) .cache(new Cache(new File(mContext.getCacheDir().getAbsolutePath(), AppConfig.OKHTTP_CACHE_DIR), AppConfig.MAX_CACHE_SIZE_INBYTES)) .interceptors().add(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)); // 打印日志 if (BuildConfig.DEBUG) { mHttpClient.networkInterceptors().add(new LoggingInterceptor()); } } /** * 初始化initRetrofit */ private void initRetrofit() { mRetrofit = new Retrofit.Builder() .client(mHttpClient) .baseUrl(AppConfig.BASE_URL) .addConverterFactory(GsonConverterFactory.create(mGson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); } public OkHttpClient getHttpClient() { return mHttpClient; } /** * 创建一个api * * @param service * @param <T> * @return */ public <T> T createCoreApi(Class<T> service) { if (!apis.containsKey(service)) { T instance = mRetrofit.create(service); apis.put(service, instance); } return (T) apis.get(service); } /** * 获取 api * * @param service * @param <T> * @return */ public <T> T getApi(Class<T> service) { if (!apis.containsKey(service)) { T instance = mRetrofit.create(service); apis.put(service, instance); } return (T) apis.get(service); } /** * LeakCanary * https://github.com/SOFTPOWER1991/leakcanarySample_androidStudio * * @param context * @return */ public static RefWatcher getRefWatcher(Context context) { MyApplication application = (MyApplication) context .getApplicationContext(); return application.refWatcher; } /////////////////////////////////////////////////////////////////////////// /** * 用于全部退出 在每个Activity * 类中onCreate()方法中调用MyApp.getInstance().addActivity(Activity activity)方法。 * 在任何一个Activity * 界面退出应用程序时,只要调用MyApp.getInstance().exit()方法,就可以在任何一个Activity中完全退出应用程序。 */ /** * 添加Activity 到容器中 * * @param activity */ public void addActivity(Activity activity) { System.out.println("@@@@addactivity" + activity.getPackageName() + activity.getClass().getName()); activityList.add(activity); } public void remove(Activity activity) { System.out.println("@@@@remove" + activity.getPackageName() + activity.getClass().getName()); activityList.remove(activity); } /** * 完全退出 */ public void finishActivity() { System.out.println(activityList.size() + "======"); for (Activity activity : activityList) { System.out.println("=========" + activity.getLocalClassName()); if (null != activity) { activity.finish(); } } android.os.Process.killProcess(android.os.Process.myPid());//杀死线程 System.exit(0); } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } }
设置BaseActivity,子类直接继承
package cn.yuebai.yuebaidealer.config; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.os.Looper; import android.os.Message; import android.view.Window; import android.view.WindowManager; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import cn.yuebai.yuebaidealer.util.ActivityUtils; /** * User: ZhiyaZhao([email protected]) * Date: 2016-04-14 * parma: 11:41 * FIXME */ public abstract class BaseActivity extends RxAppCompatActivity { private MyApplication myApplication; // 可以把常量单独放到一个Class中 public static final String ACTION_NETWORK_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE"; public static final String ACTION_NEW_VERSION = "apk.update.action"; protected static MUIHandler handler = new MUIHandler(Looper.getMainLooper()); // 数据回调接口,都传递Domine的子类实体 protected MDataCallback<MData<? extends BaseBean>> dataCallback; //这个地方有点“模板方法“的设计模式样子 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityUtils.add(this); this.init(); this.myApplication = MyApplication.getInstance().from(getActivity()); this.createApi(myApplication); this.initialization(); setBase(); setHandler(); initContentView(savedInstanceState); } private void init(){ //兼容 23 if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){ getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); } } protected MyApplication getApp() { return myApplication; } protected BaseActivity getActivity() { return this; } private void setHandler() { handler.setHandler(new IHandler() { public void handleMessage(Message msg) { handler(msg);//有消息就提交给子类实现的方法 } }); } protected abstract int inflateLayout(); /** * Initialization */ protected abstract void initialization(); /** * * @param app */ protected abstract void createApi(MyApplication app); // 初始化UI,setContentView等 protected abstract void initContentView(Bundle savedInstanceState); // 可能全屏或者没有ActionBar等 private void setBase() { requestWindowFeature(Window.FEATURE_NO_TITLE); } protected void addLeftMenu(boolean enable) { // 如果你的项目有侧滑栏可以处理此方法 if (enable) { // 是否能有侧滑栏 } else { } } //让子类处理消息 protected abstract void handler(Message msg); // 横竖屏切换,键盘等 @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { try { super.onRestoreInstanceState(savedInstanceState); } catch (Exception e) { } } BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // 处理各种情况 String action = intent.getAction(); if (ACTION_NETWORK_CHANGE.equals(action)) { // 网络发生变化 // 处理网络问题 } else if (ACTION_NEW_VERSION.equals(action)) { // 可能发现新版本 // VersionDialog 可能是版本提示是否需要下载的对话框 } } }; public void setDataCallback( MDataCallback<MData<? extends BaseBean>> dataCallback) { this.dataCallback = dataCallback; } @Override protected void onResume() { super.onResume(); // 你可以添加多个Action捕获 IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_NETWORK_CHANGE); filter.addAction(ACTION_NEW_VERSION); registerReceiver(receiver, filter); } @Override protected void onPause() { super.onPause(); unregisterReceiver(receiver); //还可能发送统计数据,比如第三方的SDK 做统计需求 } @Override protected void onDestroy() { super.onDestroy(); ActivityUtils.remove(this); } }