android 意见反馈 图片处理

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/setting_gray"
    android:orientation="vertical"
    tools:context=".FeedBackActivity">

    <include layout="@layout/header" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="282dp"
        android:background="@color/white"
        android:orientation="vertical">

        <EditText
            android:id="@+id/ed_afb_problem"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="24dp"
            android:layout_marginRight="24dp"
            android:background="@null"
            android:gravity="left|top"
            android:hint="@string/input_problem"
            android:minHeight="160dp"
            android:minLines="6"
            android:paddingTop="30dp"
            android:textColor="@color/color_363636"
            android:textColorHint="@color/color_b5b5b5"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/tv_afb_current_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_marginTop="6dp"
            android:layout_marginRight="24dp"
            android:text="0/500"
            android:textColor="@color/color_7f7f7f_text_setting_sub"
            android:textSize="12sp" />

        <View
            android:layout_width="1dp"
            android:layout_height="0dp"
            android:layout_weight="5" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="64dp"
            android:layout_marginLeft="24dp"
            android:layout_marginRight="24dp"
            android:orientation="horizontal">
            <!--图片1-->
            <RelativeLayout
                android:id="@+id/rl_afb_iv_1"
                android:layout_width="64dp"
                android:layout_height="64dp">


                <ImageView
                    android:id="@+id/iv_afb_1"
                    android:layout_width="56dp"
                    android:layout_height="56dp"
                    android:layout_centerInParent="true"
                    android:src="@mipmap/image_empty" />

                <ImageView
                    android:id="@+id/iv_afb_cancel_1"
                    android:layout_width="12dp"
                    android:layout_height="12dp"
                    android:visibility="gone"
                    android:layout_alignParentRight="true"
                    android:scaleType="centerInside"
                    android:src="@mipmap/cancel_x"
                   />

            </RelativeLayout>

            <View

                android:layout_width="0dp"
                android:layout_height="1dp"
                android:layout_weight="1" />
            <!--图片2-->
            <RelativeLayout
                android:id="@+id/rl_afb_iv_2"
                android:layout_width="64dp"
                android:layout_height="64dp"
                android:visibility="invisible">


                <ImageView
                    android:id="@+id/iv_afb_2"
                    android:layout_width="56dp"
                    android:layout_height="56dp"
                    android:layout_centerInParent="true"
                    android:src="@mipmap/image_empty" />

                <ImageView
                    android:id="@+id/iv_afb_cancel_2"
                    android:layout_width="12dp"
                    android:layout_height="12dp"
                    android:layout_alignParentRight="true"
                    android:scaleType="centerInside"

                    android:src="@mipmap/cancel_x"
                    android:visibility="gone" />
            </RelativeLayout>

            <View
                android:layout_width="0dp"
                android:layout_height="1dp"
                android:layout_weight="1" />
            <!--图片3-->
            <RelativeLayout
                android:id="@+id/rl_afb_iv_3"
                android:layout_width="64dp"
                android:layout_height="64dp"
                android:visibility="invisible">


                <ImageView
                    android:id="@+id/iv_afb_3"
                    android:layout_width="56dp"
                    android:layout_height="56dp"
                    android:layout_centerInParent="true"
                    android:src="@mipmap/image_empty" />

                <ImageView

                    android:id="@+id/iv_afb_cancel_3"
                    android:layout_width="12dp"
                    android:layout_height="12dp"
                    android:layout_alignParentRight="true"
                    android:scaleType="centerInside"

                    android:src="@mipmap/cancel_x"
                    android:visibility="gone" />
            </RelativeLayout>

            <View
                android:layout_width="0dp"
                android:layout_height="1dp"
                android:layout_weight="1" />
            <!--图片4-->
            <RelativeLayout
                android:id="@+id/rl_afb_iv_4"
                android:layout_width="64dp"
                android:layout_height="64dp"
                android:visibility="invisible">


                <ImageView
                    android:id="@+id/iv_afb_4"
                    android:layout_width="56dp"
                    android:layout_height="56dp"
                    android:layout_centerInParent="true"
                    android:src="@mipmap/image_empty" />

                <ImageView

                    android:id="@+id/iv_afb_cancel_4"
                    android:layout_width="12dp"
                    android:layout_height="12dp"
                    android:layout_alignParentRight="true"
                    android:scaleType="centerInside"

                    android:src="@mipmap/cancel_x"
                    android:visibility="invisible" />
            </RelativeLayout>

            <View
                android:layout_width="0dp"
                android:layout_height="1dp"
                android:layout_weight="1" />
            <!--图片5-->
            <RelativeLayout
                android:id="@+id/rl_afb_iv_5"
                android:layout_width="64dp"
                android:layout_height="64dp"
                android:visibility="invisible">


                <ImageView
                    android:id="@+id/iv_afb_5"
                    android:layout_width="56dp"
                    android:layout_height="56dp"
                    android:layout_centerInParent="true"
                    android:src="@mipmap/image_empty" />

                <ImageView


                    android:id="@+id/iv_afb_cancel_5"
                    android:layout_width="12dp"
                    android:layout_height="12dp"
                    android:layout_alignParentRight="true"
                    android:scaleType="centerInside"

                    android:src="@mipmap/cancel_x"
                    android:visibility="gone" />
            </RelativeLayout>


        </LinearLayout>

        <View
            android:layout_width="1dp"
            android:layout_height="0dp"
            android:layout_weight="6" />

    </LinearLayout>
    <!--电话邮箱-->
    <LinearLayout
        android:id="@+id/ll_afb_phone_email"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_marginTop="12dp"
        android:background="@color/white"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="24dp"
            android:text="@string/phone_email"
            android:textColor="@color/color_5a5a5a_profilemain"
            android:textSize="16sp" />


        <EditText
            android:id="@+id/et_afb_phone_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:background="@null"
            android:hint="@string/phone_email_hint"
            android:textColor="@color/color_5a5a5a_profilemain"
            android:textSize="16sp" />


    </LinearLayout>

    <Button
        android:id="@+id/bt_afb_commit"
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="60dp"
        android:layout_marginRight="24dp"
        android:background="@drawable/shape_login_gray"
        android:text="@android:string/yes"
        android:textColor="@color/white"
        android:textSize="20dp" />

</LinearLayout>

代码

package com.huikeyun.teacher.setting;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.PermissionChecker;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.sdk.android.oss.OSSClient;
import com.bumptech.glide.Glide;
import com.huikeyun.teacher.common.RouterConfig;
import com.huikeyun.teacher.common.utils.Cemera;
import com.huikeyun.teacher.common.utils.OkManager;
import com.huikeyun.teacher.common.utils.UploadImageUtils;
import com.liuan.lib.liuanlibrary.utils.ToastUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = RouterConfig.ROUTER_SETTING_FEEDBACK)
public class FeedBackActivity extends AppCompatActivity implements View.OnLongClickListener {

    @BindView(R2.id.iv_arrow)
    ImageView mIvArrow;
    @BindView(R2.id.tv_header_title)
    TextView mTvHeaderTitle;
    @BindView(R2.id.ed_afb_problem)
    EditText mEdAfbProblem;
    @BindView(R2.id.tv_afb_current_text)
    TextView mTvAfbCurrentText;
    @BindView(R2.id.iv_afb_cancel_1)
    ImageView mIvAfbCancel1;
    @BindView(R2.id.iv_afb_1)
    ImageView mIvAfb1;
    @BindView(R2.id.rl_afb_iv_1)
    RelativeLayout mRlAfbIv1;
    @BindView(R2.id.iv_afb_cancel_2)
    ImageView mIvAfbCancel2;
    @BindView(R2.id.iv_afb_2)
    ImageView mIvAfb2;
    @BindView(R2.id.rl_afb_iv_2)
    RelativeLayout mRlAfbIv2;
    @BindView(R2.id.iv_afb_cancel_3)
    ImageView mIvAfbCancel3;
    @BindView(R2.id.iv_afb_3)
    ImageView mIvAfb3;
    @BindView(R2.id.rl_afb_iv_3)
    RelativeLayout mRlAfbIv3;
    @BindView(R2.id.iv_afb_cancel_4)
    ImageView mIvAfbCancel4;
    @BindView(R2.id.iv_afb_4)
    ImageView mIvAfb4;
    @BindView(R2.id.rl_afb_iv_4)
    RelativeLayout mRlAfbIv4;
    @BindView(R2.id.iv_afb_cancel_5)
    ImageView mIvAfbCancel5;
    @BindView(R2.id.iv_afb_5)
    ImageView mIvAfb5;
    @BindView(R2.id.rl_afb_iv_5)
    RelativeLayout mRlAfbIv5;
    @BindView(R2.id.et_afb_phone_email)
    EditText mEtAfbPhoneEmail;
    @BindView(R2.id.ll_afb_phone_email)
    LinearLayout mLlAfbPhoneEmail;
    @BindView(R2.id.bt_afb_commit)
    Button mBtAfbCommit;
    private OSSClient oss;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feed_back);
        ButterKnife.bind(this);
        initView();
        initData();
        initLongClick();
    }

    private void initLongClick() {
        mIvAfb1.setOnLongClickListener(this);
        mIvAfb2.setOnLongClickListener(this);
        mIvAfb3.setOnLongClickListener(this);
        mIvAfb4.setOnLongClickListener(this);
        mIvAfb5.setOnLongClickListener(this);
//        长按点击 后会触发OnTOuchListener 然后onClick所以要提前禁用

        mIvAfb1.setOnTouchListener(null);
        mIvAfb2.setOnTouchListener(null);
        mIvAfb3.setOnTouchListener(null);
        mIvAfb4.setOnTouchListener(null);
        mIvAfb5.setOnTouchListener(null);
    }

    private static final String TAG = "FeedBackActivity";
    private static final int REQUEST_CAMERA_PERMISSION = 1002;
    String cameraPermission = Manifest.permission.CAMERA;

    private void initData() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);
        oss = UploadImageUtils.initAliyun(this);
        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int length = s.length();
                int maxLenght = 500;
                if (length <= maxLenght) {
//                    合法数据
                    mTvAfbCurrentText.setText(length + "/" + maxLenght);

                } else {
                    mEdAfbProblem.setText(mEdAfbProblem.getText().toString().substring(0, maxLenght));
                    mEdAfbProblem.setSelection(mEdAfbProblem.length());
                    ToastUtils.showShort("文字被截取,因为文字已经超出最大限制(" + (length - maxLenght) + "个)!");
                }


                if (length > 0 && length <= maxLenght) {
                    mBtAfbCommit.setEnabled(true);
                    mBtAfbCommit.setBackground(getResources().getDrawable(R.drawable.shape_ok));
                } else {
                    mBtAfbCommit.setEnabled(false);
                    mBtAfbCommit.setBackground(getResources().getDrawable(R.drawable.shape_login_gray));
                }


            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };

        mEdAfbProblem.addTextChangedListener(watcher);
    }

    private void initView() {
        mTvHeaderTitle.setText(R.string.feedback);
    }

    private static int maxPic = 5;
    private static int currentPic = 1;
    String[] mPicNetArray = new String[5];
    String[] mPicLocalArray = new String[5];

    @OnClick({R2.id.iv_arrow, R2.id.iv_afb_cancel_1, R2.id.iv_afb_1, R2.id.rl_afb_iv_1, R2.id.iv_afb_cancel_2, R2.id.iv_afb_2, R2.id.rl_afb_iv_2, R2.id.iv_afb_cancel_3, R2.id.iv_afb_3, R2.id.rl_afb_iv_3, R2.id.iv_afb_cancel_4, R2.id.iv_afb_4, R2.id.rl_afb_iv_4, R2.id.iv_afb_cancel_5, R2.id.iv_afb_5, R2.id.rl_afb_iv_5, R2.id.ll_afb_phone_email, R2.id.bt_afb_commit})
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.iv_arrow) {
            finish();
        } else if (i == R.id.iv_afb_cancel_1) {
            //图片1 设置为空
            clearPic(1);
        } else if (i == R.id.iv_afb_1) {
            addPic(1);
        } else if (i == R.id.iv_afb_cancel_2) {
            clearPic(2);
        } else if (i == R.id.iv_afb_2) {
            addPic(2);
        } else if (i == R.id.iv_afb_cancel_3) {
            clearPic(3);
        } else if (i == R.id.iv_afb_3) {
            addPic(3);
        } else if (i == R.id.iv_afb_cancel_4) {
            clearPic(4);
        } else if (i == R.id.iv_afb_4) {
            addPic(4);
        } else if (i == R.id.iv_afb_cancel_5) {
            clearPic(5);
        } else if (i == R.id.iv_afb_5) {
            addPic(5);

        } else if (i == R.id.bt_afb_commit) {

            /*{
	"body": "123123123",
	"file": ["/uploud/asjdhgauwgd,png", "/uploud/asjdhgauwgd,png", "/uploud/asjdhgauwgd,png"],
	"contact": ""
}*/
            String body = mEdAfbProblem.getText().toString().trim();
            String contact = mEtAfbPhoneEmail.getText().toString().trim();
            String url = "test";
            HashMap hm=new HashMap();
            hm.put("body",body);
            hm.put("contact",contact);
            hm.put("file",mPicNetArray);
            OkManager.getInstance().sendStringByPostMethod(url, hm, new OkManager.CallBackJsonObject() {
                @Override
                public void onResponse(JSONObject jsonObject, String message, boolean status, String data) {

                }
            }, new OkManager.CallBackError() {
                @Override
                public void onResponse(int errorCode) {

                }
            });

        }
    }

    private void addPic(int i) {

        currentPic = i;
        changePic(FLAG_CHOOSE_IMG);
    }

    // 获取从adbox_1到adbox_64的图片
    private ImageView getPicId(int i) {
        switch (i) {
            case 0:
                return mIvAfb1;
            case 1:
                return mIvAfb2;
            case 2:
                return mIvAfb3;
            case 3:
                return mIvAfb4;
            case 4:
                return mIvAfb5;
        }
        return mIvAfb1;
    }

    private void clearPic(int i) {


        currentPic = i;
        //判断有效位数
        int effective = 0;
        for (int i2 = 0; i2 < mPicNetArray.length; i2++) {
            if (!TextUtils.isEmpty(mPicNetArray[i2])) {
                effective += 1;
            }
        }

//判断这个
        for (int i1 = 0; i1 < mPicNetArray.length; i1++) {
            //整体往前偏移1  删除掉第一个
            if (i1 >= (i - 1)) {
//                前面数组不用动。后面的向前+1 最后的一个数组设置为空
                //最后一个数据会数组越界
                if (i1 != (mPicNetArray.length - 1)) {
                    mPicNetArray[i1] = mPicNetArray[i1 + 1];
                    mPicLocalArray[i1] = mPicLocalArray[i1 + 1];
                }


            }

        }
//        最后一个数组的数据 设置为空
        mPicNetArray[effective - 1] = "";
        mPicLocalArray[effective - 1] = "";

        if (effective == 5) {
            Glide.with(this).load(R.mipmap.image_empty).into(mIvAfb5);
            mIvAfbCancel5.setVisibility(View.GONE);
        } else if (effective == 4) {
            Glide.with(this).load(R.mipmap.image_empty).into(mIvAfb4);
            mIvAfbCancel4.setVisibility(View.GONE);
            mRlAfbIv5.setVisibility(View.INVISIBLE);
        } else if (effective == 3) {
            Glide.with(this).load(R.mipmap.image_empty).into(mIvAfb3);
            mIvAfbCancel3.setVisibility(View.GONE);
            mRlAfbIv4.setVisibility(View.INVISIBLE);
        } else if (effective == 2) {
            Glide.with(this).load(R.mipmap.image_empty).into(mIvAfb2);
            mIvAfbCancel2.setVisibility(View.GONE);
            mRlAfbIv3.setVisibility(View.INVISIBLE);
        } else if (effective == 1) {
            Glide.with(this).load(R.mipmap.image_empty).into(mIvAfb1);
            mIvAfbCancel1.setVisibility(View.GONE);
            mRlAfbIv2.setVisibility(View.INVISIBLE);
        }
        //重新设置图片
        for (int i1 = 0; i1 < mPicLocalArray.length; i1++) {
            if (!TextUtils.isEmpty(mPicLocalArray[i1])) {
                Glide.with(this).load(mPicLocalArray[i1]).into(getPicId(i1));

            }
        }


    }

    private void changePic(int REQUEST_CAMERA_PERMISSION) {


        if (Build.VERSION.SDK_INT >= 23) {
            //参1 检测当前应用是否有特定权限
            //参2 需要检测权限 维系那权限 才需要动态申请
            // 危险权限 跟用户隐私相关的权限 sd卡 短信 通话记录 打带你话 位置 摄像头 录音机
            if (ActivityCompat.checkSelfPermission(this, cameraPermission) == PermissionChecker.PERMISSION_DENIED) {
                ActivityCompat.requestPermissions(this, new String[]{cameraPermission}, REQUEST_CAMERA_PERMISSION);
                return;
            } else {
                showSelectPictureMenu(this);
            }

        } else {
            showSelectPictureMenu(this);
        }

    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 10001:
                    //图片更新成功
                    Bundle data = msg.getData();
                    progressDialog.dismiss();

                    if (data != null) {
                        String avatarUrl = data.getString("avatarUrl");
                        String localUrl = data.getString("localUrl");
                        String error_messsage = data.getString("error_messsage");
                        if (!TextUtils.isEmpty(avatarUrl)) {
                            mPicNetArray[currentPic - 1] = avatarUrl;
                            mPicLocalArray[currentPic - 1] = localUrl;

                        } else {
                            ToastUtils.showLong("上传图片失败" + error_messsage);
                        }


                    }

                    break;
            }
        }
    };

    /**
     * 弹出选择照片菜单
     */

    /**
     * 本地图片选取标志
     */
    private static final int FLAG_CHOOSE_IMG = 2;


    public void showSelectPictureMenu(Activity activity) {
        Cemera.startAlbum(activity, FLAG_CHOOSE_IMG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == FLAG_CHOOSE_IMG && resultCode == RESULT_OK) {
            String picPath = "";

            if (data != null) {
                Uri uri = data.getData();
                if (!TextUtils.isEmpty(uri.getAuthority())) {
                    Cursor cursor = getContentResolver().query(uri,
                            new String[]{MediaStore.Images.Media.DATA},
                            null, null, null);
                    if (null == cursor) {
                        Toast.makeText(getApplicationContext(), "图片没找到", Toast.LENGTH_SHORT)
                                .show();
                        return;
                    }
                    cursor.moveToFirst();
                    String path = cursor.getString(cursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));
                    cursor.close();

//                    intent.putExtra("fromTag", "project");
                    picPath = path;
                } else {
                    picPath = uri.getPath();
                }

                Log.e(TAG, "onActivityResult: " + picPath);

                if (!TextUtils.isEmpty(picPath)) {
                    progressDialog.setMessage("上传中...");
                    progressDialog.show();
                    Bitmap b = BitmapFactory.decodeFile(picPath);

                    UploadImageUtils.uploadHeadImage(picPath, b, "", oss, this, "详情图上传", mHandler);
                    changeStatus(new File(picPath));
                } else {
                    ToastUtils.showLong("图片选择失败");
                }

            }
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);


        switch (requestCode) {
            case REQUEST_CAMERA_PERMISSION:

                if (grantResults[0] == PermissionChecker.PERMISSION_GRANTED) {
                    showSelectPictureMenu(this);
                } else {
                    ToastUtils.showLong(getString(R.string.add_detail_premission));
                }
                break;

        }
    }

    private void changeStatus(File picPath) {

        switch (currentPic) {
            case 1:
                if (mIvAfb1.getVisibility() != View.VISIBLE) {
                    mIvAfb1.setVisibility(View.VISIBLE);
                }
                if (mIvAfbCancel1.getVisibility() != View.VISIBLE) {
                    mIvAfbCancel1.setVisibility(View.VISIBLE);
                }
                if (mRlAfbIv2.getVisibility() != View.VISIBLE) {
                    mRlAfbIv2.setVisibility(View.VISIBLE);
                }
                Glide.with(this).load(picPath).into(mIvAfb1);
                break;
            case 2:
                if (mIvAfb2.getVisibility() != View.VISIBLE) {
                    mIvAfb2.setVisibility(View.VISIBLE);
                }
                if (mIvAfbCancel2.getVisibility() != View.VISIBLE) {
                    mIvAfbCancel2.setVisibility(View.VISIBLE);
                }
                if (mRlAfbIv3.getVisibility() != View.VISIBLE) {
                    mRlAfbIv3.setVisibility(View.VISIBLE);
                }
                Glide.with(this).load(picPath).into(mIvAfb2);
                break;
            case 3:
                if (mIvAfb3.getVisibility() != View.VISIBLE) {
                    mIvAfb3.setVisibility(View.VISIBLE);
                }
                if (mIvAfbCancel3.getVisibility() != View.VISIBLE) {
                    mIvAfbCancel3.setVisibility(View.VISIBLE);
                }
                if (mRlAfbIv4.getVisibility() != View.VISIBLE) {
                    mRlAfbIv4.setVisibility(View.VISIBLE);
                }
                Glide.with(this).load(picPath).into(mIvAfb3);
                break;
            case 4:
                if (mIvAfb4.getVisibility() != View.VISIBLE) {
                    mIvAfb4.setVisibility(View.VISIBLE);
                }
                if (mIvAfbCancel4.getVisibility() != View.VISIBLE) {
                    mIvAfbCancel4.setVisibility(View.VISIBLE);
                }
                if (mRlAfbIv5.getVisibility() != View.VISIBLE) {
                    mRlAfbIv5.setVisibility(View.VISIBLE);
                }
                Glide.with(this).load(picPath).into(mIvAfb4);
                break;
            case 5:
                if (mIvAfb5.getVisibility() != View.VISIBLE) {
                    mIvAfb5.setVisibility(View.VISIBLE);
                }
                if (mIvAfbCancel5.getVisibility() != View.VISIBLE) {
                    mIvAfbCancel5.setVisibility(View.VISIBLE);
                }

                Glide.with(this).load(picPath).into(mIvAfb5);
                break;
        }
    }

    @Override
    public boolean onLongClick(View v) {
        int i = v.getId();

        if (i == R.id.iv_afb_1) {
            clearPic(1);
            return true;
        }
        if (i == R.id.iv_afb_2) {
            clearPic(2);
            return true;
        }
        if (i == R.id.iv_afb_3) {
            clearPic(3);
            return true;
        }
        if (i == R.id.iv_afb_4) {
            clearPic(4);
            return true;
        }
        if (i == R.id.iv_afb_5) {
            clearPic(5);
            return true;
        }
        return false;

    }
}

