在公司里面開(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)
這個(gè)便是處理視頻壓縮烁巫,時(shí)長(zhǎng)等等功能的代碼部分
當(dāng)然這樣寫(xiě)很多人會(huì)覺(jué)得沒(méi)問(wèn)題的呀
我就是這么干的蝇棉,加上去后代碼不會(huì) 報(bào)錯(cuò)垦搬,而且運(yùn)行正常治宣,但是當(dāng)你點(diǎn)擊下面這個(gè)popwindow的按鈕時(shí)
你會(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)
效果圖如下: