com.anhubo.anhubo.ui.activity.unitDetial.UploadingActivity1.java Source code

Java tutorial

Introduction

Here is the source code for com.anhubo.anhubo.ui.activity.unitDetial.UploadingActivity1.java

Source

package com.anhubo.anhubo.ui.activity.unitDetial;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
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.Environment;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.anhubo.anhubo.R;
import com.anhubo.anhubo.base.BaseActivity;
import com.anhubo.anhubo.bean.MsgPerfectLicenseBean;
import com.anhubo.anhubo.protocol.Urls;
import com.anhubo.anhubo.utils.ImageFactory;
import com.anhubo.anhubo.utils.JsonUtil;
import com.anhubo.anhubo.utils.Keys;
import com.anhubo.anhubo.utils.LogUtils;
import com.anhubo.anhubo.utils.SpUtils;
import com.anhubo.anhubo.utils.ToastUtils;
import com.anhubo.anhubo.view.AlertDialog;
import com.anhubo.anhubo.view.ShowBottonDialog;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/10/17.
 */
public class UploadingActivity1 extends BaseActivity {

    private static final int CAMERA = 0;
    private static final int PICTURE = 1;
    private static final String TAG = "UploadingActivity1";
    private static final int CROP_PHOTO = 2;
    @InjectView(R.id.ll_takePhoto01)
    LinearLayout llTakePhoto01;
    @InjectView(R.id.btn_unloading01)
    Button btnUnloading01;
    @InjectView(R.id.iv_showPhoto01)
    ImageView ivShowPhoto01;

