//model层
package zhaochuang.bawei.com.myapplication.model;
import java.util.Map;
import okhttp3.RequestBody;
import zhaochuang.bawei.com.myapplication.JieKou.LoadListener;
/**
* Created by zh on 2018/4/14.
*/
public interface Model {
void UpLoad(Map<String, RequestBody> map, LoadListener loadListener);
}
//model实现类
package zhaochuang.bawei.com.myapplication.model;
import java.util.Map;
import okhttp3.RequestBody;
import zhaochuang.bawei.com.myapplication.JieKou.LoadListener;
/**
* Created by zh on 2018/4/14.
*/
public interface Model {
void UpLoad(Map<String, RequestBody> map, LoadListener loadListener);
}
//接口
package zhaochuang.bawei.com.myapplication.JieKou;
/**
* Created by zh on 2018/4/14.
*/
public interface LoadListener {
void LoadSuccouer(Object o);
void LoadError(String json);
}
//presnter层
package zhaochuang.bawei.com.myapplication.presenter;
import java.util.Map;
import okhttp3.RequestBody;
import zhaochuang.bawei.com.myapplication.views.UpLoadVies;
/**
* Created by zh on 2018/4/14.
*/
public interface presenter {
void UpLoadpre(Map<String, RequestBody> params, UpLoadVies upLoadVies);
}
//presnter层实现类
package zhaochuang.bawei.com.myapplication.presenter;
import android.util.Log;
import java.util.Map;
import okhttp3.RequestBody;
import zhaochuang.bawei.com.myapplication.JieKou.LoadListener;
import zhaochuang.bawei.com.myapplication.TouBean;
import zhaochuang.bawei.com.myapplication.model.ModelImp;
import zhaochuang.bawei.com.myapplication.views.UpLoadVies;
/**
* Created by zh on 2018/4/14.
*/
public class presenterImp implements presenter {
@Override
public void UpLoadpre(Map<String, RequestBody> params, final UpLoadVies upLoadVies) {
new ModelImp().UpLoad(params, new LoadListener() {
@Override
public void LoadSuccouer(Object o) {
TouBean touBean= (TouBean) o;
Log.e("tag",touBean.getMsg()+"");
upLoadVies.UpLoadViesSuccoc(o);
}
@Override
public void LoadError(String json) {
Log.e("tag",json+"");
upLoadVies.UpLoadViesError(json);
}
});
}
}
//view视图
package zhaochuang.bawei.com.myapplication.views;
/**
* Created by zh on 2018/4/14.
*/
public interface UpLoadVies {
void UpLoadViesSuccoc(Object o);
void UpLoadViesError(String json);
}
//RXjava
package zhaochuang.bawei.com.myapplication;
import java.util.Map;
import io.reactivex.Observable;
import okhttp3.RequestBody;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.PartMap;
/**
* Created by zh on 2018/4/14.
*/
public interface ApiFunction {
//上传文件
@Multipart
@POST("file/upload")
Observable<TouBean> uploadFile(@PartMap Map<String, RequestBody> params);
}
//接口类
package zhaochuang.bawei.com.myapplication;
/**
* Created by zh on 2018/4/14.
*/
public class Constants {
public static String Base_url="https://www.zhaoapi.cn/";
public static String UpLoad_url="file/upload";
public static String source="android";
}
//HttpParameterBuilder 工具类
package zhaochuang.bawei.com.myapplication;
import android.net.Uri;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.RequestBody;
/**
* Created by zh on 2018/4/14.
*/
public class HttpParameterBuilder {
private static HttpParameterBuilder mParameterBuilder;
private static Map<String, RequestBody> params;
/**
* 构建私有方法
*/
private HttpParameterBuilder() {
}
/**
* 初始化对象
*/
public static HttpParameterBuilder newBuilder() {
if (mParameterBuilder == null) {
mParameterBuilder = new HttpParameterBuilder();
if (params == null) {
params = new HashMap<>();
}
}
return mParameterBuilder;
}
/**
* 添加参数
* 根据传进来的Object对象来判断是String还是File类型的参数
*/
public HttpParameterBuilder addParameter(String key, Object o) {
if (o instanceof String) {
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), (String) o);
params.put(key, body);
} else if (o instanceof File) {
RequestBody body = RequestBody.create(MediaType.parse("image/*"), (File) o);
params.put(key + "\"; filename=\"" + ((File) o).getName() + "", body);
}
return this;
}
/**
* 初始化图片的Uri来构建参数
* 一般不常用
* 主要用在拍照和图库中获取图片路径的时候
*/
public HttpParameterBuilder addFilesByUri(String key, List<Uri> uris) {
for (int i = 0; i < uris.size(); i++) {
File file = new File(uris.get(i).getPath());
RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
params.put(key + i + "\"; filename=\"" + file.getName() + "", body);
}
return this;
}
/**
* 构建RequestBody
*/
public Map<String, RequestBody> bulider() {
return params;
}
}
//MyAPP类
package zhaochuang.bawei.com.myapplication;
import android.app.Application;
import android.content.Context;
import com.facebook.drawee.backends.pipeline.Fresco;
/**
* Created by zh on 2018/4/14.
*/
public class MyApp extends Application {
public static Context con;
@Override
public void onCreate() {
super.onCreate();
con=getApplicationContext();
Fresco.initialize(this);
}
}
//PhotoUtils工具类
package zhaochuang.bawei.com.myapplication;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
/**
* @author zhengzhong on 2016/8/6 16:16
* Email zheng_zhong@163.com
*/
public class PhotoUtils {
private static final String TAG = "PhotoUtils";
/**
* @param activity 当前activity
* @param imageUri 拍照后照片存储路径
* @param requestCode 调用系统相机请求码
*/
public static void takePicture(Activity activity, Uri imageUri, int requestCode) {
//调用系统相机
Intent intentCamera = new Intent();
intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
//将拍照结果保存至photo_file的Uri中,不保留在相册中
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
activity.startActivityForResult(intentCamera, requestCode);
}
/**
* @param activity 当前activity
* @param requestCode 打开相册的请求码
*/
public static void openPic(Activity activity, int requestCode) {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
activity.startActivityForResult(photoPickerIntent, requestCode);
}
/**
* @param activity 当前activity
* @param orgUri 剪裁原图的Uri
* @param desUri 剪裁后的图片的Uri
* @param aspectX X方向的比例
* @param aspectY Y方向的比例
* @param width 剪裁图片的宽度
* @param height 剪裁图片高度
* @param requestCode 剪裁图片的请求码
*/
public static void cropImageUri(Activity activity, Uri orgUri, Uri desUri, int aspectX, int aspectY, int width, int height, int requestCode) {
Intent intent = new Intent("com.android.camera.action.CROP");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
intent.setDataAndType(orgUri, "image/*");
//发送裁剪信号
intent.putExtra("crop", "true");
intent.putExtra("aspectX", aspectX);
intent.putExtra("aspectY", aspectY);
intent.putExtra("outputX", width);
intent.putExtra("outputY", height);
intent.putExtra("scale", true);
//将剪切的图片保存到目标Uri中
intent.putExtra(MediaStore.EXTRA_OUTPUT, desUri);
//1-false用uri返回图片
//2-true直接用bitmap返回图片(此种只适用于小图片,返回图片过大会报错)
intent.putExtra("return-data", false);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
activity.startActivityForResult(intent, requestCode);
}
/**
* 读取uri所在的图片
*
* @param uri 图片对应的Uri
* @param mContext 上下文对象
* @return 获取图像的Bitmap
*/
public static Bitmap getBitmapFromUri(Uri uri, Context mContext) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), uri);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @param context 上下文对象
* @param uri 当前相册照片的Uri
* @return 解析后的Uri对应的String
*/
@SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
String pathHead = "file:///";
// 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 pathHead + Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// 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 pathHead + 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 pathHead + getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return pathHead + getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return pathHead + uri.getPath();
}
return null;
}
/**
* 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.
*/
private 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.
*/
private 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.
*/
private 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.
*/
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
}
//Retrofit网络框架
package zhaochuang.bawei.com.myapplication;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by zh on 2018/4/14.
*/
public class RetrofitUtils {
private static RetrofitUtils retrofitUtils;//工具类对象
private static ApiFunction apiFunction;//请求网络接口
public static OkHttpClient okHttpClient;
//静态快,获取OkHttpClient对象
static {
getOkHttpClient();
}
//单例锁模式
public static RetrofitUtils getInstence() {
if (retrofitUtils == null) {
synchronized (RetrofitUtils.class) {
if (retrofitUtils == null) {
retrofitUtils = new RetrofitUtils();
}
}
}
return retrofitUtils;
}
//单例模式获取okhttp
public static OkHttpClient getOkHttpClient() {
if (okHttpClient == null) {
synchronized (OkHttpClient.class) {
if (okHttpClient == null) {
File fileDir = new File(Environment.getExternalStorageDirectory(), "cache");
long fileSize = 10 * 1024 * 1024;
okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new MyInter())
//打印拦截器日志
.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.connectTimeout(15, TimeUnit.SECONDS)//设置连接超时时间
.readTimeout(15, TimeUnit.SECONDS)//设置读取超时时间
.writeTimeout(15, TimeUnit.SECONDS)//设置写入超时时间
//.cache(new Cache(fileDir,fileSize))//写入sd卡
.build();
}
}
}
return okHttpClient;
}
//私有的无参构造
private RetrofitUtils() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.Base_url)
.addConverterFactory(GsonConverterFactory.create())//添加gson转换器
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加rxjava转换器
.client(okHttpClient)//添加okhttp
.build();
apiFunction = retrofit.create(ApiFunction.class);
}
//获取
public ApiFunction API() {
return apiFunction;
}
//拦截器
static class MyInter implements Interceptor {
private int versionCode;
private Context context;
private SharedPreferences jiLu;
private String token;
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder request_builder = request.newBuilder();
context = MyApp.con;
jiLu = context.getSharedPreferences("JiLu", 0);
if (jiLu != null) {
token = jiLu.getString("token", null);
}
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
versionCode = pi.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if ("GET".equals(request.method())) {
HttpUrl.Builder builder = request.url().newBuilder();
HttpUrl build = builder.addQueryParameter("source", Constants.source)
.addQueryParameter("appVersion", versionCode + "")
.addQueryParameter("token", token + "")
.build();
request = request_builder.url(build).build();
}
if ("POST".equals(request.method())) {
if (request.body() instanceof FormBody) {
System.out.println("FormBody开始添加公共参数");
FormBody.Builder builder = new FormBody.Builder();
FormBody body = (FormBody) request.body();
for (int i = 0; i < body.size(); i++) {
builder.add(body.encodedName(i), body.encodedValue(i));
}
body = builder.add("source", Constants.source)
.add("appVersion", String.valueOf(versionCode))
.add("token", token + "")
.build();
System.out.println("开始添加公共参数55555");
request = request_builder.post(body).build();
}
//因为传送文件要用到 @Multipart注解
else if (request.body() instanceof MultipartBody) {
MultipartBody body = (MultipartBody) request.body();
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
builder.addFormDataPart("source", "android")
.addFormDataPart("appVersion", versionCode + "")
.addFormDataPart("token", token + "");
List<MultipartBody.Part> parts = body.parts();
for (MultipartBody.Part part : parts) {
builder.addPart(part);
}
request = request_builder.post(builder.build()).build();
}
}
return chain.proceed(request);
}
/**
* 添加公共参数
*
* @param oldRequest
* @return
*/
private Request addParam(Request oldRequest) {
jiLu = context.getSharedPreferences("JiLu", 0);
if (jiLu != null) {
token = jiLu.getString("token", null);
}
PackageInfo packageArchiveInfo = MyApp.con.getPackageManager().getPackageArchiveInfo(MyApp.con.getPackageName(), 0);
int versionCode = packageArchiveInfo.versionCode;
HttpUrl.Builder builder = oldRequest.url()
.newBuilder()
.setEncodedQueryParameter("source", "android")
.setEncodedQueryParameter("token", token)
.setEncodedQueryParameter("appVersion", versionCode + "");
Request newRequest = oldRequest.newBuilder()
.method(oldRequest.method(), oldRequest.body())
.url(builder.build())
.build();
return newRequest;
}
}
}
//Toast统一管理类
package zhaochuang.bawei.com.myapplication;
import android.content.Context;
import android.view.ViewGroup;
import android.widget.Toast;
/**
* Toast统一管理类
*
*/
public class ToastUtils
{
private ViewGroup.LayoutParams layoutParams;
private ToastUtils()
{
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
public static boolean isShow = true;
/**
* 短时间显示Toast
*
* @param context
* @param message
*/
public static void showShort(Context context, CharSequence message)
{
if (isShow)
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
/**
* 短时间显示Toast
*
* @param context
* @param message
*/
public static void showShort(Context context, int message)
{
if (isShow)
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
/**
* 长时间显示Toast
*
* @param context
* @param message
*/
public static void showLong(Context context, CharSequence message)
{
if (isShow)
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
/**
* 长时间显示Toast
*
* @param context
* @param message
*/
public static void showLong(Context context, int message)
{
if (isShow)
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
/**
* 自定义显示Toast时间
*
* @param context
* @param message
* @param duration
*/
public static void show(Context context, CharSequence message, int duration)
{
if (isShow)
Toast.makeText(context, message, duration).show();
}
/**
* 自定义显示Toast时间
*
* @param context
* @param message
* @param duration
*/
public static void show(Context context, int message, int duration)
{
if (isShow)
Toast.makeText(context, message, duration).show();
}
}
//Bean类
package zhaochuang.bawei.com.myapplication;
/**
* Created by zh on 2018/4/14.
*/
public class TouBean {
/**
* msg : 接口地址貌似不存在,我的天呢!好好检查一遍!!!
* code : 1
*/
private String msg;
private String code;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
//mainActivty
package zhaochuang.bawei.com.myapplication;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;
import com.facebook.drawee.view.SimpleDraweeView;
import java.io.File;
import java.util.Map;
import okhttp3.RequestBody;
import zhaochuang.bawei.com.myapplication.presenter.presenterImp;
import zhaochuang.bawei.com.myapplication.views.UpLoadVies;
public class MainActivity extends AppCompatActivity implements UpLoadVies {
private static final int CODE_GALLERY_REQUEST = 0xa0;
private static final int CODE_CAMERA_REQUEST = 0xa1;
private static final int CODE_RESULT_REQUEST = 0xa2;
private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x04;
private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
private File fileCropUri = new File(Environment.getExternalStorageDirectory(), "/crop_photo.jpg");
private Uri imageUri;
private Uri cropImageUri;
private SimpleDraweeView sd;
private Uri uri;
private PopupWindow popupWindow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sd = findViewById(R.id.sd);
//默认图片
sd.setImageURI(Uri.parse("res://com.example.xiangji70/"+R.drawable.d));
//
sd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View view1 = View.inflate(MainActivity.this, R.layout.popupwindow, null);
//view为xml布局文件
popupWindow = new PopupWindow(view1, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//必须设置
popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
popupWindow.setOutsideTouchable(true);
//显示在底部 main为activity_main布局控件中 最大的LinearLayout 的id
popupWindow.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
Button bt = view1.findViewById(R.id.bt);
Button bt1 = view1.findViewById(R.id.bt1);
Button bt2 = view1.findViewById(R.id.bt2);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
autoObtainCameraPermission();
popupWindow.dismiss();
}
});
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
autoObtainStoragePermission();
popupWindow.dismiss();
}
});
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
}
});
}
/**
* 自动获取相机权限
*/
private void autoObtainCameraPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
ToastUtils.showShort(this, "您已经拒绝过一次");
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
} else {//有权限直接调用系统相机拍照
if (hasSdcard()) {
imageUri = Uri.fromFile(fileUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
imageUri = FileProvider.getUriForFile(MainActivity.this, "com.zz.fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
} else {
ToastUtils.showShort(this, "设备没有SD卡!");
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CAMERA_PERMISSIONS_REQUEST_CODE: {//调用系统相机申请拍照权限回调
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (hasSdcard()) {
imageUri = Uri.fromFile(fileUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
imageUri = FileProvider.getUriForFile(MainActivity.this, "com.zz.fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
} else {
ToastUtils.showShort(this, "设备没有SD卡!");
}
} else {
ToastUtils.showShort(this, "请允许打开相机!!");
}
break;
}
case STORAGE_PERMISSIONS_REQUEST_CODE://调用系统相册申请Sdcard权限回调
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
} else {
ToastUtils.showShort(this, "请允许打操作SDCard!!");
}
break;
}
}
private static final int OUTPUT_X = 480;
private static final int OUTPUT_Y = 480;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
//拍照完成回调
case CODE_CAMERA_REQUEST:
cropImageUri = Uri.fromFile(fileCropUri);
PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
break;
//访问相册完成回调
case CODE_GALLERY_REQUEST:
if (hasSdcard()) {
cropImageUri = Uri.fromFile(fileCropUri);
Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
newUri = FileProvider.getUriForFile(this, "com.zz.fileprovider", new File(newUri.getPath()));
}
PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
} else {
ToastUtils.showShort(this, "设备没有SD卡!");
}
break;
case CODE_RESULT_REQUEST:
Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
if (bitmap != null) {
uri = Uri.parse(MediaStore.Images.Media.insertImage(this.getContentResolver(), bitmap, null, null));
presenterImp mypresenter=new presenterImp();
showImages(bitmap);
Map<String, RequestBody> params = HttpParameterBuilder.newBuilder()
.addParameter("uid","12509")
.addParameter("file",fileCropUri)
.bulider();
mypresenter.UpLoadpre(params,this);
}
break;
default:
}
}
}
/**
* 自动获取sdk权限
*/
private void autoObtainStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSIONS_REQUEST_CODE);
} else {
PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
}
}
/**
* 检查设备是否存在SDCard的工具方法
*/
public static boolean hasSdcard() {
String state = Environment.getExternalStorageState();
return state.equals(Environment.MEDIA_MOUNTED);
}
private void showImages(Bitmap bitmap) {
// Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null,null));
sd.setImageURI(uri);
}
@Override
public void UpLoadViesSuccoc(Object o) {
Toast.makeText(this,"上传成功",Toast.LENGTH_LONG).show();
sd.setImageURI(uri);
}
@Override
public void UpLoadViesError(String json) {
Toast.makeText(this,json,Toast.LENGTH_LONG).show();
}
}
//main布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="zhaochuang.bawei.com.myapplication.MainActivity">
<com.facebook.drawee.view.SimpleDraweeView
android:layout_width="300px"
android:layout_height="300px"
app:roundAsCircle="true"
android:id="@+id/sd"></com.facebook.drawee.view.SimpleDraweeView>
</RelativeLayout>
//popo弹出框
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:background="#ffffff"
android:layout_gravity="center_horizontal"
android:text="拍照"
android:id="@+id/bt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#DFDCD7"></View>
<Button
android:background="#ffffff"
android:layout_gravity="center_horizontal"
android:text="从相册选取"
android:id="@+id/bt1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:background="#ffffff"
android:layout_gravity="center_horizontal"
android:text="取消"
android:id="@+id/bt2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
在Android6.0中Google提出了动态申请权限的Api,调用相机拍照,访问SDcard等操作都需要先申请对应的权限如下:
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />使用FileProvider获取Uri就会将以前的file:// URI准换成content:// URI,实现一种安全的应用间数据访问,内容提供者作为Android的四大组件之一,使用同样需要在清单文件AndroidManifest.xml中进行注册的,注册方法如下 :
<provider android:name="android.support.v4.content.FileProvider" android:authorities="com.zz.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>在res目录下创建xml文件夹,file_paths.xml文件内容如下:
<?xml version="1.0" encoding="utf-8"?> <resources> <paths> <external-path name="camera_photos" path="" /> </paths> </resources>