圆形头像__调取相机相册赋值,并更新接口

//mainActivity代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private PopupWindow popupWindow;
    private CircleImageView civ;
    //登录成功请求数据的接口
    String url="https://www.zhaoapi.cn/user/getUserInfo";
    //修改头像的接口
    String url1="https://www.zhaoapi.cn/file/upload";
    //uid
    String uid="10792";
    //token
    String token="DA76A53B7FECCCBD4594D8F47347A1B3";
    //请求网络工具类
    private MyOkHttp danli;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //单例模式获取工具类对象
        danli = MyOkHttp.danli();
        //获取控件
        civ = findViewById(R.id.civ);
        civ.setOnClickListener(this);
        //准备post请求的参数
        Map<String,String> map=new HashMap<>();
        map.put("uid",uid);
        map.put("token",token);
        //进行post请求
        danli.PostOkHttp(url,map);
        //请求返回的结果
        danli.setMyOkHttpListener(new MyOkHttpListener() {
            @Override
            public void success(String json) {
                //解析数据
                Gson g=new Gson();
                Bean bean = g.fromJson(json, Bean.class);
                //获取头像的图片地址
                String a= (String) bean.getData().getIcon();
                //赋值给控件
                Glide.with(MainActivity.this).load(a).into(civ);

            }
             //失败的方法
            @Override
            public void error(String error) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.civ:
                //弹出popupWindow
      View v = LayoutInflater.from(this).inflate(R.layout.activity_select_pic_popup_window, null);
                //找到pop里面的选项
                Button pai = v.findViewById(R.id.btn_take_photo);
                Button xuan = v.findViewById(R.id.btn_pick_photo);
                Button qu =v.findViewById(R.id.btn_cancel);
                pai.setOnClickListener(this);
                xuan.setOnClickListener(this);
                qu.setOnClickListener(this);
                popupWindow = new PopupWindow(v, ViewGroup.LayoutParams.MATCH_PARENT, 
              ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().
                  getColor(android.R.color.transparent)));
                popupWindow.setOutsideTouchable(true);
                //显示
                popupWindow.showAtLocation(MainActivity.this.findViewById(R.id.main),
                 Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.btn_take_photo:
                //启动系统相机
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                startActivityForResult(intent, 666);
                popupWindow.dismiss();
                break;
            case R.id.btn_pick_photo:
                Intent in = new Intent(Intent.ACTION_PICK);
                //指定图片的类型
                in.setType("image/*");
                //进行回跳获取图片的地址,更新接口操作
                startActivityForResult(in, 999);
                popupWindow.dismiss();
                break;
            case R.id.btn_cancel:
                Log.e("TAG","取消");
                popupWindow.dismiss();
                break;
        }
    }
    //重写
    private static final String TAG = "MainActivity-----";
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //判断
        switch (requestCode) {
            case 666:
                //获取图片的uri
                if (data != null) {
                    Bitmap bitmap = data.getParcelableExtra("data");
                    //放入图片
                    civ.setImageBitmap(bitmap);
                    //上传头像
                   // OKHttpUtils okHttpUtils = new OKHttpUtils();
                    //HashMap<String, String> map = new HashMap<>();
                    //map.put("uid", "71");
  				    //map.put("file",);
                    //okHttpUtils.upLoadFile("url");
                }
                break;
            case 999:
                //获取图片的地址
                Uri data2 = data.getData();
                //String pathFromUri = UriToPathUtil.getImageAbsolutePath(MainActivity.this, data2);
                //将uri转成path路径 调修改头像的接口·
                String pathFromUri = UriToPathUtil.getImageAbsolutePath(MainActivity.this, data2);
                //将路径转换成file文件
                File file = new File(pathFromUri);
                //准备请求的参数,接口路径
                Map<String, String> parmas = new HashMap<>();
                parmas.put("uid", uid);
                parmas.put("source", "android");
                //调取工具类更新接口数据
                danli.uploadFile(url1, file, parmas,data2);
                //展示图片
                civ.setImageURI(data2);
        }
    }
}
//main布局文件
<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:orientation="vertical"
    android:id="@+id/main"
    tools:context="com.bwie.touxiangshangchuan.MainActivity">

    <TextView
        android:layout_gravity="center"
        android:textSize="25sp"
        android:text="个人信息"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <View

        android:layout_marginTop="5px"
        android:background="#9999"
        android:layout_width="match_parent"
        android:layout_height="0.75dp"/>

    <LinearLayout
        android:layout_gravity="center_vertical"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/cc"
            android:layout_marginLeft="10px"
            android:text="头像"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:textSize="20sp"
            android:layout_height="wrap_content" />

        <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/civ"
        android:src="@mipmap/ic_launcher"
        android:layout_width="50px"
        android:layout_height="50px" />
    </LinearLayout>
