Android - FFmpeg視頻錄制壓縮處理走過(guò)的坑

在公司里面開(kāi)發(fā)項(xiàng)目做視頻處理時(shí)遇到了問(wèn)題蔽莱,這個(gè)問(wèn)題困擾我很久了弟疆,解決了只想給大家說(shuō)出來(lái),雖然很簡(jiǎn)單的問(wèn)題盗冷,免得你們遇到我類(lèi)似的問(wèn)題再次難以自拔怠苔!

視頻壓縮處理我用了兩種方式來(lái)解決的,一種是第三方正塌,一種用了自己寫(xiě)了封裝的嘀略。
今天先給大家講解popwindow引用第三方視頻壓縮處理所注意的問(wèn)題。

package com.zontonec.ztkid.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.zontonec.ztkid.Constants;
import com.zontonec.ztkid.R;
import com.zontonec.ztkid.bean.DataRequestManager;
import com.zontonec.ztkid.net.Apn;
import com.zontonec.ztkid.net.request.ShareGrowthRequest;
import com.zontonec.ztkid.net.request.ShareRequest;
import com.zontonec.ztkid.util.Bimp;
import com.zontonec.ztkid.util.FileUtils;
import com.zontonec.ztkid.util.ImageUtil;
import com.zontonec.ztkid.util.JSONUtils;
import com.zontonec.ztkid.util.MapUtil;
import com.zontonec.ztkid.util.Tip;
import com.zontonec.ztkid.util.UploadUtil;
import com.zontonec.ztkid.videorecording.SendSmallVideoActivity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import mabeijianxi.camera.MediaRecorderActivity;
import mabeijianxi.camera.VCamera;
import mabeijianxi.camera.model.MediaRecorderConfig;
import mabeijianxi.camera.util.DeviceUtils;

public class ShareActivity extends CommonActivity{
    private EditText edit_txt;
    LayoutInflater layoutInflater;
    private byte[] mContent;
    private Bitmap myBitmap;
    private InputMethodManager manager;
    private GridView noScrollgridview;
    private GridAdapter adapter;
    private String path = "";
    private ProgressDialog progressDialog;
    //拍照
    private Uri contentUri;
    private final int NEED_CAMERA = 200;
    private static final int TAKE_PICTURE = 2;
    //相冊(cè)
    private static final int REQUEST_CAMERA = 1;
    private final int NEED_ALBUM = 100;

    //視頻
    private static final int VIDEO_RECORDING = 3;

    private ImageButton iv_back;
    private TextView sendText;

    private String module;//發(fā)布動(dòng)態(tài)目錄

    private String userid;//家長(zhǎng)id
    private String kidid;//學(xué)生id
    private String schoolid;//學(xué)校id

    private String appType;//家長(zhǎng)端
    private String appKey;//時(shí)間戳
    private String timeSpan;//時(shí)間

    private String toWhereType;//toWhereType = 5代表同步到成長(zhǎng)日記乓诽;toWhereType = 4代表同步到班級(jí)圈
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_diary);

        int value_tag = sp.readInt(Constants.VALUE_TAG, 0);
        int tag = sp.readInt(Constants.VAULE_KID, value_tag);
        userid = sp.readString(Constants.VAULE_FAMILYID + tag, "");
        kidid = sp.readString(Constants.VAULE_KIDID + tag, "");
        schoolid = sp.readString(Constants.VALUE_SCHOOLID + tag, "");

        DataRequestManager dataRequest = new DataRequestManager();
        appType = dataRequest.getAppType();
        appKey = dataRequest.getAppKey();
        timeSpan = dataRequest.getTimeSpan();

        Intent intent = this.getIntent();
        module = getIntent().getStringExtra("module");

        initActivity();
        //初始化視頻存儲(chǔ)路徑
        initSmallVideo(this);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        FileUtils.deleteDir();
        Bimp.bmp.clear();
        Bimp.drr.clear();
        Bimp.max=0;
    }

    @Override
    public void initActivity() {
        super.initActivity();
        if (module.equals("showclass")) {
            setBackTitleBar("發(fā)布班級(jí)圈");
        } else {
            setBackTitleBar("發(fā)布成長(zhǎng)日記");
        }
        iv_back = (ImageButton) this.findViewById(R.id.title_bar_back);
        iv_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        sendText = (TextView) findViewById(R.id.title_bar_right_send);
        sendText.setOnClickListener(this);
        manager = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
        noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
        edit_txt = (EditText) findViewById(R.id.edit);//編輯的文本內(nèi)容
        noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);

        //是否同步到成長(zhǎng)日記
        toWhereType = "0";
        //選擇同步時(shí)執(zhí)行如下方法