    private Button btnTakephoto;
    private Button btnPhoto;
    private Dialog dialog;
    private Dialog showDialog;
    private Uri imageUri;
    private File filePhoto01;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_uploading1;
    }

    @Override
    protected void initViews() {
        setTopBarDesc("?");

    }

    @Override
    protected void onLoadDatas() {

    }

    @OnClick({ R.id.ll_takePhoto01, R.id.btn_unloading01 })
    public void onClick(View view) {
        //
        switch (view.getId()) {
        case R.id.ll_takePhoto01:
            // ?
            showDialog();
            break;
        case R.id.btn_unloading01:
            // ??
            upLoading();
            break;
        case R.id.btn_popDialog_takephoto:
            // ?
            camera();
            break;
        case R.id.btn_popDialog_photo:
            // 
            getPhoto();
            break;
        }
    }

    /**
     * ?
     */
    private File newFile = null;

    private void upLoading() {
        // ?
        String businessid = SpUtils.getStringParam(mActivity, Keys.BUSINESSID);

        if (newFile == null) {
            new AlertDialog(mActivity).builder().setTitle("??").setMsg("???")
                    .setCancelable(true).show();
            return;
        }

        showDialog = loadProgressDialog.show(mActivity, "...");
        String url = Urls.Url_UpLoading01;
        Map<String, String> params = new HashMap<>();
        params.put("business_id", businessid);

        OkHttpUtils.post()//
                .addFile("file", "file01.png", newFile)//
                .url(url)//
                .params(params)//
                .build()//
                .execute(new MyStringCallback());
    }

    private Handler handler = new Handler();

    class MyStringCallback extends StringCallback {
        @Override
        public void onError(Request request, Exception e) {
            LogUtils.e(TAG, ":upLoading:", e);
            showDialog.dismiss();
            new AlertDialog(mActivity).builder().setTitle("??").setMsg("")
                    .setCancelable(true).show();

        }

        @Override
        public void onResponse(String response) {
            showDialog.dismiss();
            LogUtils.eNormal(TAG + ":upLoading:", response);
            MsgPerfectLicenseBean licenseBean = JsonUtil.json2Bean(response, MsgPerfectLicenseBean.class);
            if (licenseBean != null) {
                int code = licenseBean.code;
                final String msg = licenseBean.msg;
                if (code != 0) {
                    ToastUtils.showToast(mActivity, "");
                } else {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.showToast(mActivity, "?");
                            Intent intent = new Intent();
                            intent.putExtra(Keys.ISCLICK1, true);
                            setResult(1, intent);
                            finish();
                        }
                    }, 500);
                }
            }

        }
    }

    /**
     * 
     */
    private void camera() {
        takePhoto();
        dialog.dismiss();
    }

    /**
     * ?
     */
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, PICTURE); // 
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
            @NonNull int[] grantResults) {
        switch (requestCode) {
        case 1:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openAlbum();
            } else {
                Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
                //                    ToastUtils.showToast(mActivity, "You denied the permission");
            }
            break;
        default:
        }

    }

    /**
     * 
     */
    private void getPhoto() {
        if (ContextCompat.checkSelfPermission(mActivity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(mActivity,
                    new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1);
        } else {
            openAlbum();
        }
        dialog.dismiss();
    }

    private void takePhoto() {
        //?? ??
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File outputImage = new File(path, filename + ".jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //File?Uri??
        if (Build.VERSION.SDK_INT < 24) {

            imageUri = Uri.fromFile(outputImage);
        } else {
            imageUri = FileProvider.getUriForFile(mActivity, "com.luoli.cameraalbumtest.fileprovider", outputImage);
        }
        Intent tTntent = new Intent("android.media.action.IMAGE_CAPTURE"); //
        tTntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); //?
        startActivityForResult(tTntent, CAMERA); //?

    }

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

        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
        case CAMERA:
            try {
                //??
                startCameraCrop();

                break;
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
        case CROP_PHOTO://??
            try {
                //??Bitmap
                Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                if (bitmap != null) {
                    Bitmap photo = ImageFactory.ratio(bitmap, 1080, 720);
                    llTakePhoto01.setVisibility(View.GONE);

                    //
                    ivShowPhoto01.setImageBitmap(photo);
                    // ??
                    filePhoto01 = savePicture(photo, "photo01");
                    newFile = filePhoto01;
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            break;
        case PICTURE:// 
            if (resultCode == RESULT_OK) {
                // ?
                Bitmap bitmap = null;
                if (Build.VERSION.SDK_INT >= 19) {
                    // 4.4??
                    bitmap = handleImageOnKitKat(data);
                } else {
                    // 4.4?
                    bitmap = handleImageBeforeKitKat(data);
                }
                if (bitmap != null) {
                    Bitmap photo = ImageFactory.ratio(bitmap, 1080, 720);
                    llTakePhoto01.setVisibility(View.GONE);
                    //
                    ivShowPhoto01.setImageBitmap(photo);
                    // ??
                    filePhoto01 = savePicture(photo, "photo02");
                    newFile = filePhoto01;
                }
            }
            break;
        }

    }

    /**
     * ?
     */
    private void startCameraCrop() {
        // ??
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("scale", true);
        //
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        //?
        intent.putExtra("outputX", 1080);
        intent.putExtra("outputY", 720);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        //
        Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intentBc.setData(imageUri);
        this.sendBroadcast(intentBc);
        startActivityForResult(intent, CROP_PHOTO); //??ImageView
    }

    @TargetApi(19)
    private Bitmap handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        Log.d("TAG", "handleImageOnKitKat: uri is " + uri);
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // documentUridocument id?
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // ??id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // contentUri??
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // fileUri???
            imagePath = uri.getPath();
        }
        Bitmap bitmap = displayImage(imagePath);// ?
        return bitmap;
    }

    private Bitmap handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        Bitmap bitmap = displayImage(imagePath);
        return bitmap;
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // Uriselection??
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private Bitmap displayImage(String imagePath) {
        Bitmap bitmap = null;
        if (imagePath != null) {
            bitmap = BitmapFactory.decodeFile(imagePath);
            //            ivPhoto.setImageBitmap(bitmap);
        } else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
            //            ToastUtils.showToast(mActivity, "failed to get image");
        }
        return bitmap;
    }

    /**
     * ?? ?????
     **/
    private File savePicture(Bitmap bitmap, String fileName) {
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File outputImage = new File(path, fileName + ".jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
            OutputStream stream = new FileOutputStream(outputImage);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);// 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return outputImage;
    }

    /**
     * ?
     */
    private void showDialog() {
        // 
        View view = View.inflate(mActivity, R.layout.dialog_layout, null);
        View btnCancel = view.findViewById(R.id.btn_popDialog_cancel);//?
        //?
        ShowBottonDialog showBottonDialog = new ShowBottonDialog(mActivity, view, btnCancel);
        dialog = showBottonDialog.show();
        //?
        btnTakephoto = (Button) view.findViewById(R.id.btn_popDialog_takephoto);
        //?
        btnPhoto = (Button) view.findViewById(R.id.btn_popDialog_photo);
        // ?
        btnTakephoto.setOnClickListener(this);
        btnPhoto.setOnClickListener(this);
    }

    @Override
    public void onSystemUiVisibilityChange(int visibility) {

    }
}