弹出popueWindow选择上传方式
弹出popueWindow的方法
private void showPopueWindow(){
View popView = View.inflate(this,R.layout.popupwindow_camera_need,null);
Button bt_album = (Button) popView.findViewById(R.id.btn_pop_album);
Button bt_camera = (Button) popView.findViewById(R.id.btn_pop_camera);
Button bt_cancle = (Button) popView.findViewById(R.id.btn_pop_cancel);
//获取屏幕宽高
int weight = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels*1/3;
final PopupWindow popupWindow = new PopupWindow(popView,weight,height);
popupWindow.setAnimationStyle(R.style.anim_popup_dir);
popupWindow.setFocusable(true);
//点击外部popueWindow消失
popupWindow.setOutsideTouchable(true);
bt_album.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
popupWindow.dismiss();
}
});
bt_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
takeCamera(RESULT_CAMERA_IMAGE);
popupWindow.dismiss();
}
});
bt_cancle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
//popupWindow消失屏幕变为不透明
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 1.0f;
getWindow().setAttributes(lp);
}
});
//popupWindow出现屏幕变为半透明
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 0.5f;
getWindow().setAttributes(lp);
popupWindow.showAtLocation(popView, Gravity.BOTTOM,0,50);
}
popueWindow的布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:layout_margin="10dp"
android:paddingBottom="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical" >
<Button
android:id="@+id/btn_pop_album"
android:layout_width="match_parent"
android:layout_height="45dp"
android:text="本地相册"
android:background="#ffff"
android:textSize="18sp" />
<Button
android:id="@+id/btn_pop_camera"
android:layout_width="match_parent"
android:layout_height="45dp"
android:text="相机拍摄"
android:background="#ffff"
android:textSize="18sp" />
<Button
android:id="@+id/btn_pop_cancel"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginTop="10dp"
android:background="#ffff"
android:text="取消"
android:textSize="18sp" />
</LinearLayout>
</RelativeLayout>
调起照相机的方法
private void takeCamera(int num) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(mContext.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
photoFile = createImageFile();
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
}
}
startActivityForResult(takePictureIntent, num);//跳转界面传回拍照所得数据
}
private File createImageFile() {
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File image = null;
try {
image = File.createTempFile(
generateFileName(), /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
} catch (IOException e) {
e.printStackTrace();
}
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
public static String generateFileName() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
return imageFileName;
}
接收Intent传递回来的消息
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK ) {
if (requestCode == RESULT_LOAD_IMAGE && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
final String picturePath = cursor.getString(columnIndex);
upload(picturePath);
cursor.close();
}else if (requestCode == RESULT_CAMERA_IMAGE){
SimpleTarget target = new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
upload(saveMyBitmap(resource).getAbsolutePath());
}
@Override
public void onLoadStarted(Drawable placeholder) {
super.onLoadStarted(placeholder);
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
super.onLoadFailed(e, errorDrawable);
}
};
Glide.with(RegisterUIActivity.this).load(mCurrentPhotoPath)
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(1080, 1920)//图片压缩
.centerCrop()
.dontAnimate()
.into(target);
}
}
}
//将bitmap转化为png格式
public File saveMyBitmap(Bitmap mBitmap){
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File file = null;
try {
file = File.createTempFile(
UploadAccess.generateFileName(), /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
FileOutputStream out=new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 20, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
图片上传方法
private void upload(String picturePath) {
final ProgressDialog pb= new ProgressDialog(this);
pb.setMessage("正在上传");
pb.setCancelable(false);
pb.show();
imageUpLoad(picturePath, new Response<FileUpload>() {
@Override
public void onSuccess(FileUpload response) {
super.onSuccess(response);
if (response.success) {
myFileId = response.fileID;
runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtils.showShortToast("上传成功");
pb.dismiss();
}
});
}
}
@Override
public void onFaile(String e) {
super.onFaile(e);
runOnUiThread(new Runnable() {
@Override
public void run() {
pb.dismiss();
ToastUtils.showShortToast("上传失败");
}
});
}
});
}
public static void imageUpLoad(String localPath, final Response<FileUpload> callBack) {
MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
OkHttpClient client = new OkHttpClient();
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
File f = new File(localPath);
builder.addFormDataPart("file", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
final MultipartBody requestBody = builder.build();
//构建请求
final Request request = new Request.Builder()
.url("http:// ")//地址
.post(requestBody)//添加请求体
.build();
client.newCall(request).enqueue(new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
callBack.onFaile(e.getMessage());
System.out.println("上传失败:e.getLocalizedMessage() = " + e.getLocalizedMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
FileUpload resultBean = new Gson().fromJson(response.body().string(), FileUpload.class);
callBack.onSuccess(resultBean);
}
});
}