//      ((CompoundButton) findViewById(R.id.switch_main)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//          @Override
//          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//              if (module.equals("showclass")) {
//                  toWhereType = "5";
//              } else if (module.equals("showmy")) {
//                  toWhereType = "4";
//              }
//          }
//      });

        if (module.equals("showclass")) {
            ((CompoundButton) findViewById(R.id.switch_main)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked == false) {
                        toWhereType = "5";
                    } else {
                        toWhereType = "0";
                    }
                }
            });
        } else if (module.equals("showmy")) {
            ((CompoundButton) findViewById(R.id.switch_main)).setText("同步到班級(jí)圈");
            ((CompoundButton) findViewById(R.id.switch_main)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked == false) {
                        toWhereType = "4";
                    } else {
                        toWhereType = "0";
                    }
                }
            });
        }

        Init();
    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.title_bar_right_send:
                String content =edit_txt.getEditableText().toString().trim();
                if((content.equals("") || content.equals(null)) && (Bimp.drr.size() == 0)){
                    Tip.tipshort(mContext, "分享不能為空哦");
                    return;
                }
                new UpHead().execute();
                break;
            default:
                break;
        }
    }


    @SuppressLint("NewApi")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        ContentResolver resolver = mContext.getContentResolver();
        /**
         * 因?yàn)閮煞N方式都用到了startActivityForResult方法帜羊, 這個(gè)方法執(zhí)行完后都會(huì)執(zhí)行onActivityResult方法,
         * 所以為了區(qū)別到底選擇了那個(gè)方式獲取圖片要進(jìn)行判斷鸠天,
         * 這里的requestCode跟startActivityForResult里面第二個(gè)參數(shù)對(duì)應(yīng)
         */
        if (requestCode == 0) {
            try {
                // 獲得圖片的uri
                Uri originalUri = data.getData();
                // 將圖片內(nèi)容解析成字節(jié)數(shù)組
                mContent = ImageUtil.readStream(resolver.openInputStream(Uri
                        .parse(originalUri.toString())));
                // 將字節(jié)數(shù)組轉(zhuǎn)換為ImageView可調(diào)用的Bitmap對(duì)象
                myBitmap = ImageUtil.getPicFromBytes(mContent, null);
                myBitmap = ImageUtil.comp(myBitmap);
                myBitmap = ImageUtil.toRoundCorner(myBitmap, 20);
                // //把得到的圖片綁定在控件上顯示
//              add_image.setImageBitmap(myBitmap);
            } catch (Exception e) {
                // System.out.println(e.getMessage());
            }

        } else if (requestCode == REQUEST_CAMERA) {
            try {
                super.onActivityResult(requestCode, resultCode, data);
                Bundle extras = data.getExtras();
                myBitmap = (Bitmap) extras.get("data");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                mContent = baos.toByteArray();
                myBitmap = ImageUtil.toRoundCorner(myBitmap, 20);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 把拍攝的照片轉(zhuǎn)成圓角顯示在預(yù)覽控件上
            // //把得到的圖片綁定在控件上顯示
//          add_image.setImageBitmap(myBitmap);

        }else if (requestCode == TAKE_PICTURE){
            super.onActivityResult(requestCode, resultCode, data);
            if (Bimp.drr.size() < 9 && resultCode == -1) {
                Bimp.drr.add(path);

                BitmapFactory.Options op = new BitmapFactory.Options();
                //開(kāi)始讀入圖片讼育,此時(shí)把options.inJustDecodeBounds 設(shè)回true了
                op.inJustDecodeBounds = true;
                Bitmap pic = null;
                op.inJustDecodeBounds = false;
                int w = op.outWidth;//圖片的實(shí)際寬度
                float ww = 1080f;//這里設(shè)置高度為1080f
                //縮放比。由于是固定比例縮放稠集,只用高或者寬其中一個(gè)數(shù)據(jù)進(jìn)行計(jì)算即可
                int be = 1;//be=1表示不縮放
                if (w > ww) {//根據(jù)寬度固定大小縮放
                    be = (int) (op.outWidth / ww)+1;
                }
                if (be <= 0)
                    be = 1;
                op.inSampleSize = be;//設(shè)置縮放比例
                //重新讀入圖片奶段,注意此時(shí)已經(jīng)把options.inJustDecodeBounds 設(shè)回false了
                pic = BitmapFactory.decodeFile(path, op);
                FileOutputStream b = null;
                try {
                    b = new FileOutputStream(path);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                if (pic != null) {
                    pic.compress(Bitmap.CompressFormat.JPEG, 30, b);//30是壓縮率表示,壓縮70%剥纷;如果不壓縮是100痹籍,表示壓縮率為0
                }
            }
        }
    }


    public void Init() {

        noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        if(adapter==null){
            adapter = new GridAdapter(mContext);
        }
        adapter.update();
        adapter.notifyDataSetChanged();
        noScrollgridview.setAdapter(adapter);
        noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

            @SuppressLint("NewApi")
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
//                  Intent intent = new Intent(mContext,
//                          PhotoActivity.class);
//                  intent.putExtra("ID", arg2);
////                    startActivity(intent);
//                  startActivityForResult(intent, REQUEST_CAMERA);
                if (arg2 == Bimp.bmp.size()) {
                    hideKeyboard();
                    new PopupWindows(mContext,
                            noScrollgridview);
                } else {
                    Intent intent = new Intent(mContext,
                            PhotoActivity.class);
                    intent.putExtra("ID", arg2);
                    startActivity(intent);
                }
            }
        });
    }
    @SuppressLint("HandlerLeak")
    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater; // 視圖容器
        private int selectedPosition = -1;// 選中的位置
        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public void update() {
            loading();
        }

        public int getCount() {
            return (Bimp.bmp.size() + 1);
        }

        public Object getItem(int arg0) {

            return null;
        }

        public long getItemId(int arg0) {

            return 0;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        /**
         * ListView Item設(shè)置
         */
        @SuppressLint("NewApi")
        public View getView(int position, View convertView, ViewGroup parent) {
            final int coord = position;
            ViewHolder holder = null;
            if (convertView == null) {

                convertView = inflater.inflate(R.layout.item_published_grida,
                        parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

//          if(Bimp.bmp.size() > 4){
//              add_image.setVisibility(View.INVISIBLE);
//          }else{
//              add_image.setVisibility(View.VISIBLE);
//          }
//          holder.image.setImageBitmap(Bimp.bmp.get(position));
            if (position == Bimp.bmp.size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(
                        getResources(), R.mipmap.icon_addpic_unfocused));
                if (position == 9) {
                    holder.image.setVisibility(View.GONE);

                }
            } else {
                holder.image.setImageBitmap(Bimp.bmp.get(position));
            }
            return convertView;
        }

        public class ViewHolder {
            public ImageView image;
        }

        Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        adapter.notifyDataSetChanged();
                        break;
                }
                super.handleMessage(msg);
            }
        };

        public void loading() {
            new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        if (Bimp.max == Bimp.drr.size()) {
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                            break;
                        } else {
                            try {
                                String path = Bimp.drr.get(Bimp.max);
                                System.out.println(path);
                                Bitmap bm = Bimp.revitionImageSize(path);
                                Bimp.bmp.add(bm);
                                String newStr = path.substring(
                                        path.lastIndexOf("/") + 1,
                                        path.lastIndexOf("."));
                                FileUtils.saveBitmap(bm, "" + newStr);
                                Bimp.max += 1;
                                Message message = new Message();
                                message.what = 1;
                                handler.sendMessage(message);
                            } catch (IOException e) {

                                e.printStackTrace();
                            }
                        }
                    }
                }
            }).start();
        }
    }

    public String getString(String s) {
        String path = null;
        if (s == null)
            return "";
        for (int i = s.length() - 1; i > 0; i++) {
            s.charAt(i);
        }
        return path;
    }

