module:
public class MyModule { public void getDate(String str, HashMap<String,String> map, final MyPresenterInterface myPresenterInterface){ /** * 请求数据 */ OkHttpUtils.doPost(str, map, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String s = response.body().string(); myPresenterInterface.onSuccess(s); } }); } }
PresenterInterface:
public interface MyPresenterInterface { void onSuccess(Object obj); }
Presenter:
public class MyPresenter implements MyPresenterInterface{ private MyModule myModule; private MyViewInterface myViewInterface; public MyPresenter(MyViewInterface myViewInterface){ this.myModule = new MyModule(); this.myViewInterface = myViewInterface; } public void getDate(String date, HashMap<String,String> map){ myModule.getDate(date,map,this); } public void detachView(){ if(myViewInterface != null){ myViewInterface=null; } } @Override public void onSuccess(Object obj) { myViewInterface.onSuccess(obj); } }
ViewInterface:
public interface MyViewInterface { void onSuccess(Object obj); }
Activity继承的抽象类BaseActivity:
public abstract class BaseActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(setContextView()); initView(); initDate(); } abstract void initView(); abstract void initDate(); abstract int setContextView(); }
Activity中需要继承BaseActivity和实现对应的接口并重写其中的方法
贴一下大概可以用到的Okhhtp工具类:
单例模式和GetPost的封装
public class OkHttpUtils { private OkHttpUtils(){} static OkHttpClient mOkHttpClient; public static OkHttpClient getINSTANCE(){ if(mOkHttpClient==null){ mOkHttpClient = new OkHttpClient().newBuilder() .build(); } return mOkHttpClient; } public static void doGet(String str,Callback callback){ OkHttpClient mOkHttpClient = getINSTANCE(); Request request = new Request.Builder() .url(str) .get() .build(); mOkHttpClient.newCall(request).enqueue(callback); } public static void doPost(String str, HashMap<String,String> map,Callback callback){ OkHttpClient mOkHttpClient = getINSTANCE(); FormBody.Builder builder = new FormBody.Builder(); Iterator<String> iterator = map.keySet().iterator(); while (iterator.hasNext()){ String key = iterator.next(); String value = map.get(key); builder.add(key,value); } FormBody formBody = builder.build(); Request request = new Request.Builder() .url(str) .post(formBody) .build(); mOkHttpClient.newCall(request).enqueue(callback); } }

2687

被折叠的 条评论
为什么被折叠?