打开系统相册

package com.huikeyun.teacher.common.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;

import androidx.core.content.FileProvider;

import com.huikeyun.teacher.common.Constants;

import java.io.File;

public class Cemera {
    public static void startCamera(Activity activity, String tmpPath,int REQUEST_CODE_CAMERA_WITH_DATA) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //适配7.0拍照取uri的处理、
        File file = new File(tmpPath);
        File fileDir = new File(Constants.HEADER_IMAGE_TMP_PATH);
//文件目录不存在就创建
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        if (Build.VERSION.SDK_INT < 24) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        } else {
            Uri uri = FileProvider.getUriForFile(activity, activity.getPackageName()+".fileprovider", file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
        }
        activity.startActivityForResult(intent, REQUEST_CODE_CAMERA_WITH_DATA);
    }
    public static void startAlbum(Activity activity,int REQUEST_CODE_FLAG_CHOOSE_IMG) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        activity.startActivityForResult(intent, REQUEST_CODE_FLAG_CHOOSE_IMG);
    }
}

上传图到阿里云oos

package com.huikeyun.teacher.common.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.google.gson.Gson;
import com.huikeyun.teacher.common.Constants;
import com.huikeyun.teacher.common.RouterConfig;
import com.huikeyun.teacher.common.bean.image.HeadImageModel;
import com.huikeyun.teacher.common.network.HKYAPi;
import com.liuan.lib.liuanlibrary.init.LiuAnUtils;
import com.tencent.mmkv.MMKV;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class UploadImageUtils {
    /**
     * 上传头像从服务器获取地址
     *
     * @param pathurl
     * @param bitmap
     */
    private static final String TAG = "UploadImageUtils";
    public static String bucketName;

    public static void uploadAliYun(final String resultData, final String aliyunPath, String imagePath, OSSClient oss, Activity activity, String type, Handler  handler) {
        PutObjectRequest put = new PutObjectRequest(bucketName, aliyunPath, imagePath);

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("wangli", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {

                Log.e(TAG, "onResponse:aliyunPath " + aliyunPath);
                Log.e(TAG, "onResponse:result " + result);
                Log.e(TAG, "onResponse:imagePath " + imagePath);
                if ("上传头像".equals(type)) {
                    Intent intent = new Intent();
                    intent.putExtra("photoUrl", "/" + aliyunPath);
                    intent.putExtra("imagePath", imagePath);
                    activity.setResult(Activity.RESULT_OK, intent);
                    activity.finish();
                } else if ("第三方注册上传头像".equals(type)) {
                    String gender = MMKV.mmkvWithID("bind_thrid").decodeString("gender", "");
                    String keyType = MMKV.mmkvWithID("bind_thrid").decodeString("keyType", "");
                    String loginKey = MMKV.mmkvWithID("bind_thrid").decodeString("loginKey", "");
                    String nickName = MMKV.mmkvWithID("bind_thrid").decodeString("nickName", "");
                    Boolean isFromWeb = MMKV.mmkvWithID("bind_thrid").decodeBool("isFromWeb", false);
                    String password = MMKV.mmkvWithID("bind_thrid").decodeString("password", "");
                    String isSigunp = MMKV.mmkvWithID("bind_thrid").decodeString("isSigunp", "");
                    int REQUEST_LOGIN_CODE = MMKV.mmkvWithID("bind_thrid").decodeInt("REQUEST_LOGIN_CODE");

                    //去拿着这个数据到下一页注册z
                    ARouter.getInstance().build(RouterConfig.ROUTER_LOGIN_BIND_PHONE)
                            .withString("gender", gender)
                            .withString("keyType", keyType)
                            .withString("loginKey", loginKey)
                            .withString("nickName", nickName)
                            .withString("avatarUrl", "/" + aliyunPath)
                            .withString("password", password)
                            .withString("isSigunp", isSigunp)
                            .withBoolean("isFromWeb", isFromWeb)
                            .navigation(activity, REQUEST_LOGIN_CODE);
                } else if ("详情图上传".equals(type)) {

                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    message.what = 10001;
                    bundle.putString("avatarUrl", "/" + aliyunPath);
                    bundle.putString("localUrl", imagePath);
                    message.setData(bundle);
                    if (handler != null) {
                        handler.handleMessage(message);
                    }

                }


            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                Log.e("wangli", "onFailure:" + request.getUploadFilePath());
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Toast.makeText(LiuAnUtils.getContext(), serviceException.getRawMessage(), Toast.LENGTH_SHORT).show();
                }

                if (handler != null) {
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    message.what = 1001;
                    bundle.putString("avatarUrl", "");
                    bundle.putString("error_messsage", "阿里服务器提交失败:错误码"+ request.getUploadFilePath());
                    message.setData(bundle);
                    handler.handleMessage(message);
                }


            }
        });
        task.waitUntilFinished();
    }

    //阿里云初始化配置
    public static OSSClient initAliyun(Context context) {
        String endpoint = Constants.ALIYUN_ENDPOINT;
        // 明文设置secret的方式建议只在测试时使用,更多鉴权模式请参考后面的`访问控制`章节
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(Constants.ALIYUN_ACCESS_KEY_ID, Constants.ALIYUN_SECRET_ACCESS_KEY);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次
        OSSClient oss = new OSSClient(context, endpoint, credentialProvider, conf);
        return oss;
    }

    /**
     * 保存bitmap对象到本地
     *
     * @param bitmap
     */
    public static String savaBitmap(Bitmap bitmap) {
        File fileDir = new File(Constants.HEADER_IMAGE_TMP_PATH);
//文件目录不存在就创建
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        String filename = Constants.TMP_PATH;
        File f = new File(filename);
        if (f.exists()) {
            f.delete();
        }

        FileOutputStream fOut = null;
        try {
            f.createNewFile();
            fOut = new FileOutputStream(f);
        } catch (Exception e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);// 把Bitmap对象解析成流
        try {
            fOut.flush();
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filename;
    }


    public static void uploadHeadImage(final String pathurl, Bitmap bitmap, String fromTag, OSSClient oss, Activity activity, String type, Handler handler) {

        if (fromTag.equals("project")) {
            bucketName = Constants.ALIYUN_CXCY_BUCKET;
        } else {
            bucketName = Constants.ALIYUN_DEFAULT_BUCKET;
        }
        String url = HKYAPi.SETTING_GET_UPLOAD_HEADER;

        HeadImageModel model = new HeadImageModel();
        model.setBucket(bucketName);
        model.setFilename(pathurl.substring(pathurl.lastIndexOf("/") + 1));
        model.setFilesize(bitmap.getByteCount());
        model.setFiletype("image/" + pathurl.substring(pathurl.lastIndexOf(".") + 1));
        Log.e("wangli", "fromTag:" + fromTag);
        if (fromTag.equals("project")) {
            model.setPrefix("project/logo");
        } else {
            model.setPrefix("uploads/avatar/link");
        }

        String requestData = new Gson().toJson(model);
        Log.e(TAG, "uploadHeadImage: " + requestData);
        OkManager.getInstance().sendStringByPostMethod(url, requestData, new OkManager.CallBackJsonObject() {
            @Override
            public void onResponse(JSONObject jsonObject, String message, boolean status, String data) {
                Log.e(TAG, "onResponse:allPath " + data);
                String imageUrl = "";

                if (fromTag.equals("project")) {
                    imageUrl = "project/" + data.substring(data.indexOf("logo/"), data.lastIndexOf("?"));
                } else {

                    imageUrl = "uploads/avatar/" + data.substring(data.indexOf("link/"), data.lastIndexOf("?"));
                }

                uploadAliYun(data, imageUrl, pathurl, oss, activity, type, handler);
            }
        }, new OkManager.CallBackError() {
            @Override
            public void onResponse(int errorCode) {
                if (handler != null) {
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    message.what = 1001;
                    bundle.putString("avatarUrl", "");
                    bundle.putString("error_messsage", "本地服务器提交失败:错误码"+url);
                    message.setData(bundle);
                    handler.handleMessage(message);
                }
            }
        });


    }
}