//  protected void onRestart() {
//      adapter.update();
//      super.onStart();
//  }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        adapter.update();
        adapter.notifyDataSetChanged();
    }

    //相冊(cè) 拍照 視頻
    public class PopupWindows extends PopupWindow {

        public PopupWindows(final Context mContext, View parent) {

            View view = View
                    .inflate(mContext, R.layout.item_popupwindows, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.fade_ins));
            LinearLayout ll_popup = (LinearLayout) view
                    .findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.push_bottom_in_2));

            setWidth(LayoutParams.FILL_PARENT);
            setHeight(LayoutParams.FILL_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();

            final Button bt1 = (Button) view
                    .findViewById(R.id.item_popupwindows_camera);
            Button bt2 = (Button) view
                    .findViewById(R.id.item_popupwindows_Photo);
            Button bt3 = (Button) view
                    .findViewById(R.id.item_popupwindows_cancel);
            //視頻部分
            Button bt4 = (Button) view
                    .findViewById(R.id.item_popupwindows_video);
            bt1.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    //檢測(cè)是否有相機(jī)和讀寫(xiě)文件權(quán)限
//                    if (ActivityCompat.checkSelfPermission(ShareActivity.this, Manifest.permission.CAMERA)
//                            != PackageManager.PERMISSION_GRANTED
//                            || ActivityCompat.checkSelfPermission(ShareActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                            != PackageManager.PERMISSION_GRANTED) {
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                            requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, NEED_CAMERA);
//                        } else {
                            photo();
