//首先需要添加权限
uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
//之后写一个开启小视频的按钮 点击跳转------VideoRecordActivity
1.制作视频的类 VideoRecordActivity
1.2xml文件---
activity_video_record
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.bwie.yikezhong1.View.MyActivity.VideoRecordActivity">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<com.bwie.yikezhong1.View.MyActivity.VideoRecorderView //自定义类
android:id="@+id/recoder"
android:layout_width="fill_parent"
android:layout_height="288dp"
android:layout_alignParentTop="true">
</com.bwie.yikezhong1.View.MyActivity.VideoRecorderView>
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:gravity="center_horizontal|center_vertical">
<Button
android:id="@+id/videoController"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/video_button"//点击拍摄的圆
android:text="按住拍"
android:textColor="#FFF" />
</LinearLayout>
</LinearLayout>
//VideoRecordActivity 类
public class VideoRecordActivity extends AppCompatActivity {
private static final String TAG = "你猜";
private VideoRecorderView recoderView;
private Button videoController;
private boolean isCancel = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_record);
recoderView = (VideoRecorderView) findViewById(R.id.recoder);
videoController = (Button) findViewById(R.id.videoController);
ViewGroup.LayoutParams params = recoderView.getLayoutParams();
int[] dev = getDisplayMetrics();//PhoneUtil.getResolution(this);
params.width = dev[0];
params.height = dev[1]*2/3;//(int) (((float) dev[1])*4/5);
recoderView.setLayoutParams(params);
videoController.setOnTouchListener(new VideoTouchListener());
recoderView.setRecorderListener(new VideoRecorderView.RecorderListener() {
@Override
public void recording(int maxtime, int nowtime) {
}
@SuppressLint("LongLogTag")
@Override
public void recordSuccess(File videoFile) {
//System.out.println("recordSuccess");
if (videoFile != null)
if (videoFile.getAbsolutePath() != null) {
showDialog(videoFile.getAbsolutePath());
}
}
@SuppressLint("LongLogTag")
@Override
public void recordStop() {
Log.e(TAG+".recordStop()","=========");
}
@SuppressLint("LongLogTag")
@Override
public void recordCancel() {
Log.e(TAG+".recordCancel()","=========");
releaseAnimations();
}
@SuppressLint("LongLogTag")
@Override
public void recordStart() {
Log.e(TAG+".recordStart()","=========");
}
@SuppressLint("LongLogTag")
@Override
public void videoStop() {
Log.e(TAG+".videoStop()","=========");
}
@SuppressLint("LongLogTag")
@Override
public void videoStart() {
Log.e(TAG+".videoStart()","=========");
}
});
}
public class VideoTouchListener implements View.OnTouchListener {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
recoderView.startRecord();
isCancel = false;
pressAnimations();
holdAnimations();
break;
case MotionEvent.ACTION_MOVE:
if (event.getX() > 0
&& event.getX() < videoController.getWidth()
&& event.getY() > 0
&& event.getY() < videoController.getHeight()) {
//showPressMessage();
isCancel = false;
} else {
//cancelAnimations();
isCancel = true;
}
break;
case MotionEvent.ACTION_UP:
if (isCancel) {
recoderView.cancelRecord();
}else{
recoderView.endRecord();
}
releaseAnimations();
break;
default:
break;
}
return false;
}
}
@SuppressLint("LongLogTag")
protected void showDialog(final String path) {
AlertDialog.Builder builder = new AlertDialog.Builder(VideoRecordActivity.this);
builder.setMessage("确定去发表?");
builder.setTitle("提示");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(VideoRecordActivity.this, ChuanShiPinActivity.class);
intent.putExtra("path",path);
startActivity(intent);
dialog.dismiss();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
/**
* 按下时候动画效果
*/
public void pressAnimations() {
AnimationSet animationSet = new AnimationSet(true);
ScaleAnimation scaleAnimation = new ScaleAnimation(1, 1.5f,
1, 1.5f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnimation.setDuration(200);
AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
alphaAnimation.setDuration(200);
animationSet.addAnimation(scaleAnimation);
animationSet.addAnimation(alphaAnimation);
animationSet.setFillAfter(true);
//message.setText("松手完成");
videoController.startAnimation(animationSet);
}
/**
* 释放时候动画效果
*/
public void releaseAnimations() {
AnimationSet animationSet = new AnimationSet(true);
ScaleAnimation scaleAnimation = new ScaleAnimation(1.5f, 1f,
1.5f, 1f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnimation.setDuration(200);
AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
alphaAnimation.setDuration(200);
animationSet.addAnimation(scaleAnimation);
animationSet.addAnimation(alphaAnimation);
animationSet.setFillAfter(true);
//message.setVisibility(View.GONE);
videoController.setText("按住拍");
videoController.startAnimation(animationSet);
}
public void holdAnimations() {
AnimationSet animationSet = new AnimationSet(true);
ScaleAnimation scaleAnimation = new ScaleAnimation(1.5f, 1f,
1.5f, 1f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnimation.setDuration(200);
AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
alphaAnimation.setDuration(200);
animationSet.addAnimation(scaleAnimation);
animationSet.addAnimation(alphaAnimation);
animationSet.setFillAfter(true);
videoController.setText("松手完成");
videoController.startAnimation(animationSet);
}
/**
* get resolution
*
* @return
*/
@SuppressLint("LongLogTag")
public int[] getDisplayMetrics() {
int resolution[] = new int[2];
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay()
.getMetrics(dm);
resolution[0] = dm.widthPixels;
resolution[1] = dm.heightPixels;
Log.e(TAG+".getDisplayMetrics()","DisplayMetrics.width="+dm.widthPixels+"***DisplayMetrics.height=dm.heightPixels");
return resolution;
}
}
//1.3自定义控件 展示效果
public class VideoRecorderView extends LinearLayout implements MediaRecorder.OnErrorListener {
//视频展示
private SurfaceView surfaceView;
private SurfaceHolder surfaceHoler;
private SurfaceView videoSurfaceView;
private ImageView playVideo;
//进度条
private ProgressBar progressBar_left;
private ProgressBar progressBar_right;
//录制视频
private MediaRecorder mediaRecorder;
//摄像头
private Camera camera;
private Timer timer;
//视频播放
private MediaPlayer mediaPlayer;
//时间限制
private static final int recordMaxTime = 30;
private int timeCount;
//生成的文件
private File vecordFile;
private Context context;
//正在录制
private boolean isRecording = false;
//录制成功
private boolean isSuccess = false;
private RecorderListener recorderListener;
private MediaCodec.BufferInfo mBufferInfo;
public VideoRecorderView(Context context) {
super(context, null);
this.context = context;
}
public VideoRecorderView(Context context, AttributeSet attrs) {
super(context, attrs, 0);
this.context = context;
init();
}
public VideoRecorderView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
}
private void init() {
LayoutInflater.from(context).inflate(R.layout.ui_recorder, this);
surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
videoSurfaceView = (SurfaceView) findViewById(R.id.playView);
playVideo = (ImageView) findViewById(R.id.playVideo);
progressBar_left = (ProgressBar) findViewById(R.id.progressBar_left);
progressBar_right = (ProgressBar) findViewById(R.id.progressBar_right);
progressBar_left.setMax(recordMaxTime * 20);
progressBar_right.setMax(recordMaxTime * 20);
progressBar_left.setProgress(recordMaxTime * 20);
surfaceHoler = surfaceView.getHolder();
surfaceHoler.addCallback(new CustomCallBack());
//surfaceHoler.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceHoler.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
initCamera();
playVideo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
playVideo();
}
});
}
private class CustomCallBack implements SurfaceHolder.Callback {
@Override
public void surfaceCreated(SurfaceHolder holder) {
initCamera();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
freeCameraResource();
}
}
@Override
public void onError(MediaRecorder mr, int what, int extra) {
try {
if (mr != null)
mr.reset();
} catch (Exception e) {
}
}
/**
* 初始化摄像头
*/
private void initCamera() {
if (camera != null)
freeCameraResource();
try {
camera = Camera.open();
} catch (Exception e) {
e.printStackTrace();
freeCameraResource();
}
if (camera == null)
return;
camera.setDisplayOrientation(90);
camera.autoFocus(null);
try {
camera.setPreviewDisplay(surfaceHoler);
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
camera.unlock();
}
/**
* 初始化摄像头配置
*/
private void initRecord() {
mBufferInfo = new MediaCodec.BufferInfo();
mediaRecorder = new MediaRecorder();
mediaRecorder.reset();
if (camera != null)
mediaRecorder.setCamera(camera);
mediaRecorder.setOnErrorListener(this);
mediaRecorder.setPreviewDisplay(surfaceHoler.getSurface());
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
mediaRecorder.setVideoSize(352, 288);
// mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mediaRecorder.setVideoFrameRate(15);
mediaRecorder.setVideoEncodingBitRate(1 * 1024 * 512);
mediaRecorder.setOrientationHint(90);
mediaRecorder.setMaxDuration(recordMaxTime * 1000);
mediaRecorder.setOutputFile(vecordFile.getAbsolutePath());
}
private void prepareRecord() {
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 开始录制
*/
public void startRecord() {
//录制中
if (isRecording)
return;
//创建文件
createRecordDir();
initCamera();
videoSurfaceView.setVisibility(View.GONE);
playVideo.setVisibility(View.GONE);
surfaceView.setVisibility(View.VISIBLE);
//初始化控件
initRecord();
prepareRecord();
isRecording = true;
if (recorderListener != null)
recorderListener.recordStart();
//10秒自动化结束
timeCount = 0;
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
timeCount++;
progressBar_left.setProgress(timeCount);
progressBar_right.setProgress(recordMaxTime * 20 - timeCount);
if (recorderListener != null)
recorderListener.recording(recordMaxTime * 1000, timeCount * 50);
if (timeCount == recordMaxTime * 20) {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
}
}, 0, 50);
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
endRecord();
}
}
};
/**
* 停止录制
*/
public void endRecord() {
if (!isRecording)
return;
isRecording = false;
if (recorderListener != null) {
recorderListener.recordStop();
recorderListener.recordSuccess(vecordFile);
}
stopRecord();
releaseRecord();
freeCameraResource();
videoSurfaceView.setVisibility(View.VISIBLE);
playVideo.setVisibility(View.VISIBLE);
}
/**
* 取消录制
*/
public void cancelRecord() {
videoSurfaceView.setVisibility(View.GONE);
playVideo.setVisibility(View.GONE);
surfaceView.setVisibility(View.VISIBLE);
if (!isRecording)
return;
isRecording = false;
stopRecord();
releaseRecord();
freeCameraResource();
isRecording = false;
if (vecordFile.exists())
vecordFile.delete();
if (recorderListener != null)
recorderListener.recordCancel();
initCamera();
}
/**
* 停止录制
*/
private void stopRecord() {
progressBar_left.setProgress(recordMaxTime * 20);
progressBar_right.setProgress(0);
if (timer != null)
timer.cancel();
if (mediaRecorder != null) {
// 设置后不会崩
mediaRecorder.setOnErrorListener(null);
mediaRecorder.setPreviewDisplay(null);
try {
mediaRecorder.stop();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void destoryMediaPlayer() {
if (mediaPlayer == null)
return;
mediaPlayer.setDisplay(null);
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
/**
* 播放视频
*/
public void playVideo() {
surfaceView.setVisibility(View.GONE);
videoSurfaceView.setVisibility(View.VISIBLE);
playVideo.setVisibility(View.GONE);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(vecordFile.getAbsolutePath());
mediaPlayer.setDisplay(videoSurfaceView.getHolder());
mediaPlayer.prepare();//缓冲
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
if (recorderListener != null)
recorderListener.videoStart();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if (recorderListener != null)
recorderListener.videoStop();
playVideo.setVisibility(View.VISIBLE);
}
});
}
public RecorderListener getRecorderListener() {
return recorderListener;
}
public void setRecorderListener(RecorderListener recorderListener) {
this.recorderListener = recorderListener;
}
public SurfaceView getSurfaceView() {
return surfaceView;
}
public void setSurfaceView(SurfaceView surfaceView) {
this.surfaceView = surfaceView;
}
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
public interface RecorderListener {
public void recording(int maxtime, int nowtime);
public void recordSuccess(File videoFile);
public void recordStop();
public void recordCancel();
public void recordStart();
public void videoStop();
public void videoStart();
}
/**
* 创建视频文件
*/
private void createRecordDir() {
// File sampleDir = new File(Environment.getExternalStorageDirectory() + File.separator + "WeChatVideoRecorder/");
File sampleDir = new File(Environment.getExternalStorageDirectory() , "nicai");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
File vecordDir = sampleDir;
// 创建文件
try {
vecordFile = File.createTempFile("recording", ".mp4", vecordDir);//mp4格式
} catch (IOException e) {
}
}
/**
* 释放资源
*/
private void releaseRecord() {
if (mediaRecorder != null) {
mediaRecorder.setOnErrorListener(null);
try {
mediaRecorder.release();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
mediaRecorder = null;
}
/**
* 释放摄像头资源
*/
private void freeCameraResource() {
if (null != camera) {
camera.setPreviewCallback(null);
camera.stopPreview();
camera.lock();
camera.release();
camera = null;
}
}
}
//自定义xml文件 R.layout.ui_recorder
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="2">
<SurfaceView
android:id="@+id/surfaceview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<SurfaceView
android:id="@+id/playView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal|center_vertical">
<ImageView
android:id="@+id/playVideo"
android:layout_width="32dp"
android:layout_height="32dp"
android:src="@drawable/video_button"//点击拍摄的圆图片
android:visibility="gone" />
</LinearLayout>
</FrameLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ProgressBar
android:id="@+id/progressBar_left"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="0dip"
android:layout_height="2dp"
android:layout_weight="1"
android:progress="100"
android:progressDrawable="@drawable/video_progress_color_left" />
<ProgressBar
android:id="@+id/progressBar_right"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="0dip"
android:layout_height="2dp"
android:layout_weight="1"
android:progressDrawable="@drawable/video_progress_color_right" />
</LinearLayout>
</LinearLayout>
1.@drawable/video_progress_color_left 布局文件
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<gradient
android:endColor="@android:color/holo_green_light"
android:startColor="@android:color/holo_green_light" />
</shape>
</item>
<!-- 设置进度条颜色(白色) -->
<item android:id="@android:id/progress">
<clip>
<shape>
<gradient
android:endColor="@android:color/black"
android:startColor="@android:color/black" />
</shape>
</clip>
</item>
</layer-list>
2. @drawable/video_progress_color_right
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 设置背景色(黑色) -->
<item android:id="@android:id/background">
<shape>
<gradient
android:endColor="#000000"
android:startColor="#000000" />
</shape>
</item>
<!-- 设置进度条颜色(白色) -->
<item android:id="@android:id/progress">
<clip>
<shape>
<gradient
android:endColor="@android:color/holo_green_light"
android:startColor="@android:color/holo_green_light" />
</shape>
</clip>
</item>
</layer-list>
//拍摄完成跳转的类 ChuanShiPinActivity
//xml布局 R.layout.activity_chuan_shi_pin
<RelativeLayout
android:layout_marginTop="30px"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/ed"
android:hint="视频描述"/>
<Button
android:layout_marginRight="20px"
android:layout_alignParentRight="true"
android:id="@+id/fa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送"/>
</RelativeLayout>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/iv"
android:src="@drawable/beijing1"/>
// ChuanShiPinActivitypublic class ChuanShiPinActivity extends BaseActivity implements RegView{
private ImageView iv;
private EditText ed;
Button fa;
private File TuPianfile;
private File ShipinFile;
private iPresenterImpl p;
@Override
public int bindLayout() {
return R.layout.activity_chuan_shi_pin;
}
@Override
public void initData() {
Intent intent = getIntent();
String path = intent.getStringExtra("path");
iv = findViewById(R.id.iv);
fa = findViewById(R.id.fa);
ed = findViewById(R.id.ed);
ShipinFile = new File(path);
p = new iPresenterImpl(this);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent1 = new Intent(Intent.ACTION_PICK, null);
intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent1, 1);
}
});
fa.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s = ed.getText().toString();
HttpParameterBuilder params = HttpParameterBuilder.newBuilder();//通过工具添加图片和string 上传到服务器
params.addParameter("uid", SPUtil.getSPUtil(ChuanShiPinActivity.this).getString("uid",null));
params.addParameter("latitude","40");
params.addParameter("latitude","40");
params.addParameter("videoDesc",s);
params.addParameter("videoFile",ShipinFile);
params.addParameter("coverFile",TuPianfile);
p.FaBuShiPin(params.bulider());
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//picturePath就是图片在储存卡所在的位置
String picturePath = cursor.getString(columnIndex);
TuPianfile=new File(picturePath);
cursor.close();
iv.setImageURI(selectedImage);
}
break;
}
}
@Override
public void Success(Object o) {
BaseUser bu= (BaseUser) o;
if(bu.getCode().equals("0")){
Toast.makeText(this,bu.getMsg(),Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,bu.getMsg(),Toast.LENGTH_SHORT).show();
}
}
@Override
public void Error(String error) {
Toast.makeText(this,error,Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
p.destroy();
}
}
//转化file文件和string 工具类 方便上传到服务器 HttpParameterBuilder
public class HttpParameterBuilder {
private static HttpParameterBuilder mParameterBuilder;
private static Map<String, RequestBody> params;
/**
* 构建私有方法
*/
private HttpParameterBuilder() {
}
/**
* 初始化对象
*/
public static HttpParameterBuilder newBuilder() {
if (mParameterBuilder == null) {
mParameterBuilder = new HttpParameterBuilder();
if (params == null) {
params = new HashMap<>();
}
}
return mParameterBuilder;
}
/**
* 添加参数
* 根据传进来的Object对象来判断是String还是File类型的参数
*/
public HttpParameterBuilder addParameter(String key, Object o) {
if (o instanceof String) {
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), (String) o);
params.put(key, body);
} else if (o instanceof File) {
RequestBody body = RequestBody.create(MediaType.parse("image/*"), (File) o);
params.put(key + "\"; filename=\"" + ((File) o).getName() + "", body);
}
return this;
}
/**
* 初始化图片的Uri来构建参数
* 一般不常用
* 主要用在拍照和图库中获取图片路径的时候
*/
public HttpParameterBuilder addFilesByUri(String key, List<Uri> uris) {
for (int i = 0; i < uris.size(); i++) {
File file = new File(uris.get(i).getPath());
RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
params.put(key + i + "\"; filename=\"" + file.getName() + "", body);
}
return this;
}
/**
* 构建RequestBody
*/
public Map<String, RequestBody> bulider() {
return params;
}
}
//apifuntion//上传视频文件
@Multipart
@POST("quarter/publishVideo")
Observable<BaseUser> faBuShiPin(@PartMap Map<String, RequestBody> params);
//p层@Override
public void FaBuShiPin(Map<String, RequestBody> params) {
iModel.faBuShiPin(params, new LoadListener() {
@Override
public void Success(Object o) {
regView.Success(o);
}
@Override
public void Error(String error) {
regView.Error(error);
}
});
}
//M层 public void faBuShiPin(Map<String, RequestBody> params, final LoadListener loadListener) {
RetrofitUtils.getInstence()
.API()
.faBuShiPin(params)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<BaseUser>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(BaseUser value) {
loadListener.Success(value);
}
@Override
public void onError(Throwable e) {
loadListener.Error(e.toString());
}
@Override
public void onComplete() {
}
});
//retrofit加rxjava工具类请找我之前的博客