网络工具类

package com.huikeyun.teacher.common.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.huikeyun.teacher.common.R;
import com.huikeyun.teacher.common.RouterConfig;
import com.huikeyun.teacher.common.network.NetworkUtils;
import com.liuan.lib.liuanlibrary.init.LiuAnUtils;
import com.liuan.lib.liuanlibrary.utils.ToastUtils;
import com.tencent.mmkv.MMKV;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkManager {
    private Gson gson = null;
    private OkHttpClient client;
    private volatile static OkManager manager;
    private static final String TAG = "OkManager";
    private Handler handler;
    private Request.Builder builder;
    //提交json数据
    private static final MediaType JSON_UTF8 = MediaType.parse("application/json;charset=utf-8");
    //提交字符串
    public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown;charset=utf-8");
    //提交json非utf-8数据
    private static final MediaType JSON = MediaType.parse("application/json");

    private OkManager() {
        client = new OkHttpClient()
                .newBuilder()
                .connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)//设置读取超时时间
                .build();
        client.writeTimeoutMillis();
        gson = new Gson();
        handler = new Handler(Looper.getMainLooper());
        String access_token = MMKV.defaultMMKV().decodeString("access_token");
        builder = new Request.Builder();

//        builder.header("Accept","application/json");
//        builder.header("Accept-Encoding", "application/json");
//        builder.header("Accept", "*/*");
        builder.header("Cache-Control", "no-cache");
//        builder.header("Content-Type", "application/json");
        if (!TextUtils.isEmpty(access_token)) {
            builder.addHeader("access_token", access_token);
        }

    }

    public static OkManager instance = null;

    //采用单例模式获取对象
    public static OkManager getInstance() {


        if (instance == null) {
            instance = new OkManager();
        }
        return instance;
    }

    /**
     * 同步请求数据 在android 开发中不常用,因为阻塞UI线程
     *
     * @param url
     * @return
     */

    public String syncGitByURL(String url) {
        if (!NetworkUtils.checkedNetwork(LiuAnUtils.getContext())) {// 网络请求之前先检查网络是否可用
            ToastUtils.showLong(LiuAnUtils.getContext().getString(R.string.net_error));
            return "";
        }
        Request request = builder.url(url).get().build();
        //构建一个request请求
        Response response = null;
        try {
            //同步请求数据
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 请求指定的url返回的记过是json字符串
     *
     * @param url
     * @param callBack
     */
    public void asyncJsonStringByURL(String url, final CallBackString callBack, CallBackError errorCallBack) {
        if (initNetWork(errorCallBack)) {
            return;
        }
        final Request request = builder.url(url).get().build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                netWordFaild(call, e);

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (response != null && response.isSuccessful()) {
                    onSuccessJsonStringMethod(response.body().string(), callBack);
                } else {
                    onFailureCallBack(response.code(), response.body().string(), errorCallBack);
                }
            }
        });

    }


    /**
     * 请求返回的结果json 字符串
     *
     * @param jsonValue
     * @param callBack
     */
    private void onSuccessJsonStringMethod(final String jsonValue, CallBackString callBack) {

        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null) {
                    try {
                        callBack.onResponse(jsonValue);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

 public static String getTopActivity(Context context){
        ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
//        Log.d("Chunna.zheng", "pkg:"+cn.getPackageName());//包名
//        Log.d("Chunna.zheng", "cls:"+cn.getClassName());//包名加类名
        return cn.getClass().getSimpleName();
    }

    private void onFailureCallBack(final int errorCode, String errorMsage, CallBackError callBack) {
        String message = "";
        try {
            JSONObject jsonObject = new JSONObject(errorMsage);
            message = jsonObject.getString("message");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String simpleName = getTopActivity(LiuAnUtils.getContext());
        Log.e(TAG, "onFailureCallBack: "+ simpleName);
        if (message.equals("token失效")&&!simpleName.equals("LoginActivity")) {
            LoginUtils.clearLoginMsg(false);
            ARouter.getInstance().build(RouterConfig.ROUTER_LOGIN_LOGIN).navigation();
            ToastUtils.showLong(LiuAnUtils.getContext().getString(R.string.login_err));
            return;
        }

        ToastUtils.showLong("网络错误,错误码" + errorCode + "\n错误信息" + errorMsage);

        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null) {
                    callBack.onResponse(errorCode);
                }
            }
        });
    }


    /**
     * 请求返回的结果json 对象
     *
     * @param jsonValue
     * @param callBack
     */
    private void onSucessJsonObjectMethod(final String jsonValue, CallBackJsonObject callBack) {

        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(jsonValue);
                        Log.e(TAG, "onResponse: " + jsonObject.toString());
                        String message = jsonObject.getString("message");
                        boolean status = jsonObject.getBoolean("status");
                        String data = "";
                        if (jsonObject.has("data")) {
                            data = jsonObject.getString("data");
                        }
                        callBack.onResponse(jsonObject, message, status, data);

                    } catch (JSONException e) {
                        Log.e(TAG, "onResponse->jsonValue: " + jsonValue);
                        Log.e(TAG, "onResponse->JSONException: " + e.toString());
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public void sayncJsonObkectByURL(String url, final CallBackJsonObject callBack, CallBackError errorCallBack) {
        if (initNetWork(errorCallBack)) {
            return;
        }
        final Request request = builder.url(url).get().build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                netWordFaild(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response != null && response.isSuccessful()) {
                    onSucessJsonObjectMethod(response.body().string(), callBack);
                } else {
                    onFailureCallBack(response.code(), response.body().string(), errorCallBack);
                }
            }
        });
    }

    public void asyncGetByteByURL(String url, final CallBackByte callBack, CallBackError errorCallBack) {
        if (initNetWork(errorCallBack)) {
            return;
        }
        final Request request = builder.url(url).get().build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                netWordFaild(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response != null && response.isSuccessful()) {
                    onSucessByteMethod(response.body().bytes(), callBack);
                } else {
                    onFailureCallBack(response.code(), response.body().string(), errorCallBack);
                }
            }
        });
    }

    /**
     * 请求返回json对象
     *
     * @param url
     * @param callback
     * @param errorCallBack
     */

    public void asyncGetJsonObjectByURL(String url, final CallBackJsonObject callback, CallBackError errorCallBack) {
        if (initNetWork(errorCallBack)) {
            return;
        }
        Request request = builder.url(url).get().build();
        Log.e(TAG, "onResponse:url   " + url);

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                netWordFaild(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Headers requestHeaders = response.networkResponse().request().headers();
                Log.e(TAG, "onResponse:requestHeaders   " + requestHeaders);
                Log.e(TAG, "onResponse:response   " + response.toString());
                if (response != null && response.isSuccessful()) {
                    onSucessJsonObjectMethod(response.body().string(), callback);
                } else {
                    onFailureCallBack(response.code(), response.body().string(), errorCallBack);
                }
            }
        });
    }

    private boolean initNetWork(CallBackError errorCallBack) {
        if (!NetworkUtils.checkedNetwork(LiuAnUtils.getContext())) {// 网络请求之前先检查网络是否可用
            String net_error = LiuAnUtils.getContext().getString(R.string.net_error);
            ToastUtils.showLong(net_error);
            onFailureCallBack(-1, net_error, errorCallBack);
            return true;
        }
        return false;
    }

    public void asyncGetJsonObjectByURL(String url, HashMap hm, final CallBackJsonObject callback, CallBackError errorCallBack) {
        if (initNetWork(errorCallBack)) {
            return;
        }

        Iterator<Map.Entry<String, String>> iterator = hm.entrySet().iterator();
        int index = 0;
        while (iterator.hasNext()) {
            index++;
            Map.Entry<String, String> next = iterator.next();
            if (index == 1) {
                url += "?" + next.getKey() + "=" + next.getValue();
            } else {
                url += "&" + next.getKey() + "=" + next.getValue();
            }
        }
        RequestBody requestBody = RequestBody.create(JSON, gson.toJson(hm));
        Request request = builder.url(url).method("get", requestBody).get().build();
        Log.e(TAG, "onResponse:url   " + url);

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                netWordFaild(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Headers requestHeaders = response.networkResponse().request().headers();
                Log.e(TAG, "onResponse:requestHeaders   " + requestHeaders);
                Log.e(TAG, "onResponse:response   " + response.toString());
                if (response != null && response.isSuccessful()) {
                    onSucessJsonObjectMethod(response.body().string(), callback);
                } else {
                    onFailureCallBack(response.code(), response.body().string(), errorCallBack);
                }
            }
        });
    }


    /**
     * 采用post提交表单
     *
     * @param url
     * @param params
     * @param callBack
     * @param errorCallBack
     */

    public void sendComplexForm(String url, Map<String, String> params, final CallBackJsonObject callBack, CallBackError errorCallBack) {
        if (initNetWork(errorCallBack)) {
            return;
        }
        //表单对象,包含以input开始的对象
        FormBody.Builder builder1 = new FormBody.Builder();
        if (params != null && params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder1.add(entry.getKey(), entry.getValue());
            }
        }
        RequestBody requestBody = builder1.build();
        //采用post提交
        Request request = builder.url(url).post(requestBody).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                netWordFaild(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response != null && response.isSuccessful()) {
                    onSucessJsonObjectMethod(response.body().string(), callBack);
                } else {
                    onFailureCallBack(response.code(), response.body().string(), errorCallBack);
                }
            }
        });
    }

    /**
     * 向服务器提交数据
     *
     * @param url
     * @param content
     * @param callback
     * @param callBackError
     */
    public void sendStringByPostMethod(String url, String content, final CallBackJsonObject callback, CallBackError callBackError) {
        if (initNetWork(callBackError)) {
            return;
        }
        final Request request = builder.url(url).post(RequestBody.create(JSON, content)).build();
        Log.e(TAG, "onResponse:sendStringByPostMethod:response " + content);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                netWordFaild(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e(TAG, "onResponse:sendStringByPostMethod:response " + response);
                Headers headers = response.networkResponse().request().headers();
                Log.e(TAG, "onResponse:sendStringByPostMethod:headers " + headers);
                if (response != null && response.isSuccessful()) {

                    onSucessJsonObjectMethod(response.body().string(), callback);
                } else {
                    onFailureCallBack(response.code(), response.body().string(), callBackError);
                }
            }
        });

    }

    /**
     * 向服务器提交数据
     *
     * @param url
     * @param hashMap
     * @param callback
     */
    public void sendStringByPostMethod(String url, HashMap hashMap, final CallBackJsonObject callback, final CallBackError callBackError) {
        if (initNetWork(callBackError)) {
            return;
        }
        HashMapUtils.LogMap(hashMap);

        final Request request = builder.url(url).post(RequestBody.create(JSON, gson.toJson(hashMap))).build();
        Log.e(TAG, "onResponse:sendStringByPostMethod:url " + url);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                netWordFaild(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e(TAG, "onResponse:sendStringByPostMethod:response " + response);
                Headers headers = response.networkResponse().request().headers();
                Log.e(TAG, "onResponse:sendStringByPostMethod:headers " + headers);
                if (response != null && response.isSuccessful()) {
                    onSucessJsonObjectMethod(response.body().string(), callback);
                } else {
                    onFailureCallBack(response.code(), response.body().string(), callBackError);
                }

            }
        });