//                        }
//                    }
                    dismiss();
                }
            });
            bt2.setOnClickListener(new OnClickListener() {
                @SuppressLint("NewApi")
                public void onClick(View v) {

                    //檢測(cè)是否有相機(jī)和讀寫(xiě)文件權(quán)限
//                    if (ActivityCompat.checkSelfPermission(ShareActivity.this, Manifest.permission.CAMERA)
//                            != PackageManager.PERMISSION_GRANTED
//                            || ActivityCompat.checkSelfPermission(ShareActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                            != PackageManager.PERMISSION_GRANTED) {
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                            requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, NEED_ALBUM);
//                        }else {
                            Intent intent = new Intent(mContext,
                                    PhotoListActivity.class);
                            startActivityForResult(intent, REQUEST_CAMERA);
//                        }
//                    }
                   dismiss();

                }
            });
            bt3.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });
/**
 * Created by kris-liutao on 2017.
 * 小視頻錄制
 */
            bt4.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                            //進(jìn)行H264編碼二次壓縮
                            .doH264Compress(true)
                            .smallVideoWidth(480)
                            .smallVideoHeight(480)
                            .recordTimeMax(10 * 1000)
                            .maxFrameRate(20)
                            .minFrameRate(8)
                            .captureThumbnailsTime(1)
                            .recordTimeMin((int) (3.0 * 1000))
                            .build();
                    MediaRecorderActivity.goSmallVideoRecorder((Activity) mContext, SendSmallVideoActivity.class.getName(), config);
                    dismiss();

                }
            });
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,  @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case NEED_CAMERA:
                // 如果權(quán)限被拒絕,grantResults 為空
                if (grantResults.length > 0
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    photo();
                } else {
                    Tip.tipshort(mContext, "該功能需要相機(jī)和讀寫(xiě)文件權(quán)限");
                }
                break;
            case NEED_ALBUM:
                // 如果權(quán)限被拒絕晦鞋,grantResults 為空
                if (grantResults.length > 0
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(mContext,
                            PhotoListActivity.class);
                    startActivityForResult(intent, REQUEST_CAMERA);
                } else {
                    Tip.tipshort(mContext, "該功能需要相冊(cè)和讀寫(xiě)文件權(quán)限");
                }
                break;

        }
    }

    @SuppressLint("NewApi")
    public void photo() {
//      Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//      File file = new File(Environment.getExternalStorageDirectory()
//              + "/myimage/", String.valueOf(System.currentTimeMillis())
//              + ".jpg");
//      if (!file.exists())
//          file.getParentFile().mkdirs();
//      path = file.getPath();
//      Uri imageUri = Uri.fromFile(file);
//      openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//      startActivityForResult(openCameraIntent, TAKE_PICTURE);

        File imagePath = new File(Environment.getExternalStorageDirectory(), "images");
        if (!imagePath.exists()) imagePath.mkdirs();
        File newFile = new File(imagePath, "default_image.jpg");
        path = newFile.getPath();

        //第二參數(shù)是在manifest.xml定義 provider的authorities屬性
        contentUri = FileProvider.getUriForFile(this, "com.zontonec.ztkid.fileprovider", newFile);

        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //兼容版本處理蹲缠,因?yàn)?intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION) 只在5.0以上的版本有效
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            openCameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            ClipData clip =
                    ClipData.newUri(getContentResolver(), "A photo", contentUri);
            openCameraIntent.setClipData(clip);
            openCameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            List<ResolveInfo> resInfoList =
                    getPackageManager()
                            .queryIntentActivities(openCameraIntent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                grantUriPermission(packageName, contentUri,
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
        }

        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }

    class UpHead extends AsyncTask<Void, Void, String>{
        private String result;
        @Override
        protected String doInBackground(Void... params) {

            Map resultMap = null;
            try {
                String url = Apn.DMS_UPLOADFILE;

                url = url + "&module=" + module + "&userid=" + userid + "&apptype=" + appType + "&schoolid=" + schoolid + "&kidid=" + kidid;

                System.out.println("url:"+url);
                String resultjson = UploadUtil.uploadFiles(Bimp.drr, url);
//              System.out.println("resultjson:"+resultjson);
                if(resultjson==null){
                    return null;
                }else if(resultjson.equals("timeout")){
                    return "timeout";
                }else{

                    resultMap = JSONUtils.fromJson(resultjson, Map.class);
//              System.out.println("resultMap:"+resultMap);

                    List<Map> list = MapUtil
                            .getSafeMapWhenInteger((List) resultMap
                                    .get("data"));
//              System.out.println("list:"+list);
                    List<Map> maps=new ArrayList<Map>();
                    for (int i = 0; i <list.size(); i++) {
                        Map data =list.get(i);
                        if (data.get("uploadStatus").equals("0")) {
                            Map<String, String> temp = new HashMap<String, String>();
                            temp.put("sType", "1");
                            temp.put("attachmentID", MapUtil.getValueStr(data, "fileId"));
                            temp.put("attachmentUrl", MapUtil.getValueStr(data, "fileUrl"));
                            maps.add(temp);
                        }else{
                            return result;
                        }
                    }
                    try {
                        String content =edit_txt.getText().toString();
                        System.out.println("發(fā)布動(dòng)態(tài)請(qǐng)求:" + userid + "--" + kidid + "--" + appType + "--" + toWhereType + "--" + content + "--" + appKey + "--" + timeSpan + "--" + maps);
                        if (module.equals("showclass")) {
                            result = Apn.httpConnection(new ShareRequest(userid, kidid, appType, toWhereType, content, appKey, timeSpan, maps));
                        } else if (module.equals("showmy")) {
                            result = Apn.httpConnection(new ShareGrowthRequest(userid, kidid, appType, toWhereType, content, appKey, timeSpan, maps));
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }}

            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            return result;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog=new ProgressDialog(mContext);
            progressDialog.setMessage("正在分享......");
            progressDialog.setCancelable(false);
            progressDialog.show();
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            progressDialog.dismiss();
//          System.out.println("發(fā)布動(dòng)態(tài)的result:"+result);
            if(result==null){
                Tip.tipshort(mContext,"分享失敗!");
            }else if(result.equals("timeout")){
                Tip.tipshort(mContext,"上傳超時(shí)!");
            }else{
                Map resultMap = JSONUtils.fromJson(result, Map.class);
                try {
                    if (Apn.isSuccess(resultMap)) {

//                      String sumpersonpoints = MapUtil.getValueStr(resultMap, "sumpersonpoints");
//
//                      String[] sumpoint = sumpersonpoints.toString().split("\\.");
//                      int sumpoints = Integer.parseInt(sumpoint[0]);
//
//                      if (sumpoints < 20) {
//                          Tip.tipshort(mContext, "積分值 +1");
//                      } else {
//                          Tip.tipshort(mContext, "分享成功");
//                      }

                        Tip.tipshort(mContext,"分享成功");
                        //刷新視圖
                        FileUtils.deleteDir();
                        Bimp.bmp.clear();
                        Bimp.drr.clear();
                        Bimp.max=0;
                        adapter.update();
                        adapter.notifyDataSetChanged();
                        edit_txt.setText("");
//                      add_image.setVisibility(View.VISIBLE);

                        if (module.equals("showclass")) {
                            Intent intent = new Intent();
                            intent.setAction("refresh.class.fragment");
                            intent.putExtra("share", "refresh");
                            mContext.sendBroadcast(intent);
                        } else if (module.equals("showmy")) {
                            Intent intent = new Intent();
                            intent.setAction("refresh.growth.fragment");
                            intent.putExtra("share", "refresh");
                            mContext.sendBroadcast(intent);
                        }
                        finish();
                    } else {
                        Tip.tipshort(mContext,resultMap.get("data").toString());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 隱藏軟鍵盤(pán)
     */
    private void hideKeyboard() {
        if (((Activity) mContext).getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (((Activity) mContext).getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(((Activity) mContext).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    @Override
    public void initView() {
        super.initView();
    }

    private void initSmallVideo(Context context) {
        // 設(shè)置拍攝視頻緩存路徑
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        if (DeviceUtils.isZte()) {
            if (dcim.exists()) {
                VCamera.setVideoCachePath(dcim + "/beiguanhuai/");
            } else {
                VCamera.setVideoCachePath(dcim.getPath().replace("/sdcard/",
                        "/sdcard-ext/")
                        + "/beiguanhuai/");
            }
        } else {
            VCamera.setVideoCachePath(dcim + "/beiguanhuai/");
        }
        // 開(kāi)啟log輸出,ffmpeg輸出到logcat
        VCamera.setDebugMode(true);
        // 初始化拍攝SDK澎胡,必須
        VCamera.initialize(context);
    }
}

這種方式使用壓縮異常簡(jiǎn)單

第一步:
添加下面這段依賴同步
compile 'com.mabeijianxi:small-video-record:1.0.7'

第二步:
在activity或者fragment中初始化initSmallVideo()

 private void initSmallVideo(Context context) {
        // 設(shè)置拍攝視頻緩存路徑
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        if (DeviceUtils.isZte()) {
            if (dcim.exists()) {
                VCamera.setVideoCachePath(dcim + "/beiguanhuai/");
            } else {
                VCamera.setVideoCachePath(dcim.getPath().replace("/sdcard/",
                        "/sdcard-ext/")
                        + "/beiguanhuai/");
            }
        } else {
            VCamera.setVideoCachePath(dcim + "/beiguanhuai/");
        }
        // 開(kāi)啟log輸出,ffmpeg輸出到logcat
        VCamera.setDebugMode(true);
        // 初始化拍攝SDK葫盼,必須
        VCamera.initialize(context);
    }

第三步

只需要寫(xiě)個(gè)button就可啟動(dòng)

這里寫(xiě)圖片描述

這個(gè)便是處理視頻壓縮烁巫,時(shí)長(zhǎng)等等功能的代碼部分

這里寫(xiě)圖片描述

當(dāng)然這樣寫(xiě)很多人會(huì)覺(jué)得沒(méi)問(wèn)題的呀

我就是這么干的蝇棉,加上去后代碼不會(huì) 報(bào)錯(cuò)垦搬,而且運(yùn)行正常治宣,但是當(dāng)你點(diǎn)擊下面這個(gè)popwindow的按鈕時(shí)

這里寫(xiě)圖片描述

你會(huì)發(fā)現(xiàn)之前寫(xiě)的拍照退个,相冊(cè)不能使用了同眯,按鈕點(diǎn)擊無(wú)響應(yīng)湾趾,萬(wàn)般無(wú)奈看了各種博客說(shuō)什么gradle的呀芭商,SDK版本問(wèn)題的呀...........?最后還是沒(méi)能解決,還真不好注意這方面的問(wèn)題搀缠。

解決辦法

將寫(xiě)好的權(quán)限管理全部注釋掉使用EasyPermissions啊或者其他類(lèi)的來(lái)管理動(dòng)態(tài)授權(quán)蓉坎,在這里面只有簡(jiǎn)單的調(diào)用就OK了

最后每個(gè)按鈕的點(diǎn)擊事件便都能響應(yīng)
效果圖如下:


這里寫(xiě)圖片描述

CSDN請(qǐng)移步到

http://blog.csdn.net/First_CooMan##

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市胡嘿,隨后出現(xiàn)的幾起案子蛉艾,更是在濱河造成了極大的恐慌,老刑警劉巖衷敌,帶你破解...
    沈念sama閱讀 211,123評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件勿侯,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡缴罗,警方通過(guò)查閱死者的電腦和手機(jī)助琐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,031評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)面氓,“玉大人兵钮,你說(shuō)我怎么就攤上這事蛆橡。” “怎么了掘譬?”我有些...
    開(kāi)封第一講書(shū)人閱讀 156,723評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵泰演,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我葱轩,道長(zhǎng)睦焕,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,357評(píng)論 1 283
  • 正文 為了忘掉前任靴拱,我火速辦了婚禮垃喊,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘袜炕。我一直安慰自己本谜,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,412評(píng)論 5 384
  • 文/花漫 我一把揭開(kāi)白布偎窘。 她就那樣靜靜地躺著耕突,像睡著了一般。 火紅的嫁衣襯著肌膚如雪评架。 梳的紋絲不亂的頭發(fā)上眷茁,一...
    開(kāi)封第一講書(shū)人閱讀 49,760評(píng)論 1 289
  • 那天,我揣著相機(jī)與錄音纵诞,去河邊找鬼上祈。 笑死,一個(gè)胖子當(dāng)著我的面吹牛浙芙,可吹牛的內(nèi)容都是我干的登刺。 我是一名探鬼主播,決...
    沈念sama閱讀 38,904評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼嗡呼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼纸俭!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起南窗,我...
    開(kāi)封第一講書(shū)人閱讀 37,672評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤揍很,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后万伤,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體窒悔,經(jīng)...
    沈念sama閱讀 44,118評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,456評(píng)論 2 325
  • 正文 我和宋清朗相戀三年敌买,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了简珠。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,599評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡虹钮,死狀恐怖聋庵,靈堂內(nèi)的尸體忽然破棺而出膘融,到底是詐尸還是另有隱情,我是刑警寧澤祭玉,帶...
    沈念sama閱讀 34,264評(píng)論 4 328
  • 正文 年R本政府宣布氧映,位于F島的核電站,受9級(jí)特大地震影響攘宙,放射性物質(zhì)發(fā)生泄漏屯耸。R本人自食惡果不足惜拐迁,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,857評(píng)論 3 312
  • 文/蒙蒙 一蹭劈、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧线召,春花似錦铺韧、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,731評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至讯壶,卻和暖如春料仗,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背伏蚊。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,956評(píng)論 1 264
  • 我被黑心中介騙來(lái)泰國(guó)打工立轧, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人躏吊。 一個(gè)月前我還...
    沈念sama閱讀 46,286評(píng)論 2 360
  • 正文 我出身青樓氛改,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親比伏。 傳聞我的和親對(duì)象是個(gè)殘疾皇子胜卤,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,465評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 171,742評(píng)論 25 707
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件赁项、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,059評(píng)論 4 62
  • 2017.02.22 可以練習(xí)葛躏,每當(dāng)這個(gè)時(shí)候,腦袋就犯困悠菜,我這腦袋真是神奇呀紫新,一說(shuō)讓你做事情,你就犯困李剖,你可不要太...
    Carden閱讀 1,331評(píng)論 0 1
  • 我的生活真是的
    喂喲喲零么閱讀 108評(píng)論 0 0
  • 一個(gè)人行走在 曾無(wú)比熟悉的街頭 卻還是 莫名其妙的迷了路 川流不息的人群 再?zèng)]有一個(gè)你 帶著焦急的目光追尋 只剩不...
    陳皮桃汁閱讀 249評(píng)論 0 0