Android 实战技术应用程序员Android知识点和文章分享

Android - FFmpeg视频录制压缩处理走过的坑

2017-09-13  本文已影响230人  Kris_liu

在公司里面开发项目做视频处理时遇到了问题,这个问题困扰我很久了,解决了只想给大家说出来,虽然很简单的问题,免得你们遇到我类似的问题再次难以自拔!

视频压缩处理我用了两种方式来解决的,一种是第三方,一种用了自己写了封装的。
今天先给大家讲解popwindow引用第三方视频压缩处理所注意的问题。

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;
    //相册
    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;//发布动态目录

    private String userid;//家长id
    private String kidid;//学生id
    private String schoolid;//学校id

    private String appType;//家长端
    private String appKey;//时间戳
    private String timeSpan;//时间

    private String toWhereType;//toWhereType = 5代表同步到成长日记;toWhereType = 4代表同步到班级圈
    @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();
        //初始化视频存储路径
        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("发布班级圈");
        } else {
            setBackTitleBar("发布成长日记");
        }
        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);//编辑的文本内容
        noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);

        //是否同步到成长日记
        toWhereType = "0";
        //选择同步时执行如下方法
//      ((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("同步到班级圈");
            ((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();
        /**
         * 因为两种方式都用到了startActivityForResult方法, 这个方法执行完后都会执行onActivityResult方法,
         * 所以为了区别到底选择了那个方式获取图片要进行判断,
         * 这里的requestCode跟startActivityForResult里面第二个参数对应
         */
        if (requestCode == 0) {
            try {
                // 获得图片的uri
                Uri originalUri = data.getData();
                // 将图片内容解析成字节数组
                mContent = ImageUtil.readStream(resolver.openInputStream(Uri
                        .parse(originalUri.toString())));
                // 将字节数组转换为ImageView可调用的Bitmap对象
                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();
            }
            // 把拍摄的照片转成圆角显示在预览控件上
            // //把得到的图片绑定在控件上显示
//          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();
                //开始读入图片,此时把options.inJustDecodeBounds 设回true了
                op.inJustDecodeBounds = true;
                Bitmap pic = null;
                op.inJustDecodeBounds = false;
                int w = op.outWidth;//图片的实际宽度
                float ww = 1080f;//这里设置高度为1080f
                //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
                int be = 1;//be=1表示不缩放
                if (w > ww) {//根据宽度固定大小缩放
                    be = (int) (op.outWidth / ww)+1;
                }
                if (be <= 0)
                    be = 1;
                op.inSampleSize = be;//设置缩放比例
                //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回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设置
         */
        @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();
    }

    //相册 拍照 视频
    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) {
                    //检测是否有相机和读写文件权限
//                    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) {

                    //检测是否有相机和读写文件权限
//                    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()
                            //进行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:
                // 如果权限被拒绝,grantResults 为空
                if (grantResults.length > 0
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    photo();
                } else {
                    Tip.tipshort(mContext, "该功能需要相机和读写文件权限");
                }
                break;
            case NEED_ALBUM:
                // 如果权限被拒绝,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, "该功能需要相册和读写文件权限");
                }
                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();

        //第二参数是在manifest.xml定义 provider的authorities属性
        contentUri = FileProvider.getUriForFile(this, "com.zontonec.ztkid.fileprovider", newFile);

        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //兼容版本处理,因为 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("发布动态请求:" + 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("发布动态的result:"+result);
            if(result==null){
                Tip.tipshort(mContext,"分享失败!");
            }else if(result.equals("timeout")){
                Tip.tipshort(mContext,"上传超时!");
            }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();
                }
            }
        }
    }
    /**
     * 隐藏软键盘
     */
    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) {
        // 设置拍摄视频缓存路径
        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/");
        }
        // 开启log输出,ffmpeg输出到logcat
        VCamera.setDebugMode(true);
        // 初始化拍摄SDK,必须
        VCamera.initialize(context);
    }
}

这种方式使用压缩异常简单

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

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

 private void initSmallVideo(Context context) {
        // 设置拍摄视频缓存路径
        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/");
        }
        // 开启log输出,ffmpeg输出到logcat
        VCamera.setDebugMode(true);
        // 初始化拍摄SDK,必须
        VCamera.initialize(context);
    }

第三步

只需要写个button就可启动

这里写图片描述

这个便是处理视频压缩,时长等等功能的代码部分

这里写图片描述

当然这样写很多人会觉得没问题的呀

我就是这么干的,加上去后代码不会 报错,而且运行正常,但是当你点击下面这个popwindow的按钮时

这里写图片描述

你会发现之前写的拍照,相册不能使用了,按钮点击无响应,万般无奈看了各种博客说什么gradle的呀,SDK版本问题的呀...........?最后还是没能解决,还真不好注意这方面的问题。

解决办法

将写好的权限管理全部注释掉使用EasyPermissions啊或者其他类的来管理动态授权,在这里面只有简单的调用就OK了

最后每个按钮的点击事件便都能响应
效果图如下:


这里写图片描述

CSDN请移步到

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

上一篇下一篇

猜你喜欢

热点阅读