//

    }

    public void sendStringByPutMethod(String url, Object o, final CallBackJsonObject callback, final CallBackError errorCallBack) {
        if (initNetWork(errorCallBack)) {
            return;
        }
        Log.e(TAG, "onResponse:sendStringByPutMethod: gson\n" + gson.toJson(o));
        final Request request = builder.url(url).put(RequestBody.create(JSON, gson.toJson(o))).build();
        Log.e(TAG, "onResponse:sendStringByPostMethod:url " + url);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                netWordFaild(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e(TAG, "onResponse:sendStringByPostMethod:response " + response);
                Headers headers = response.networkResponse().request().headers();
                Log.e(TAG, "onResponse:sendStringByPostMethod:headers " + headers);
                if (response != null && response.isSuccessful()) {
                    onSucessJsonObjectMethod(response.body().string(), callback);
                } else {
                    onFailureCallBack(response.code(), response.body().string(), errorCallBack);
                }
            }
        });
    }

    public void asyncDownLoadImageByURL(String url, final CallBackBitmap callback, final CallBackError errorCallBack) {
        if (initNetWork(errorCallBack)) {
            return;
        }
        final Request request = builder.url(url).get().build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                netWordFaild(call, e);

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response != null && response.isSuccessful()) {
                    byte[] data = response.body().bytes();
//                    Bitmap bitmap = new CropSquareTrans().transform(BitmapFactory.decodeByteArray(data, 0, data.length));
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    callback.onResponse(bitmap);
                } else {
                    onFailureCallBack(response.code(), response.body().string(), errorCallBack);
                }
            }
        });
    }

    private void netWordFaild(Call call, IOException e) {
        if (e instanceof SocketTimeoutException) {//判断超时异常
            ToastUtils.showLong("Socket网络请求超时");
            return;
        }
        if (e instanceof ConnectException) {//判断连接异常,我这里是报Failed to connect to 10.7.5.144
            ToastUtils.showLong("网络请求超时");
            return;
        }
        ToastUtils.showLong("网络错误");


        Log.e(TAG, "网络错误" + e.toString());
    }

    /**
     * 请求返回的字节集数组对象
     *
     * @param data
     * @param callBack
     */
    private void onSucessByteMethod(final byte[] data, CallBackByte callBack) {

        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null) {
                    try {
                        callBack.onResponse(data);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public void addHeader(String access_token, String accessToken) {
        if (builder != null) {
            builder.header(access_token, accessToken);
        }
    }

    public void sendStringByPostMethodApplicationJson(String logUrl, String foodJson, CallBackJsonObject callBackJsonObject, CallBackError callBackError) {
        
    }


    public interface CallBackString {
        void onResponse(String result);
    }

    public interface CallBackByte {
        void onResponse(byte[] result);
    }

    public interface CallBackBitmap {
        void onResponse(Bitmap bitmap);
    }

    public interface CallBackJsonObject {
        void onResponse(JSONObject jsonObject, String message, boolean status, String data);
    }

    public interface CallBackError {
        void onResponse(int errorCode);
    }


}

 

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安果移不动

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值