今天分享一个自己封装的一个 MVP模式的网络框架,本人一直在用,现在又改进了一些 终于有时间来分享给大家,大神估计觉得我这是小菜菜,只分享给需要的小伙伴 嘿嘿 不喜勿喷哈,下面开始吧
1.导入需要的包第三方文件
在app下的builder.gradle中配置
//butterknife
implementation 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
//rxJava
implementation 'io.reactivex:rxjava:1.1.0'
implementation 'io.reactivex:rxandroid:1.1.0'
//retrofit
implementation 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
implementation 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
//okhttp
implementation 'com.squareup.okhttp3:logging-interceptor:3.5.0'
implementation 'com.squareup.okhttp3:okhttp:3.5.0'
//Gson
implementation 'com.google.code.gson:gson:2.6.2'
此处需要注意的是: butterKnife需要在Project的builder.gradle中添加
dependencies {
classpath 'com.android.tools.build:gradle:3.1.2'
classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
2.在项目中建立Sercives接口 个人用的比较多的是 POST GET 上传的 一直用的鸿洋大神的OkhttpUtils 这里不多讲
public interface AppServices {
//GET 请求方式 传值为表单格式
@GET
Call<Object> getInter(@Url String url, @QueryMap Map<String, Object> maps);
//GET 请求方式 传值为Json字符串格式
@GET
Call<Object> getInter(@Url String url, @QueryMap String jsonData);
//POST 请求方式 传值为表单格式
@FormUrlEncoded
@POST()
Call<Object> getPostInter(@Url() String url, @FieldMap Map<String, Object> maps);
//POST 请求方式 传值为Json格式
@Headers({"Content-type:application/json",
"Content-Length:59"})
@POST()
Call<Object> getPostInter(@Url() String url, @Body RequestBody jsonValue);
//上传文件 带参数
@Multipart
@POST()
Call<Object> updateAvatar(@Url() String url, @QueryMap Map<String, Object> map, @Part("file\"; filename=\"app.apk\"") RequestBody imgs);
//删除请求
@DELETE()
Call<Object> deleteData(@Url() String url, @QueryMap Map<String, Object> map);
//put
@FormUrlEncoded
@PUT()
Call<Object> putData(@Url() String url, @FieldMap Map<String, Object> map);
@Multipart
@POST()
Call<ResponseBody> updateAvatar(@Url() String url, @QueryMap Map<String, Object> map, @Part("file\"; filename=\"hnwt.apk\"") MultipartBody.Part maps);
}
3.接下来是 接口,存放我们需要调用的接口信息
/**
* Created by Jane on 2018/8/8.
*/
public interface Constants {
String APP_URL = "http://IP:PORT/systemws/";// APP_URL
String LOGIN_ = "login/validatephonecode?bearer=";//登录
}
4.网络请求类 NetHttpApi
/**
* Created by Jane on 2017/12/13.
* 网络请求Api
*/
public class NetHttpApi {
private Retrofit retrofit;
//请求超时时间
private static final int REQUEST_TIME = 10;
private static NetHttpApi instance;
/**
* 构造函数
* @param context 上下文对象
* @param interceptor 用于添加Header 文件使用
* */
private NetHttpApi(Context context, Interceptor interceptor) {
//日志显示级别
HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
//新建log拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.d("vvvvvvvvv", "OkHttp====Message==:" + message);
}
});
loggingInterceptor.setLevel(level);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.connectTimeout(REQUEST_TIME, TimeUnit.SECONDS)
.readTimeout(REQUEST_TIME, TimeUnit.SECONDS)
.writeTimeout(REQUEST_TIME, TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor).addInterceptor(interceptor);
client.build();
Gson gson = new GsonBuilder()
.setLenient()
.create();
retrofit = new Retrofit.Builder().client(client.build())
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(Constants.APP_URL).build();
}
private NetHttpApi(Context context) {
//日志显示级别
HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
//新建log拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.d("vvvvvvvvv", "OkHttp====Message==:" + message);
}
});
loggingInterceptor.setLevel(level);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.connectTimeout(REQUEST_TIME, TimeUnit.SECONDS)
.readTimeout(REQUEST_TIME, TimeUnit.SECONDS)
.writeTimeout(REQUEST_TIME, TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor);
client.build();
Gson gson = new GsonBuilder()
.setLenient()
.create();
retrofit = new Retrofit.Builder().client(client.build())
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(Constants.APP_URL).build();
}
/**
* 创建单例模式,避免重复创建对象
**/
public static NetHttpApi getInstance(Context context, Interceptor interceptor) {
if (instance == null) {
synchronized (NetHttpApi.class) {
if (instance == null) {
instance = new NetHttpApi(context, interceptor);
}
}
}
NetHttpApi netHttpApi = new NetHttpApi(context, interceptor);
return netHttpApi;
}
/**
* 创建单例模式,避免重复创建对象
**/
public static NetHttpApi getInstance(Context context) {
if (instance == null) {
synchronized (NetHttpApi.class) {
if (instance == null) {
instance = new NetHttpApi(context);
}
}
}
NetHttpApi netHttpApi = new NetHttpApi(context);
return netHttpApi;
}
/**
* 获取一个service对象
*/
public <T> T getService(Class<T> service) {
return retrofit.create(service);
}
}
5.封装view 模块的接口 IgetResult
/**
* Created by Jane on 2017/6/16.
* 处理请求返回值的接口
*/
public interface IgetResult {
void getResult(String url, Map<String, Object> maps, OnResultListener onResultListener);
void getResult(String url, String value, OnResultListener onResultListener);
void getPostResult(String url, Map<String, Object> maps, OnResultListener onResultListener);
void getPostResult(String url, RequestBody jsonStr, OnResultListener onResultListener);
void deleteResult(String url, Map<String, Object> maps, OnResultListener onResultListener);
void putResult(String url, Map<String, Object> maps, OnResultListener onResultListener);
void uploadResult(String url, File upFile, Map<String, Object> map, OnResultListener onResultListener);
void uploadResult(String url, MultipartBody.Part body, Map<String, Object> map, OnResultListener onResultListener);
}
接口: IView 主要处理一些UI视图
/**
* Created by Jane on 2017/4/29.
*/
public interface IView {
void showloading();
void hideloading();
void resultSuccess(int requestCode, Object t) ;
void showFail(String exception);
}
接口: OnResultListener 处理请求状态
/**
* Created by Jane on 2017/4/29.
*/
public interface OnResultListener<T> {
void onSuccess(T t);
void fail(String errormsg);
}
类:ResultView 做一些请求 封装请求 绑定view
/**
* Created by Jane on 2017/6/16.
*/
public class ResultView implements IgetResult {
AppServices appServices;
public ResultView(Context context, Interceptor interceptor) {
appServices = NetHttpApi.getInstance(context,interceptor).getService(AppServices.class);
}
public ResultView(Context context) {
appServices = NetHttpApi.getInstance(context).getService(AppServices.class);
}
@Override
public void getResult(String url, Map<String, Object> maps, final OnResultListener onResultListener) {
Call<Object> call = appServices.getInter(url, maps);
call.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
Object t = response.body();
onResultListener.onSuccess(t);
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
if (null != t && t != null) {
onResultListener.fail(t.getMessage());
} else {
onResultListener.fail("");
}
}
});
}
@Override
public void getResult(String url, String value, final OnResultListener onResultListener) {
Call<Object> call = appServices.getInter(url, value);
call.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
Object t = response.body();
onResultListener.onSuccess(t);
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
if (null != t && t != null) {
onResultListener.fail(t.getMessage());
} else {
onResultListener.fail("");
}
}
});
}
@Override
public void getPostResult(String url, Map<String, Object> body, final OnResultListener onResultListener) {
Call<Object> call = appServices.getPostInter(url, body);
call.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
Object t = response.body();
if (response.isSuccess()) {
onResultListener.onSuccess(t);
} else {
try {
Object obj = (Object) response.errorBody().string();
onResultListener.onSuccess(obj);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
if (null != t && t != null) {
onResultListener.fail(t.getMessage());
} else {
onResultListener.fail("");
}
}
});
}
@Override
public void getPostResult(String url, RequestBody jsonStr, final OnResultListener onResultListener) {
Call<Object> call = appServices.getPostInter(url, jsonStr);
call.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
Object t = response.body();
if (response.isSuccess()) {
onResultListener.onSuccess(t);
} else {
try {
Object obj = (Object) response.errorBody().string();
onResultListener.onSuccess(obj);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
if (null != t && t != null) {
onResultListener.fail(t.getMessage());
} else {
onResultListener.fail("");
}
}
});
}
@Override
public void deleteResult(String url, Map<String, Object> maps, final OnResultListener onResultListener) {
Call<Object> call = appServices.deleteData(url, maps);
call.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
Object t = response.body();
if (response.isSuccess()) {
onResultListener.onSuccess(t);
} else {
try {
Object obj = (Object) response.errorBody().string();
onResultListener.onSuccess(obj);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
if (null != t && t != null) {
onResultListener.fail(t.getMessage());
} else {
onResultListener.fail("");
}
}
});
}
@Override
public void putResult(String url, Map<String, Object> maps, final OnResultListener onResultListener) {
Call<Object> call = appServices.putData(url, maps);
call.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
Object t = response.body();
if (response.isSuccess()) {
onResultListener.onSuccess(t);
} else {
try {
Object obj = (Object) response.errorBody().string();
onResultListener.onSuccess(obj);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
if (null != t && t != null) {
onResultListener.fail(t.getMessage());
} else {
onResultListener.fail("");
}
}
});
}
@Override
public void uploadResult(String url, File upFile, Map<String, Object> map, final OnResultListener onResultListener) {
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), upFile);
Call<Object> call = appServices.updateAvatar(url, map, requestBody);
call.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
//。。。。。
Object t = response.body();
if (response.isSuccess()) {
onResultListener.onSuccess(t);
} else {
try {
Object obj = (Object) response.errorBody().string();
onResultListener.onSuccess(obj);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
if (null != t && t != null) {
onResultListener.fail(t.getMessage());
} else {
onResultListener.fail("");
}
}
});
}
@Override
public void uploadResult(String url, MultipartBody.Part body, Map<String, Object> map, final OnResultListener onResultListener) {
}
}
6.Presenter 解析器 只列举一个 PostPresenter 其余的参考项目中的文件即可
/**
* Created by Jane on 2017/4/30.
*/
public class PostPresenter {
Context context;
IgetResult igetResult;
IView iView;
public PostPresenter(Context context, IView iView, Interceptor interceptor) {
this.context = context;
igetResult = new ResultView(context,interceptor);
this.iView = iView;
}
public PostPresenter(Context context, IView iView) {
this.context = context;
igetResult = new ResultView(context);
this.iView = iView;
}
public void getPostInterface(final int requestCode, String url, Map<String, Object> maps) {
iView.showloading();
igetResult.getPostResult(url, maps, new OnResultListener() {
@Override
public void onSuccess(Object o) {
iView.hideloading();
iView.resultSuccess(requestCode, o);
}
@Override
public void fail(String errormsg) {
iView.hideloading();
iView.showFail(errormsg);
}
});
}
public void getPostInterface(final int requestCode, String url, RequestBody jsonValue) {
iView.showloading();
igetResult.getPostResult(url, jsonValue, new OnResultListener() {
@Override
public void onSuccess(Object o) {
iView.hideloading();
iView.resultSuccess(requestCode, o);
}
@Override
public void fail(String errormsg) {
iView.hideloading();
iView.showFail(errormsg);
}
});
}
}
7.Activity交互处理 这里封装到了BaseActivity里面 主页面不需要多余的操作即可
/**
* Created by Jane on 2018/8/6.
*/
public abstract class BaseActivity extends Activity implements IView {
private Unbinder unbinder;
private Dialog dialog;
//动态权限
private String permissionInfo;
private final int SDK_PERMISSION_REQUEST = 127;
private ValueCallback<Uri> mUploadMessage;// 表单的数据信息
private ValueCallback<Uri[]> mUploadCallbackAboveL;
private final static int FILECHOOSER_RESULTCODE = 1;// 表单的结果回调
private Uri imageUri;
private Context context;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 去除title
requestWindowFeature(Window.FEATURE_NO_TITLE);
// 去掉Activity上面的状态栏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(getContentView());
context=this;
unbinder = ButterKnife.bind(this);
initview(savedInstanceState);
getPersimmions();
}
/**
* 布局文件
*/
public abstract int getContentView();
/**
* 初始化操作
*
* @param savedInstanceState 保存示例对象
*/
public abstract void initview(Bundle savedInstanceState);
@Override
protected void onDestroy() {
super.onDestroy();
unbinder.unbind();
closeDialog();
}
@Override
public void showloading() {
showDialog();
}
@Override
public void hideloading() {
closeDialog();
}
@Override
public void resultSuccess(int requestCode, Object o) {
}
@Override
public void showFail(String errormsg) {
ToastUtil.showToast(BaseActivity.this, getString(R.string.toast_loading_error));
}
/**
* 显示Dialog
*/
protected void showDialog() {
if (dialog == null) {
dialog = LoadingDialog.createLoadingDialog(this, getString(R.string.toast_loading_middle));
dialog.show();
}
}
public void closeDialog() {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
/**
* 获取权限
*/
private void getPersimmions() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ArrayList<String> permissions = new ArrayList<String>();
/***
* 定位权限为必须权限,用户如果禁止,则每次进入都会申请
*/
// 定位精确位置
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.READ_PHONE_STATE);
}
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (checkSelfPermission(Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
permissions.add(Manifest.permission.ACCESS_WIFI_STATE);
}
/*
* 读写权限和电话状态权限非必要权限(建议授予)只会申请一次,用户同意或者禁止,只会弹一次
*/
// 读写权限
if (addPermission(permissions, Manifest.permission.READ_EXTERNAL_STORAGE)) {
permissionInfo += "Manifest.permission.READ_EXTERNAL_STORAGE Deny \n";
}
if (addPermission(permissions, Manifest.permission.CAMERA)) {
permissionInfo += "Manifest.permission.CAMERA Deny \n";
}
if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
}
// 读取电话状态权限
if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
}
// 读取电话状态权限
if (addPermission(permissions, Manifest.permission.ACCESS_WIFI_STATE)) {
permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
}
if (permissions.size() > 0) {
requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
}
}
}
@TargetApi(23)
private boolean addPermission(ArrayList<String> permissionsList, String permission) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
if (shouldShowRequestPermissionRationale(permission)) {
return true;
} else {
permissionsList.add(permission);
return false;
}
} else {
return true;
}
}
// 用户权限 申请 的回调方法
@TargetApi(23)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
// TODO Auto-generated method stub
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
if (mUploadCallbackAboveL != null) {
onActivityResultAboveL(requestCode, resultCode, data);
} else if (mUploadMessage != null) {
if (result != null) {
String path = getPath(getApplicationContext(),
result);
Uri uri = Uri.fromFile(new File(path));
mUploadMessage
.onReceiveValue(uri);
} else {
mUploadMessage.onReceiveValue(imageUri);
}
mUploadMessage = null;
}
} else if (requestCode == 121) {
Uri uri = data.getData();//得到uri,后面就是将uri转化成file的过程。
String[] proj = {MediaStore.Images.Media.DATA};
Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
String img_path = actualimagecursor.getString(actual_image_column_index);
File file = new File(img_path);
Toast.makeText(this, file.toString(), Toast.LENGTH_SHORT).show();
} else {
super.onActivityResult(requestCode, resultCode, data);
return;
}
}
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
@SuppressWarnings("null")
private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
if (requestCode != FILECHOOSER_RESULTCODE
|| mUploadCallbackAboveL == null) {
return;
}
Uri[] results = null;
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
results = new Uri[]{imageUri};
} else {
String dataString = data.getDataString();
ClipData clipData = data.getClipData();
if (clipData != null) {
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item item = clipData.getItemAt(i);
results[i] = item.getUri();
}
}
if (dataString != null)
results = new Uri[]{Uri.parse(dataString)};
}
}
if (results != null) {
mUploadCallbackAboveL.onReceiveValue(results);
mUploadCallbackAboveL = null;
} else {
results = new Uri[]{imageUri};
mUploadCallbackAboveL.onReceiveValue(results);
mUploadCallbackAboveL = null;
}
return;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null) cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
}
7.使用 这里以Post 表单/Json两种请求为例
public class MainActivity extends BaseActivity {
private PostPresenter postPresenter;
private final int LOGIN_CODE=1;//登录请求码
@Override
public int getContentView() {
return R.layout.activity_main;
}
@Override
public void initview(Bundle savedInstanceState) {
postPresenter=new PostPresenter(this,this);
}
private void post(){
/**
* 表单方式 无Header
* */
Map<String, Object> map = new HashMap<>();
map.put("username","");
map.put("password","");
postPresenter.getPostInterface(LOGIN_CODE, Constants.LOGIN_, map);
/**
* Json方式传值 无Header
* */
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username","");
jsonObject.put("password","");
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody myreqbody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
jsonObject.toString());
postPresenter.getPostInterface(LOGIN_CODE, Constants.LOGIN_, myreqbody);
}
@Override
public void resultSuccess(int requestCode, Object o) {
super.resultSuccess(requestCode, o);
if (requestCode==LOGIN_CODE){
Gson gson=new Gson();
String jsonStr=gson.toJson(o);
LoginResult loginResult=gson.fromJson(jsonStr,LoginResult.class);
//做下一步判断
}
}
}
8.最后不要忘记 网络权限哈
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
下载地址:https://download.csdn.net/download/zww986736788/10601184