//先写这个类
public class MyApplication extends Application { public static int myTid; public static Handler handler; @Override public void onCreate() { super.onCreate(); myTid = Process.myTid(); handler=new Handler(); CrashHandler.getInstance().init(this); ImageLoaderConfiguration build=new ImageLoaderConfiguration.Builder(this).build(); ImageLoader.getInstance().init(build); } public static int getMyTid() { return myTid; } public static Handler getHandler() { return handler; } }
在写个类
public class CommonUtil { public static void runOnUiThead(Runnable runnable){ if (Process.myTid()==MyApplication.getMyTid()){ runnable.run(); }else { MyApplication.getHandler().post(runnable); } }
}
写这俩个类是保证运行在主线程中
封装的post请求和拦截器
public class OkHttpUtil { private static OkHttpUtil okHttpUtil; public static OkHttpUtil getInstance(){ if (okHttpUtil==null){ okHttpUtil=new OkHttpUtil(); } return okHttpUtil; } public void doPost(String url, Map<String,String> map, Callback callback){ OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new MyInterceptor()).build(); FormBody.Builder builder = new FormBody.Builder(); Set<String> keys = map.keySet(); for (String key : keys){ String value = map.get(key); builder.add(key,value+""); } FormBody body = builder.build(); Request request = new Request.Builder().url(url).post(body).build(); Call call = okHttpClient.newCall(request); call.enqueue(callback); } public class MyInterceptor implements Interceptor{ @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); RequestBody body = request.body(); if (body instanceof FormBody){ FormBody.Builder newBuilder = new FormBody.Builder(); for (int i=0;i<((FormBody) body).size();i++){ String name = ((FormBody) body).name(i); String value = ((FormBody) body).value(i); newBuilder.add(name,value); } //将公共参数添加进去 newBuilder.add("oxwlxojflwblxbsapi","get_recent_posts"); FormBody newBody = newBuilder.build(); //创建新的请求 Request request1 = request.newBuilder().post(newBody).build(); Response response = chain.proceed(request1); return response; } return null; } } }在model实现类里这样调用不用handler
public class IViewModlempl implements IViewModel { private IViewPresenter iViewPresenter; public IViewModlempl(IViewPresenter iViewPresenter) { this.iViewPresenter = iViewPresenter; } @Override public void getData(String url, Map<String, String> map) { OkHttpUtil.getInstance().doPost(url, map, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()){ String beanJson = response.body().string(); final Bean bean = new Gson().fromJson(beanJson, Bean.class); CommonUtil.runOnUiThead(new Runnable() { @Override public void run() { iViewPresenter.setData(bean); } }); } } }); } }