修改用户头像

加载图片使用Glide框架
添加权限:


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lotus.looppicturesdemo">

    //权限:网络请求、外部存储
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            intent-filter>
        activity>
    application>

manifest>

在appa的gradle里声明一下

//引进glide图片加载
    compile 'com.github.bumptech.glide:glide:3.7.0'

对话框使用alertview
在appa的gradle里声明一下

//引进alertview对话框
    compile 'com.bigkoo:alertview:1.0.2'

实际使用代码为:

Glide.with(HomeActivity.this).load(xxxURLxxx).into(想显示的控件);
如:Glide.with(HomeActivity.this).load(Constant.Server_IP + userInfo.getTouxiang()).into(imgUserIcon);

实际实现代码

文件对象使用了一个自定义的名为FileMode的实体类,根据需要可做更改
1.xml相应布局为:

<LinearLayout
        android:orientation="horizontal"
        android:id="@+id/layout_user_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorWhite"
        android:padding="10dp"
        android:gravity="center_vertical">

        <ImageView
            android:background="@mipmap/ic_launcher_round"
            android:id="@+id/img_user_icon"
            android:layout_width="70dp"
            android:layout_height="70dp" />

        <TextView
            android:gravity="right"
            android:drawablePadding="5dp"
            android:layout_marginLeft="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="点击设置头像"
            android:textColor="@color/colorBlack"
            android:textSize="16sp" />
    LinearLayout>

2.activity中:
//需要的常量及变量

private final int CODE_CAMERA_REQUEST = 10000;
    private final int CODE_SELECT_REQUEST = 10001;
    private final int CODE_RESULT_REQUEST = 10002;
    private final static int RESULT_PERMISSION = 1001;
    private final static int RESULT_SUCCESS = 1002;
    private String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};//存储

//权限申请与检测

 /**
     * 开始提交请求权限
     */
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(HomeActivity.this, permissions, RESULT_SUCCESS);
    }

    /**
     * 用户权限 申请 的回调方法
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == RESULT_SUCCESS) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else {
                        //    finish();
                    }
                } else {
                    //      Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 提示用户去应用设置界面手动开启权限
     */
    private void showDialogTipUserGoToAppSettting() {

        AlertDialog dialog = new AlertDialog.Builder(HomeActivity.this)
                .setTitle("权限不可用")
                .setMessage("请在-设置-应用管理中,允许使用存储权限")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setCancelable(false).show();
    }

    /**
     * 跳转到当前应用的设置界面
     */
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, RESULT_PERMISSION);
    }

//获取图片路径

/**
     * 获得图片路径
     *
     * @param context
     * @param uri
     * @return
     */
    @SuppressLint("NewApi")
    public String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/"
                            + split[1];
                }


            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection,
                        selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * 解析图片路径
     *
     * @param context
     * @param uri
     * @param selection
     * @param selectionArgs
     * @return
     */
    public 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 index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * 判断图片的Uri是哪种
     *
     * @param uri
     * @return
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri
                .getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri
                .getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri
                .getAuthority());
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri
                .getAuthority());
    }

//获取选择的图片