</LinearLayout>
//popupWindow布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/pop_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#9999"
        android:gravity="center_horizontal"
        android:orientation="vertical">


        <Button
            android:id="@+id/btn_take_photo"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dip"
            android:layout_marginRight="20dip"
            android:layout_marginTop="20dip"
            android:background="#8e8e8e"
            android:text="拍照"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btn_pick_photo"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dip"
            android:layout_marginRight="20dip"
            android:layout_marginTop="5dip"
            android:background="#8e8e8e"
            android:text="从相册选择"
            />

        <Button
            android:id="@+id/btn_cancel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="15dip"
            android:layout_marginLeft="20dip"
            android:layout_marginRight="20dip"
            android:layout_marginTop="15dip"
            android:background="#8e8e8e"
            android:text="取消"
            android:textColor="#ffffff"

            />
    </LinearLayout>
</RelativeLayout>
//将uri转成path路径  改变获取的相机相册地址转换为路径的工具类
public class UriToPathUtil {

    public static String getRealFilePath(Context context, final Uri uri) {
        if (null == uri)
            return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[] 
           { MediaStore.Images.ImageColumns.DATA }, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }

                }
                cursor.close();
            }
            if (data == null) {
                data = getImageAbsolutePath(context, uri);
            }

        }
        return data;
    }

    public static Uri getUri(final String filePath) {
        return Uri.fromFile(new File(filePath));
    }

    /**
     * 根据Uri获取图片绝对路径,解决Android4.4以上版本Uri转换
     *
     * @param context
     * @param imageUri
     * @author yaoxing
     * @date 2014-10-12
     */
    @TargetApi(19)
    public static String getImageAbsolutePath(Context context, Uri imageUri) {
        if (context == null || imageUri == null)
            return null;
 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT &&
           DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), 
                Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                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;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[] { split[1] };
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri))
                return imageUri.getLastPathSegment();
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) 
    {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = { column };
        try {
       cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }
    /**
     * @param uri
     *                The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri
     *                The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri
     *                The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri
     *                The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}
//Okhtto工具类,因上传参数有file 所以要多写一个方法,用这个MultipartBody.Builder 对象开启请求

public class MyOkHttp {
    //单例模式
    private  static MyOkHttp myOkHttp=null;
    MyHandler myHandler=new MyHandler();
    MyOkHttpListener myOkHttpListener;
    public static MyOkHttp danli(){
        if(myOkHttp==null){
            myOkHttp=new MyOkHttp();
        }
        return myOkHttp;
    }

    //get
    public void getOkHttp(String url){
        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                    Message msg=new Message();
                    msg.what=0;
                    msg.obj=e.toString();
                    myHandler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message msg=new Message();
                msg.what=1;
                msg.obj=response.body().string();
                myHandler.sendMessage(msg);
            }
        });
    }

    //post
    public void PostOkHttp(String url, Map<String,String> map){
              OkHttpClient client=new OkHttpClient.Builder().addInterceptor(new MyInter()).build();
              //创建FromBody
              FormBody.Builder  builder=new FormBody.Builder();
              //遍历map
              Set<String> keys = map.keySet();
        for (String key:keys) {
            String v = map.get(key);
            builder.add(key,v);
        }
        //build
        FormBody build = builder.build();
        Request request=new Request.Builder().url(url).post(build).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg=new Message();
                msg.what=0;
                msg.obj=e.toString();
                myHandler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message msg=new Message();
                msg.what=1;
                msg.obj=response.body().string();
                myHandler.sendMessage(msg);
            }
        });
    }
    //更新头像的方法
    private static final String TAG = "MyOkHttp----";
    public void uploadFile(String url, File file,Map<String, String> map,Uri data2){
        OkHttpClient okHttpClient = new OkHttpClient();
        //MultipartBody  传图片 二进制的信息要用这个
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        //遍历map   获取参数添加到builder中
        Set<String> keys = map.keySet();
        for (String key:keys) {
            String v = map.get(key);
            builder.addFormDataPart(key,v);
        }
        //把文件对象放到请求路径中
builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
        //创建 build
        MultipartBody requestBody = builder.build();
        Request request = new Request.Builder()
                .post(requestBody)//请求体
                .url(url)//指定路径  就是请求的接口
                .build();//启动
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "失败---" );
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("aaa","成功");
            }
        });
    }

    //拦截器
    class MyInter implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            //获取原来的body
            Request request = chain.request();
            RequestBody body = request.body();
            if(body instanceof FormBody){
                //遍历原来的所有参数,加到新的Body里面,最后将公共参数加到新的Body
                FormBody.Builder  newBuilder=new FormBody.Builder();
                for (int i = 0; i <((FormBody) body).size() ; i++) {
                    String name = ((FormBody) body).name(i);
                    String value = ((FormBody) body).value(i);
                    //放入新的
                    newBuilder.add(name,value);
                }
                //在将公共参数添加进去
                FormBody newBody = newBuilder.add("source", "android").build();
                //创建新的请求
                Request build = request.newBuilder().post(newBody).build();
                Response response = chain.proceed(build);
                return response;
            }
            return null;
        }
    }


    //外部访问的方法
    public void setMyOkHttpListener(MyOkHttpListener myOkHttpListener){
        this.myOkHttpListener=myOkHttpListener;
    }
    //Handler
    class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String error= (String) msg.obj;
                    myOkHttpListener.error(error);
                    break;
                case 1:
                    String json= (String) msg.obj;
                    myOkHttpListener.success(json);
                    break;
            }
        }
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值