|
package com.electric.chargingpile.activity;
import static com.hjq.permissions.Permission.CAMERA;
import static com.hjq.permissions.Permission.READ_MEDIA_IMAGES;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.electric.chargingpile.R;
import com.electric.chargingpile.application.MainApplication;
import com.electric.chargingpile.data.CarOwnerCertificateBean;
import com.electric.chargingpile.data.Cars;
import com.electric.chargingpile.data.Province;
import com.electric.chargingpile.engine.GlideEngine;
import com.electric.chargingpile.entity.CarModelEntity;
import com.electric.chargingpile.entity.CarSeriesEntity;
import com.electric.chargingpile.event.CarIntentModelEvent;
import com.electric.chargingpile.manager.ProfileManager;
import com.electric.chargingpile.util.BarColorUtil;
import com.electric.chargingpile.util.DES3;
import com.electric.chargingpile.util.ImageCropEngine;
import com.electric.chargingpile.util.ImageFileCompressEngine;
import com.electric.chargingpile.util.JsonUtils;
import com.electric.chargingpile.util.LoadingDialog;
import com.electric.chargingpile.util.LogUtils;
import com.electric.chargingpile.util.MeOnCameraInterceptListener;
import com.electric.chargingpile.util.MeSandboxFileEngine;
import com.electric.chargingpile.util.OkHttpUtil;
import com.electric.chargingpile.util.PhotoUtils;
import com.electric.chargingpile.util.PictureUtlis;
import com.electric.chargingpile.util.StatusConstants;
import com.electric.chargingpile.util.ToastUtil;
import com.electric.chargingpile.util.UploadUtil;
import com.electric.chargingpile.util.Util;
import com.electric.chargingpile.view.CustomProgressDialog;
import com.electric.chargingpile.view.RoundImageView;
import com.google.gson.Gson;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.umeng.analytics.MobclickAgent;
import com.yalantis.ucrop.view.OverlayView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.Call;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
public class UserInfoActivity extends Activity implements View.OnClickListener {
private static final String TAG = "UserInfoActivity";
private ImageView back;
private EditText et_nickName;
private EditText et_realName;
private ToggleButton btn_sex, btn_car;
private RelativeLayout rl_icon;
private Button cancleButton, btn_one, btn_two;
private PopupWindow popupWindow;
private View popupWindowView;
private RoundImageView iconPic;
private TextView tv_save, onclick;
private String sex = "1";
private Bitmap download_bmp;
LoadingDialog dialog;
String name0 = "";
String name1 = "";
private int cha;
private String chatime;
private Bitmap photo, output;
Context mContext;
private String car_brand, car_type;
private Spinner spinnerProvince, spinnerCity;
List<Province> pr = new ArrayList<Province>();
private CustomProgressDialog pd_info;
private String ss;
public static final int RESULT_SUCCESS = 0;
Bitmap bitmap = null;
Bitmap selectbm = null;
Bitmap servicebitmap = null;
int default_brand = -1, default_type = -1;
String chexing;
String yichexing;
private ImageView point;
String select_pinpai = "", select_chexing = "";
private TextView tv_point;
private RelativeLayout rl_point;
private android.view.animation.Animation animation;
private static final int RC_CAMERA_PERM = 123;
private LoadingDialog loadDialog;
// -2 -> 去认证, -1 -> 认证失败,0 -> 审核中,1 -> 表示通过审核,2 -> 表示意向车型。
private int certificateStatus = -2;
private LinearLayout go_certificate;
private TextView go_title;
private TextView go_desc;
private ImageView go_cursor;
private LinearLayout carIntentModel;
private TextView carModel;
private CarModelEntity mCarModelEntity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BarColorUtil.initStatusBarColor(UserInfoActivity.this);
setContentView(R.layout.activity_user_info);
EventBus.getDefault().register(this);
dialog = new LoadingDialog(this);
dialog.setCanceledOnTouchOutside(false);
mContext = this;
initView();
spinner();
getFromServer();
}
public void onEventMainThread(Province b) {
car_brand = b.getName();
car_type = b.getCities().get(b.getId()).getName();
}
private void initView() {
loadDialog = new LoadingDialog(this);
loadDialog.setCanceledOnTouchOutside(false);
rl_point = (RelativeLayout) findViewById(R.id.rl_point);
tv_point = (TextView) findViewById(R.id.tv_point);
animation = AnimationUtils.loadAnimation(UserInfoActivity.this, R.anim.nn);
animation = AnimationUtils.loadAnimation(UserInfoActivity.this, R.anim.nn);
point = (ImageView) findViewById(R.id.tv_one);
et_nickName = (EditText) findViewById(R.id.et_nickName);
et_nickName.setText(MainApplication.userNickname);
et_nickName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MobclickAgent.onEvent(getApplicationContext(), "0802", new HashMap<String, String>().put("type", "昵称"));
}
});
et_realName = (EditText) findViewById(R.id.et_realName);
Log.e(TAG, "initView: " + MainApplication.userCar);
if (MainApplication.userCar.equals("")) {
} else if ("待购".equals(MainApplication.userCar)) {
} else {
String car = MainApplication.userCar.replace("$$", " ");
String[] strarray = car.split(" ");
if (strarray.length > 1) {
car_brand = strarray[0];
car_type = strarray[1];
}
}
onclick = (TextView) findViewById(R.id.onclick);
carModel = (TextView) findViewById(R.id.carModel);
onclick.setOnClickListener(this);
back = (ImageView) findViewById(R.id.iv_back);
back.setOnClickListener(this);
rl_icon = (RelativeLayout) findViewById(R.id.rl_icon);
rl_icon.setOnClickListener(this);
btn_sex = (ToggleButton) findViewById(R.id.sex_button);
btn_sex.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Log.d("@@@@", "女");
sex = "0";
} else {
Log.d("!!!!", "男");
sex = "1";
}
}
});
btn_car = (ToggleButton) findViewById(R.id.car_button);
btn_car.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Log.d("@@@@", "nocar");
} else {
Log.d("!!!!", "havecar");
}
}
});
iconPic = (RoundImageView) findViewById(R.id.iv_user_icon);
setIcon();
tv_save = (TextView) findViewById(R.id.tv_make_sure);
tv_save.setOnClickListener(this);
go_certificate = findViewById(R.id.go_certificate);
go_certificate.setOnClickListener(this);
carIntentModel = findViewById(R.id.carIntentModel);
carIntentModel.setOnClickListener(this);
go_title = findViewById(R.id.go_title);
go_desc = findViewById(R.id.go_desc);
go_cursor = findViewById(R.id.go_cursor);
TextView phone = findViewById(R.id.phone);
String userPhone = MainApplication.userPhone;
if (userPhone.length() == 11) {
phone.setText(userPhone.substring(0, 3) + "****" + userPhone.substring(7, userPhone.length()));
}
// String carIntentModel = ProfileManager.getInstance().getCarIntentModel(this);
//
// if (!TextUtils.isEmpty(carIntentModel)){
// carModel.setText(carIntentModel);
// }
}
private void setIcon() {
if (!"".equals(MainApplication.userIcon)) {
Picasso.with(UserInfoActivity.this)
.load(MainApplication.userIcon)
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
iconPic.setImageBitmap(bitmap);
photo = ((BitmapDrawable) iconPic.getDrawable()).getBitmap();
}
@Override
public void onBitmapFailed(Drawable drawable) {
}
@Override
public void onPrepareLoad(Drawable drawable) {
}
});
} else {
iconPic.setImageResource(R.drawable.icon_user1118);
photo = ((BitmapDrawable) iconPic.getDrawable()).getBitmap();
}
}
private void spinner() {
List<Cars> cars = new ArrayList<Cars>();
Cars car = new Cars("E140ev", "1", "1");
cars.add(car);
List<Cars> cars2 = new ArrayList<Cars>();
Cars car0 = new Cars("车型", "1", "1");
cars2.add(car0);
spinnerProvince = (Spinner) this
.findViewById(R.id.spinner_province_search_event);
spinnerCity = (Spinner) this
.findViewById(R.id.spinner_city_search_event);
Province p = new Province();
p.setCities(cars2);
p.setId(1);
p.setName("品牌");
pr.add(p);
ArrayAdapter<Province> provinceAdapter = new ArrayAdapter<Province>(UserInfoActivity.this, R.layout.simple_spinner_item, pr);
spinnerProvince.setAdapter(provinceAdapter);
spinnerProvince.setOnItemSelectedListener(new ProvinceAdapter());
spinnerCity.setOnItemSelectedListener(new CityAdapter());
}
class ProvinceAdapter implements AdapterView.OnItemSelectedListener {
/**
* (non-Javadoc)
*/
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
onProvinChange(position);
Province d = pr.get(position);
try {
car_brand = d.getName();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* (non-Javadoc)
*/
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
final class CityAdapter extends ProvinceAdapter {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
car_type = (String) spinnerCity.getSelectedItem();
Log.e("car_type", car_type);
}
}
public void onProvinChange(int position) {
List<Cars> car = pr.get(position).getCities();
List<String> strName = new ArrayList<String>();
for (int i = 0; i < car.size(); i++) {
Cars c = car.get(i);
strName.add(c.getName());
}
ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(
UserInfoActivity.this, R.layout.simple_spinner_item,
android.R.id.text1, strName);
spinnerCity.setAdapter(cityAdapter);
Log.e("default_type", default_type + "");
if (default_type != -1) {
spinnerCity.setSelection(default_type);
default_type = -1;
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.onclick:
break;
case R.id.iv_back:
finish();
break;
case R.id.rl_icon:
MobclickAgent.onEvent(getApplicationContext(), "0802", new HashMap<String, String>().put("type", "头像"));
cameraTask();
break;
case R.id.tv_make_sure:
if (checkText()) {
MobclickAgent.onEvent(getApplicationContext(), "0802", new HashMap<String, String>().put("type", "保存"));
new Thread(new Runnable() {
@Override
public void run() {
shite("");
}
}).start();
if (mCarModelEntity!=null){
requestCarIntentModel();
}
dialog.show();
}
break;
case R.id.go_certificate:
// -2 -> 去认证, -1 -> 认证失败,0 -> 审核中,1 -> 表示通过审核,2 -> 表示意向车型。
if (certificateStatus == -2) {
getCarOwnerCertificateList(true);
}
MobclickAgent.onEvent(getApplicationContext(),"1151");
break;
case R.id.carIntentModel:
CarBrandActivity.actionStart(this,"1");
// startActivityForResult(new Intent(UserInfoActivity.this, SelectCarActivity.class), 11);
MobclickAgent.onEvent(getApplicationContext(),"1150");
break;
}
}
private boolean checkText() {
String nickName = et_nickName.getText().toString().trim();
if (TextUtils.isEmpty(nickName)) {
Toast.makeText(this, "请输入您的昵称", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
public void createDialog() {
if (pd_info == null) {
pd_info = CustomProgressDialog.createDialog(mContext);
pd_info.setMessage(mContext.getResources().getString(
R.string.version_updating));
pd_info.show();
}
}
public void dismissDialog() {
if (pd_info != null) {
pd_info.dismiss();
pd_info = null;
}
}
private void showWindow() {
LayoutInflater inflater = (LayoutInflater) getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
popupWindowView = inflater.inflate(R.layout.popupwindow_upload, null);
popupWindow = new PopupWindow(popupWindowView,
ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT,
true);
popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_yinying531));
popupWindow.setOutsideTouchable(true);
popupWindowView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_MENU) && (popupWindow.isShowing())) {
popupWindow.dismiss();
return true;
}
return false;
}
});
popupWindowView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (popupWindow.isShowing()) {
popupWindow.dismiss();
}
return false;
}
});
// 设置PopupWindow的弹出和消失效果
popupWindow.setAnimationStyle(R.style.popupAnimation);
cancleButton = (Button) popupWindowView
.findViewById(R.id.cancleButton);
cancleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
popupWindow.dismiss();
}
});
btn_one = (Button) popupWindowView.findViewById(R.id.tvTwo);
btn_one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
takePhoto(view);
popupWindow.dismiss();
}
});
btn_two = (Button) popupWindowView.findViewById(R.id.tvThree);
btn_two.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openPhotoAlbum();
popupWindow.dismiss();
}
});
popupWindow.showAtLocation(cancleButton, Gravity.CENTER, 0, 0);
}
public void shite(String s) {
Map<String, String> par = new HashMap<String, String>();
String file;
long appTime1 = System.currentTimeMillis() / 1000;
Log.i("appTime(long)---", appTime1 + "");
long updatetime = appTime1 - MainMapActivity.cha - 1;
Log.i("updatetime(long)---", updatetime + "");
Log.i("cha---", MainMapActivity.cha + "");
String token = String.valueOf(updatetime);
Log.i("token---", token);
try {
if (null != photo) {
Bitmap bm = imageZoom(photo);
ss = bitmapToBase64(bm);
}
par.put("file", ss);
par.put("filename", "androidapp.jpg");
} catch (Exception e) {
e.printStackTrace();
}
par.put("username", et_realName.getText().toString());
par.put("nickname", et_nickName.getText().toString());
par.put("sex", sex);
try {
par.put("token", DES3.encode(token));
} catch (Exception e) {
e.printStackTrace();
}
try {
String u = UploadUtil.post(
MainApplication.url + "/zhannew/basic/web/index.php/tpmember/full?id=" + MainApplication.userId,
par, null);
Message msg = new Message();
msg.obj = u;
msg.what = 2;
handle.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 拍照
*
* @param view
*/
public void takePhoto(View view) {
PictureSelector.create(this)
.openGallery(SelectMimeType.ofImage())
.setSelectorUIStyle(PictureUtlis.getStyle())
.setImageEngine(GlideEngine.createGlideEngine())
.setCompressEngine(new ImageFileCompressEngine()) //设置压缩
.setSandboxFileEngine(new MeSandboxFileEngine()) //设置相册沙盒目录拷贝引擎
.setCameraInterceptListener(new MeOnCameraInterceptListener())
.setSelectionMode(SelectModeConfig.SINGLE)
.setMaxSelectNum(1)
.isEmptyResultReturn(true) //支持未选择返回
.setImageSpanCount(4)
.isPageStrategy(true) // 是否开启分页模式
.isDisplayCamera(true) //是否显示相机入口
.isPreviewFullScreenMode(true)//预览点击全屏效果
.isCameraRotateImage(true) //拍照是否纠正旋转图片
.isEmptyResultReturn(true)//支持未选择返回
.isWithSelectVideoImage(false)//是否支持视频图片同选
.isSelectZoomAnim(true)// 选择缩略图缩放效果
.isCameraAroundState(false)// 是否开启前置摄像头;系统相机 只支持部分机型
.isCameraRotateImage(true) //拍照是否纠正旋转图片
.isGif(false)// 是否显示gif文件
.isWebp(true)// 是否显示webp文件
.isBmp(true)//是否显示bmp文件
.isMaxSelectEnabledMask(true)// 达到最大选择数是否开启禁选蒙层
.isAutomaticTitleRecyclerTop(true) //点击相册标题是否快速回到第一项
.isFastSlidingSelect(true) //快速滑动选择
.isDirectReturnSingle(true)//PictureConfig.SINGLE模式下是否直接返回
.setQuerySortOrder(MediaStore.MediaColumns.DATE_MODIFIED + " DESC")//由远-近 MediaStore.MediaColumns.DATE_MODIFIED + " ASC"
.isPreviewImage(true)//是否预览图片
.setCropEngine(new ImageCropEngine(1F,1F,true))
.setFilterMinFileSize(1) //过滤最小文件
.forResult(2);
}
private void openPhotoAlbum() {
PictureSelector.create(this)
.openGallery(SelectMimeType.ofImage())
.setSelectorUIStyle(PictureUtlis.getStyle())
.setImageEngine(GlideEngine.createGlideEngine())
.setCompressEngine(new ImageFileCompressEngine()) //设置压缩
.setSandboxFileEngine(new MeSandboxFileEngine()) //设置相册沙盒目录拷贝引擎
.setCameraInterceptListener(new MeOnCameraInterceptListener())
.setSelectionMode(SelectModeConfig.SINGLE)
.setMaxSelectNum(1)
.isEmptyResultReturn(true) //支持未选择返回
.setImageSpanCount(4)
.isPageStrategy(true) // 是否开启分页模式
.isDisplayCamera(true) //是否显示相机入口
.isPreviewFullScreenMode(true)//预览点击全屏效果
.isCameraRotateImage(true) //拍照是否纠正旋转图片
.isEmptyResultReturn(true)//支持未选择返回
.isWithSelectVideoImage(false)//是否支持视频图片同选
.isSelectZoomAnim(true)// 选择缩略图缩放效果
.isCameraAroundState(false)// 是否开启前置摄像头;系统相机 只支持部分机型
.isCameraRotateImage(true) //拍照是否纠正旋转图片
.isGif(false)// 是否显示gif文件
.isWebp(true)// 是否显示webp文件
.isBmp(true)//是否显示bmp文件
.isMaxSelectEnabledMask(true)// 达到最大选择数是否开启禁选蒙层
.isAutomaticTitleRecyclerTop(true) //点击相册标题是否快速回到第一项
.isFastSlidingSelect(true) //快速滑动选择
.isDirectReturnSingle(true)//PictureConfig.SINGLE模式下是否直接返回
.setQuerySortOrder(MediaStore.MediaColumns.DATE_MODIFIED + " DESC")//由远-近 MediaStore.MediaColumns.DATE_MODIFIED + " ASC"
.isPreviewImage(true)//是否预览图片
.setFilterMinFileSize(1) //过滤最小文件
.setCropEngine(new ImageCropEngine(1F,1F,true))
.forResult(1);
}
@AfterPermissionGranted(RC_CAMERA_PERM)
public void cameraTask() {
String[] callPhone =
new String[]{READ_MEDIA_IMAGES, CAMERA};
XXPermissions.with(this)
// 申请单个权限
.permission(callPhone)
.request(new OnPermissionCallback() {
@Override
public void onGranted(List<String> permissions, boolean all) {
if (all) {
showWindow();
}else{
ToastUtil.showToast(getApplicationContext(), "获取部分权限成功,但部分权限未正常授予", Toast.LENGTH_SHORT);
}
}
@Override
public void onDenied(List<String> permissions, boolean never) {
if (never) {
// 如果是被永久拒绝就跳转到应用权限系统设置页面
XXPermissions.startPermissionActivity(UserInfoActivity.this, permissions);
} else {
ToastUtil.showToast(getApplicationContext(), "获取权限失败", Toast.LENGTH_SHORT);
}
}
});
if (hasCameraPermission()) {
showWindow();
} else {
// Ask for one permission
EasyPermissions.requestPermissions(
this,
"充电桩需要获取您相关权限,是否允许?",
RC_CAMERA_PERM,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE);
}
}
private boolean hasCameraPermission() {
return EasyPermissions.hasPermissions(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
);
}
/**
* 调用系统相册
*
* @param view
*/
public void getPhoto(View view) {
PhotoUtils.openPic(UserInfoActivity.this, 1);
}
public void startPhotoZoom(Uri uri) {
/*
* * 至于下面这个Intent的ACTION是怎么知道的,大家可以看下自己路径下的如下网页 *
* yourself_sdk_path/docs/reference/android/content/Intent.html *
* 直接在里面Ctrl+F搜:CROP ,之前小马没仔细看过,其实安卓系统早已经有自带图片裁剪功能, * 是直接调本地库的,不懂C C++
* 这个不做详细了解去了,有轮子就用轮子,不再研究轮子是怎么 * 制做的了...吼吼
*/
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(intent, 3);
}
/**
* 保存裁剪之后的图片数据
**/
private void setPicToView(Intent picdata) {
com.blankj.utilcode.util.LogUtils.e("!@#");
Bundle extras = picdata.getExtras();
if (extras != null) {
photo = extras.getParcelable("data");
if (photo != null) {
// m_imageUser.setImageBitmap((Bitmap) photo);
// 给image设置图片
// toRoundBitmap(photo);
iconPic.setImageBitmap(photo);
// saveBitmap();
}
}
}
private String bitmapToBase64(Bitmap bitmap) {
String result = null;
ByteArrayOutputStream baos = null;
try {
if (bitmap != null) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
baos.flush();
baos.close();
byte[] bitmapBytes = baos.toByteArray();
result = android.util.Base64.encodeToString(bitmapBytes, android.util.Base64.DEFAULT);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.flush();
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
@Override
public void onActivityResult(final int requestCode, int resultCode,
final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int output_X = 150, output_Y = 150;
// Log.e("data", data.toString() + " resultCode ==" + resultCode);
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case 1:
case 2:
activityResult(data);
break;
default:
break;
}
;
}
private void activityResult(Intent data) {
List<LocalMedia> medias = PictureSelector.obtainSelectorList(data);
if (medias != null && medias.size() > 0) {
String path = Util.getCompressAbsolutePath(medias.get(0));
photo = imageZoom(BitmapFactory.decodeFile(path));
if (photo != null) {
iconPic.setImageBitmap(photo);
}
}
}
private Bitmap imageZoom(Bitmap bm) {
// 图片允许最大空间 单位:KB
double maxSize = 40.00;
// 将bitmap放至数组中,意在bitmap的大小(与实际读取的原文件要大)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
// 将字节换成KB
double mid = b.length / 1024;
// 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
if (mid > maxSize) {
// 获取bitmap大小 是允许最大大小的多少倍
double i = mid / maxSize;
// 开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍
// (1.保持刻度和高度和原bitmap比率一致,压缩后也达到了最大大小占用空间的大小)
bm = zoomImage(bm, bm.getWidth() / Math.sqrt(i), bm.getHeight()
/ Math.sqrt(i));
}
return bm;
}
public Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight) {
// 获取这个图片的宽和高
float width = bgimage.getWidth();
float height = bgimage.getHeight();
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 计算宽高缩放率
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 缩放图片动作
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
(int) height, matrix, true);
return bitmap;
}
private Bitmap comp(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
if (baos.toByteArray().length / 1024 > 1024) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
baos.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%,把压缩后的数据存放到baos中
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
//现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
float hh = 800f;//这里设置高度为800f
float ww = 480f;//这里设置宽度为480f
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;//设置缩放比例
//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
isBm = new ByteArrayInputStream(baos.toByteArray());
bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
}
/**
* 转换图片成圆形
*
* @param bitmap 传入Bitmap对象
* @return
*/
public Bitmap toRoundBitmap(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float roundPx;
float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
if (width <= height) {
roundPx = width / 2;
top = 0;
bottom = width;
left = 0;
right = width;
height = width;
dst_left = 0;
dst_top = 0;
dst_right = width;
dst_bottom = width;
} else {
roundPx = height / 2;
float clip = (width - height) / 2;
left = clip;
right = width - clip;
top = 0;
bottom = height;
width = height;
dst_left = 0;
dst_top = 0;
dst_right = height;
dst_bottom = height;
}
output = Bitmap.createBitmap(width,
height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
final RectF rectF = new RectF(dst);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, src, dst, paint);
return output;
}
Handler handle = new Handler(Looper.getMainLooper()) {
public void handleMessage(Message msg) {
switch (msg.what) {
case StatusConstants.REQUEST_WHAT_SUCCESS:
LogUtils.getLogger().e(msg.obj.toString());
break;
case 1:
try {
JSONArray jsonary = new JSONArray(msg.obj.toString());
for (int i = 0; i < jsonary.length(); i++) {
JSONObject js = new JSONObject(jsonary.get(i).toString());
Province prov = new Province();
prov.setId(js.getInt("id"));
prov.setName(js.getString("name"));
if (prov.getName().equals(name0)) {
default_brand = i;
}
JSONArray jsonary1 = js.getJSONArray("cars");
List<Cars> cities = new ArrayList<Cars>();
for (int j = 0; j < jsonary1.length(); j++) {
JSONObject js2 = new JSONObject(jsonary1.get(j).toString());
Cars car = new Cars(js2.getString("name"), js2.getString("id"), js2.getString("brand_id"));
if (car.getName().equals(name1)) {
default_type = j;
}
cities.add(car);
}
prov.setCities(cities);
pr.remove(prov);
pr.add(prov);
}
} catch (JSONException e) {
e.printStackTrace();
}
ArrayAdapter<Province> provinceAdapter = new ArrayAdapter<Province>(UserInfoActivity.this, R.layout.simple_spinner_item, pr);
spinnerProvince.setAdapter(provinceAdapter);
provinceAdapter.notifyDataSetChanged();
if (default_brand != -1) {
spinnerProvince.setSelection(default_brand + 1);
default_brand = -1;
}
new Handler().postDelayed(new Runnable() {
public void run() {
spinnerCity.setSelection(default_type);
}
}, 5000);
break;
case 2:
Log.e(TAG, "handleMessage: " + msg.obj.toString());
try {
JSONObject jsonObject = new JSONObject(msg.obj.toString());
String rtnCode = jsonObject.getString("rtnCode");
String rtnMsg = jsonObject.getString("rtnMsg");
if (rtnCode.equals("01")) {
dialog.cancel();
String picurl = JsonUtils.getKeyResult(msg.obj.toString(), "picurl");
MainApplication.userIcon = MainApplication.url + picurl;
ProfileManager.getInstance().setUsericon(getApplicationContext(), MainApplication.userIcon);
MainApplication.userNickname = et_nickName.getText().toString();
ProfileManager.getInstance().setNickname(getApplicationContext(), et_nickName.getText().toString());
Intent intent = new Intent();
intent.putExtra("nickname", et_nickName.getText().toString().trim());
intent.putExtra("userphoto", ss);
setResult(RESULT_SUCCESS, intent);
String plusScore = jsonObject.getString("plusScore");
if (!plusScore.equals("")) {
tv_point.setText(plusScore);
rl_point.setVisibility(View.VISIBLE);
rl_point.startAnimation(animation);
new Handler().postDelayed(new Runnable() {
public void run() {
rl_point.setVisibility(View.GONE);
}
}, 1000);
new Handler().postDelayed(new Runnable() {
public void run() {
UserInfoActivity.this.finish();
}
}, 1500);
} else {
ToastUtil.showToast(UserInfoActivity.this, "保存成功", Toast.LENGTH_SHORT);
UserInfoActivity.this.finish();
}
} else if (rtnCode.equals("03")) {
dialog.cancel();
Toast.makeText(UserInfoActivity.this, "请求超时", Toast.LENGTH_SHORT).show();
} else if (rtnCode.equals("02")) {
dialog.cancel();
Toast.makeText(UserInfoActivity.this, "该昵称已有用户使用,请重新填写", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
case 5:
Toast.makeText(UserInfoActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
break;
}
super.handleMessage(msg);
}
};
public void getFromServer() {
new Thread(new Runnable() {
@Override
public void run() {
show_Data();
}
}).start();
}
private void show_Data() {
//http://hw.gearedu.com:9080/rongyao/rest
//String url = mParentContext.getString(R.string.ip_url) + "/resource/book?userId=" + userid;
String url = MainApplication.url + "/zhannew/basic/web/index.php/brand/getlist";
Request request = new Request.Builder().url(url).build();
Response response = null;
try {
response = OkHttpUtil.execute(request);
if (response.code() == 200) {
String json = "";
try {
json = response.body().string();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Message msg = handle.obtainMessage();
msg.what = 1;
msg.obj = json;
handle.sendMessage(msg);
} else if (response.code() == 204) {
Message msg = handle.obtainMessage();
msg.what = 5;
handle.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100;
while (baos.toByteArray().length / 1024 > 100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
options -= 10;//每次都减少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
return bitmap;
}
@Override
protected void onResume() {
super.onResume();
MobclickAgent.onResume(this);
getCarOwnerCertificateList(false);
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPause(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
private void getCarOwnerCertificateList(Boolean showLoading) {
if (showLoading) {
loadDialog.show();
}
long tokenTime = System.currentTimeMillis() / 1000 - MainMapActivity.cha - 1;
String token = null;
try {
token = DES3.encode(String.valueOf(tokenTime));
token = URLEncoder.encode(token, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
String url = MainApplication.url + "/zhannew/basic/web/index.php/car/my?userid=" + MainApplication.userId + "&order=1" + "&token=" + token;
// Log.e(TAG, "getCarOwnerCertificateList: "+url );
OkHttpUtils.get().url(url).build().connTimeOut(6000).readTimeOut(6000).execute(new StringCallback() {
@Override
public void onError(Call call, Exception e) {
e.printStackTrace();
loadDialog.dismiss();
Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
go_title.setText("认证车主");
go_desc.setText("去认证车主(得充电优惠券)");
go_desc.setTextColor(Color.parseColor("#3AB948"));
go_cursor.setVisibility(View.VISIBLE);
}
@Override
public void onResponse(String response) {
loadDialog.dismiss();
String rtnCode = JsonUtils.getKeyResult(response, "rtnCode");
if ("01".equals(rtnCode)) {
String data = JsonUtils.getKeyResult(response, "data");
List<CarOwnerCertificateBean> list = new ArrayList<>();
try {
list = JsonUtils.parseToObjectList(data, CarOwnerCertificateBean.class);
} catch (com.alibaba.fastjson.JSONException e) {
}
CarSeriesEntity carSeriesEntity = null;
if (list.size() != 0) {
boolean isCertifiedOwner = true;//是否是已通过认证车主
boolean isVerified = true;//是否是已认证车主
boolean isCarIntendedModel = true;//是否是意向车型
Gson gson = new Gson();
for (CarOwnerCertificateBean bean : list) {
//获取已通过车主认证车型
if (bean.getStatus() == 1 && bean.getMain() == 1 && isCertifiedOwner) {
certificateStatus = 1;
carSeriesEntity = gson.fromJson(bean.getChexing(), CarSeriesEntity.class);
isCertifiedOwner = false;
}
//获取意向车型
if (bean.getStatus() == 2 && isCarIntendedModel) {
CarSeriesEntity entity = gson.fromJson(bean.getChexing(), CarSeriesEntity.class);
if (mCarModelEntity == null){
carModel.setText(entity.getSeriesName());
}
isCarIntendedModel = false;
}
//已完成车主认证功能
if (bean.getStatus() != 2 && isVerified) {
certificateStatus = bean.getStatus();
CarSeriesEntity entity = gson.fromJson(bean.getChexing(), CarSeriesEntity.class);
MainApplication.userCertifiedModel = (entity.getSeriesName());
isVerified = false;
}
}
}
if (certificateStatus == 0 || certificateStatus == -1) {
go_title.setText("认证车主");
go_desc.setText("审核中");
go_desc.setTextColor(Color.RED);
go_cursor.setVisibility(View.INVISIBLE);
} else if (certificateStatus == 1) {
go_title.setText("认证车主");
if (carSeriesEntity != null) {
go_desc.setText(carSeriesEntity.getSeriesName());
}
go_desc.setTextColor(Color.parseColor("#0E0E0E"));
go_cursor.setVisibility(View.INVISIBLE);
} else {
go_title.setText("认证车主");
go_desc.setText("去认证车主(得充电优惠券)");
go_desc.setTextColor(Color.parseColor("#3AB948"));
go_cursor.setVisibility(View.VISIBLE);
}
if (certificateStatus == -2 && showLoading) {
startActivity(new Intent(getApplication(), CarOwnerCertificateActivity.class));
}
} else {
String rtnMsg = JsonUtils.getKeyResult(response, "rtnMsg");
Toast.makeText(getApplicationContext(), rtnMsg, Toast.LENGTH_SHORT).show();
go_title.setText("认证车主");
go_desc.setText("去认证车主(得充电优惠券)");
go_desc.setTextColor(Color.parseColor("#3AB948"));
go_cursor.setVisibility(View.VISIBLE);
}
}
});
}
/**
* 意向车型Event
*/
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void onCarModelEvent(CarIntentModelEvent event) {
if (event != null) {
mCarModelEntity = event.getCarModelEntity();
carModel.setText(mCarModelEntity.getSeriesName());
EventBus.getDefault().removeStickyEvent(event);
}
}
private void requestCarIntentModel() {
String url = MainApplication.url + "/zhannew/basic/web/index.php/car/add";
long tokenTime = System.currentTimeMillis() / 1000 - MainMapActivity.cha - 1;
String token = null;
try {
token = DES3.encode(String.valueOf(tokenTime));
} catch (Exception e) {
e.printStackTrace();
}
Map<String, String> map = new HashMap<>();
map.put("engine_number", "yixiang");
map.put("plate_number", "意向");
map.put("cartype", "自用");
map.put("userid", MainApplication.userId);
map.put("token", token);
Gson gson = new Gson();
if (mCarModelEntity == null){
return;
}
String chexing = gson.toJson(mCarModelEntity);
map.put("chexing", chexing);
OkHttpUtils.post().params(map).url(url).build().execute(new StringCallback() {
@Override
public void onError(Call call, Exception e) {
loadDialog.dismiss();
}
@Override
public void onResponse(String response) {
loadDialog.dismiss();
String rtnCode = JsonUtils.getKeyResult(response, "rtnCode");
if ("01".equals(rtnCode)) {
ToastUtil.showToast(getApplicationContext(), "意向车型提交成功", Toast.LENGTH_SHORT);
MainApplication.userCarIntentMode = mCarModelEntity.getSeriesName();
carModel.setText(mCarModelEntity.getSeriesName());
ProfileManager.getInstance().setCarIntentModel(UserInfoActivity.this, mCarModelEntity.getSeriesName());
} else {
ToastUtil.showToast(getApplicationContext(), "意向车型提交失败,请重新提交", Toast.LENGTH_SHORT);
}
}
});
}
}
|