1. 程式人生 > >Android7.0呼叫系統相機拍照、訪問相簿問題上傳到伺服器

Android7.0呼叫系統相機拍照、訪問相簿問題上傳到伺服器

//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 [email protected]
 */
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>