/**
     * 获取选择的头像
     *
     * @param requestCode
     * @param resultCode
     * @param intent
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_SELECT_REQUEST:
                    Uri uri = null;
                    if (Build.VERSION.SDK_INT < 19) {
                        uri = intent.getData();
                    } else {
                        uri = intent.getData();
                        String fileNames = getPath(this, uri);
                        uri = Uri.fromFile(new File(fileNames));
                    }
                    IntentUtil.cropPhoto(HomeActivity.this, uri, CODE_RESULT_REQUEST);
                    break;
                case CODE_CAMERA_REQUEST:
                    File path = IntentUtil.getStoreLocalfilePath(HomeActivity.this);
                    IntentUtil.cropPhoto(HomeActivity.this, Uri.fromFile(path), CODE_RESULT_REQUEST);
                    break;
                case CODE_RESULT_REQUEST:
                    Bitmap bitmap = intent.getParcelableExtra("data");
                    if (null != bitmap) {
                        new SaveToFile(bitmap).execute();
                    } else {
                        Toast.makeText(getApplicationContext(), "图片出错", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case RESULT_PERMISSION:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        // 检查该权限是否已经获取
                        int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                        // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                        if (i != PackageManager.PERMISSION_GRANTED) {
                            // 提示用户应该去应用设置界面手动开启权限
                            //showDialogTipUserGoToAppSettting();
                            startRequestPermission();
                        } else {
                            IntentUtil.selectPhoto(HomeActivity.this, CODE_SELECT_REQUEST);
                        }
                    } else {
                        IntentUtil.selectPhoto(HomeActivity.this, CODE_SELECT_REQUEST);
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, intent);
    }

//保存图片并上传

/**
     * 拍照后保存图片
     */
    private class SaveToFile extends AsyncTask {
        private Bitmap cameraBitmap;

        public SaveToFile(Bitmap data) {
            this.cameraBitmap = data;
            Toast.makeText(getApplicationContext(), "正在处理中...", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected File doInBackground(Void... params) {
            File file = IntentUtil.getStoreLocalfilePath(HomeActivity.this);
            if (file.exists() && file.length() > 0) {
                file.delete();
            } else {
                FileUtil.mkdirs(file.getParentFile());
            }
            FileOutputStream fout = null;
            try {
                fout = new FileOutputStream(file);
                cameraBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                fout.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                Util.closeQuietly(fout);
            }
            return file;
        }

        @Override
        protected void onPostExecute(File file) {
            if (file != null && file.isFile() && file.length() > 20) {
                saveUserInfo(file);//上传用户头像
            } else {
                Toast.makeText(getApplicationContext(), "设置用户头像失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 上传用户头像
     */
    private void saveUserInfo(File file) {
        //TODO 上传File
        RequestParams params = new RequestParams(Constant.UPLOADICON);
        String token = CookieUtil.getUserInfo().getObj().getToken();
        params.addBodyParameter("token", token);
        params.addBodyParameter("file", file);
        // 添加get请求参数,addQueryStringParameter()函数。请求的参数以键值对的形式添加在url的后面。
        // 例如:params.addQueryStringParameter("onoff", "100")实则为http://192.168.1.249:8000/?onoff=100
        // post和get基本上类似,但是添加参数要使用,addBodyParameter。post请求参数, 添加的参数是在http的内容中,而不是url中
        x.http().post(params, new Callback.CommonCallback() {
            @Override
            public void onSuccess(FileMode result) {
                if (result != null) {
                    Toast.makeText(getApplicationContext(), "上传用户头像成功", Toast.LENGTH_SHORT).show();
                    getUserInfo();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

//调用对话框,询问选择图片的方式:相册、拍照

new AlertView(null, null, "取消", null,
                        new String[]{"拍照", "从相册选择"},
                        this, AlertView.Style.ActionSheet, new OnItemClickListener() {
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            if (FileUtil.existSDCard()) {
                                IntentUtil.cameraPhoto(HomeActivity.this, IntentUtil.getStoreLocalfilePath(HomeActivity.this), CODE_CAMERA_REQUEST);
                            } else {
                                Toast.makeText(getApplicationContext(), "没有SD卡,不能照相!!!", Toast.LENGTH_SHORT).show();
                            }
                        } else if (position == 1) {
                            // 版本判断。当手机系统大于 23 时,才有必要去判断权限是否获取
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                // 检查该权限是否已经获取
                                int i = ContextCompat.checkSelfPermission(HomeActivity.this, permissions[0]);
                                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                                if (i != PackageManager.PERMISSION_GRANTED) {
                                    // 如果没有授予该权限,就去提示用户请求
                                    startRequestPermission();
                                } else {
                                    IntentUtil.selectPhoto(HomeActivity.this, CODE_SELECT_REQUEST);
                                }
                            } else {
                                IntentUtil.selectPhoto(HomeActivity.this, CODE_SELECT_REQUEST);
                            }
                        }
                    }
                }).setCancelable(true).show();

你可能感兴趣的:(Android之路)