|
package com.electric.chargingpile.activity;
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.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.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import androidx.core.content.FileProvider;
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.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.Cars;
import com.electric.chargingpile.data.Province;
import com.electric.chargingpile.manager.ProfileManager;
import com.electric.chargingpile.util.BarColorUtil;
import com.electric.chargingpile.util.DES3;
import com.electric.chargingpile.util.JsonUtils;
import com.electric.chargingpile.util.LoadingDialog;
import com.electric.chargingpile.util.LogUtils;
import com.electric.chargingpile.util.OkHttpUtil;
import com.electric.chargingpile.util.PhotoUtils;
import com.electric.chargingpile.util.StatusConstants;
import com.electric.chargingpile.util.ToastUtil;
import com.electric.chargingpile.util.UploadUtil;
import com.electric.chargingpile.view.CustomProgressDialog;
import com.electric.chargingpile.view.RoundImageView;
import com.electric.chargingpile.view.xrichtext.SDCardUtil;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
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 me.iwf.photopicker.PhotoPicker;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
public class UserInfoActivity extends Activity implements View.OnClickListener, EasyPermissions.PermissionCallbacks {
private static final String TAG = "UserInfoActivity";
private ImageView back;
private EditText et_nickName;
private EditText et_realName;
private TextView et_che;
private ToggleButton btn_sex, btn_car;
private RelativeLayout rl_icon, rl_select_car, rl_isBuy;
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 String nocar = "";
private String havecar = "";
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;
public static final int REQUSET = 11;
String select_pinpai = "", select_chexing = "";
private TextView tv_point, tv_buy;
private RelativeLayout rl_point;
private android.view.animation.Animation animation;
private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
private Uri imageUri;
private Uri cropImageUri;
private static final int RC_CAMERA_PERM = 123;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BarColorUtil.initStatusBarColor(UserInfoActivity.this);
setContentView(R.layout.activity_user_info);
dialog = new LoadingDialog(this);
dialog.setCanceledOnTouchOutside(false);
mContext = this;
initView();
// getFromServer();
spinner();
getFromServer();
}
public void onEventMainThread(Province b) {
Log.e("ffff", b.getName() + " " + b.getCities().get(b.getId()).getName());
// Toast.makeText(this, b.getName()+ " " + b.getCities().get(b.getId()).getName(), Toast.LENGTH_SHORT).show();
et_che.setText(b.getName() + " - " + b.getCities().get(b.getId()).getName());
car_brand = b.getName();
car_type = b.getCities().get(b.getId()).getName();
}
private void initView() {
tv_buy = (TextView) findViewById(R.id.tv_buy);
rl_point = (RelativeLayout) findViewById(R.id.rl_point);
rl_isBuy = (RelativeLayout) findViewById(R.id.rl_isBuy);
rl_isBuy.setOnClickListener(this);
tv_point = (TextView) findViewById(R.id.tv_point);
animation = AnimationUtils.loadAnimation(UserInfoActivity.this, R.anim.nn);
rl_select_car = (RelativeLayout) findViewById(R.id.rl_select_car);
rl_select_car.setOnClickListener(this);
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);
et_che = (TextView) findViewById(R.id.et_che);
Log.e(TAG, "initView: " + MainApplication.userCar);
if (MainApplication.userCar.equals("")) {
tv_buy.setText("");
rl_select_car.setVisibility(View.GONE);
} else if ("待购".equals(MainApplication.userCar)) {
tv_buy.setText("未购买");
rl_select_car.setVisibility(View.GONE);
et_che.setText("");
} else {
String car = MainApplication.userCar.replace("$$", " ");
tv_buy.setText("已购买");
rl_select_car.setVisibility(View.VISIBLE);
et_che.setText(car);
String[] strarray = car.split(" ");
if (strarray.length > 1) {
car_brand = strarray[0];
car_type = strarray[1];
}
}
onclick = (TextView) findViewById(R.id.onclick);
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);
// rl_brand = (RelativeLayout) findViewById(R.id.rl_1);
// rl_brand.setOnClickListener(this);
// rl_type = (RelativeLayout) findViewById(R.id.rl_2);
// rl_type.setOnClickListener(this);
// long appTime1 = System.currentTimeMillis()/1000;
//// Log.d("appTime(long)---", appTime1+"");
// String apptime = String.valueOf(appTime1);
// int updateapptime = Integer.valueOf(apptime);
//
// if(MainFragment.cha>0){
// cha = updateapptime - (MainFragment.cha);
// }else if (MainFragment.cha<0){
// cha = updateapptime+(MainFragment.cha);
// }else {
// cha = updateapptime;
// }
// chatime = String.valueOf(cha);
// Log.i("updatetime----",updateapptime+"");
// Log.i("cha",chatime);
}
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_face2_0);
photo = ((BitmapDrawable) iconPic.getDrawable()).getBitmap();
}
// if (ImageTools.findPhotoFromSDCard(MainApplication.storePath,"user_icon")){
// Bitmap bmp = BitmapFactory.decodeFile(MainApplication.storePath+"/user_icon.png");
// photo = bmp;
// iconPic.setImageBitmap(bmp);
// }else {
// Log.e(TAG, "setIcon: "+MainApplication.userIcon );
// new Task().execute(MainApplication.userIcon);
// }
}
private void spinner() {
List<Cars> cars = new ArrayList<Cars>();
Cars car = new Cars("E140ev", "1", "1");
// Cars car1=new Cars("E150ev","1","2");
// Cars car2=new Cars("EV160","1","3");
// Cars car3=new Cars("EV200","1","4");
cars.add(car);
// cars.add(car1);
// cars.add(car2);
// cars.add(car3);
//
List<Cars> cars2 = new ArrayList<Cars>();
Cars car0 = new Cars("车型", "1", "1");
// Cars car11=new Cars("2222","1","2");
// Cars car22=new Cars("33333","1","3");
// Cars car33=new Cars("4444","1","4");
cars2.add(car0);
// cars2.add(car11);
// cars2.add(car22);
// cars2.add(car33);
// // spinner方面的东西
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("品牌");
// Province p2=new Province("比亚迪1", 2, cars2);
// Province p3=new Province("比亚迪2", 2, cars);
// Province p4=new Province("比亚迪3", 2, cars);
// Province p5=new Province("比亚迪4", 2, cars);
// Province p6=new Province("比亚迪5", 2, cars);
// Province p7=new Province("比亚迪6", 2, cars);
// Province p8=new Province("比亚迪7", 2, cars);
// Province p9=new Province("比亚迪8", 2, cars);
pr.add(p);
// pr.add(p2);
// pr.add(p3);
// pr.add(p4);
// pr.add(p5);
// pr.add(p6);
// pr.add(p7);
// pr.add(p8);
// pr.add(p9);
// pr.add(p2);
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());
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
}
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);
// btnP.setText(d.getName());
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) {
// currentCity = currentProvince.getCities().get(position);
car_type = (String) spinnerCity.getSelectedItem();
Log.e("car_type", car_type);
}
}
public void onProvinChange(int position) {
// currentProvince = parse.getProvinces().get(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;
}
// Log.e("default_type",default_type+"");
// if (default_type==-1){
// spinnerCity.setSelection(0);
// default_type=-1;
// }else{
// spinnerCity.setSelection(default_type);
// }
// if (currentProvince.getCities().size() > 0) {
// cityAdapter.notifyDataSetChanged();
// spinnerCity.setSelection(0);
// }
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.rl_select_car:
MobclickAgent.onEvent(getApplicationContext(), "0802", new HashMap<String, String>().put("type", "车型"));
// startActivityForResult(new Intent(UserInfoActivity.this,
// ChePaiActivity.class), 55);
startActivityForResult(new Intent(UserInfoActivity.this, SelectCarActivity.class), REQUSET);
break;
case R.id.rl_isBuy:
MobclickAgent.onEvent(getApplicationContext(), "0802", new HashMap<String, String>().put("type", "是否购车"));
LayoutInflater inflater1 = (LayoutInflater) getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
View popupWindowView = inflater1.inflate(R.layout.layout_isbuy, null);
final PopupWindow popupWindow1 = new PopupWindow(popupWindowView,
ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT,
true);
popupWindow1.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_yinying531));
popupWindow1.setOutsideTouchable(true);
popupWindowView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_MENU) && (popupWindow1.isShowing())) {
popupWindow1.dismiss();
return true;
}
return false;
}
});
popupWindowView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (popupWindow1.isShowing()) {
popupWindow1.dismiss();
}
return false;
}
});
// 设置PopupWindow的弹出和消失效果
popupWindow1.setAnimationStyle(R.style.popupAnimation);
Button cancleButton = (Button) popupWindowView
.findViewById(R.id.cancleButton);
cancleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
popupWindow1.dismiss();
}
});
Button btn_one = (Button) popupWindowView.findViewById(R.id.tvTwo);
btn_one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tv_buy.setText("已购买");
rl_select_car.setVisibility(View.VISIBLE);
// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
// Environment.getExternalStorageDirectory(), "androidapp.jpg")));
// ((Activity) mContext).startActivityForResult(intent, 2);
popupWindow1.dismiss();
}
});
Button btn_two = (Button) popupWindowView.findViewById(R.id.tvThree);
btn_two.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tv_buy.setText("未购买");
rl_select_car.setVisibility(View.GONE);
// Intent intent = new Intent(Intent.ACTION_PICK, null);
// intent.setDataAndType(
// MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
// "image/*");
// startActivityForResult(intent, 1);
popupWindow1.dismiss();
}
});
popupWindow1.showAtLocation(cancleButton, Gravity.CENTER, 0, 0);
break;
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();
dialog.show();
}
break;
}
}
private boolean checkText() {
String nickName = et_nickName.getText().toString().trim();
String isBuy = tv_buy.getText().toString().trim();
String carType = et_che.getText().toString().trim();
if (TextUtils.isEmpty(nickName)) {
Toast.makeText(this, "请输入您的昵称", Toast.LENGTH_SHORT).show();
return false;
}
if (TextUtils.isEmpty(isBuy)) {
Toast.makeText(this, "请选择您是否购买了新能源汽车", Toast.LENGTH_SHORT).show();
return false;
}
if (isBuy.equals("已购买")) {
if (TextUtils.isEmpty(carType)) {
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) {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
"image/*");
startActivityForResult(intent, 1);
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);
if (tv_buy.getText().toString().equals("未购买")) {
havecar = "待购";
} else {
if (car_brand != null && null != car_type) {
havecar = car_brand + "$$" + car_type;
}
}
nocar = "";
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);
par.put("chexing", havecar);
par.put("yichexing", nocar);
Log.e("chexing", havecar);
Log.e("yichexing", nocar);
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) {
if (SDCardUtil.hasSdcard()) {
imageUri = Uri.fromFile(fileUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
//通过FileProvider创建一个content类型的Uri
imageUri = FileProvider.getUriForFile(UserInfoActivity.this, "com.electric.chargingpile.provider", fileUri);
PhotoUtils.takePicture(UserInfoActivity.this, imageUri, 2);
} else {
Toast.makeText(UserInfoActivity.this, "设备没有SD卡!", Toast.LENGTH_SHORT).show();
Log.e("asd", "设备没有SD卡");
}
}
@AfterPermissionGranted(RC_CAMERA_PERM)
public void cameraTask() {
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 REQUSET:
select_pinpai = data.getStringExtra("pinpai");
select_chexing = data.getStringExtra("chexing");
et_che.setText(select_pinpai + " " + select_chexing);
car_brand = select_pinpai;
car_type = select_chexing;
break;
case PhotoPicker.REQUEST_CODE:
if (data != null) {
data.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
// for (String imagePath : photos) {
//
// }
// }
// startPhotoZoom(data.getData());
//可以同时插入多张图片
for (String imagePath : photos) {
File file = new File(imagePath);
com.blankj.utilcode.util.LogUtils.e(file.length());
Uri fileUri = FileProvider.getUriForFile(getApplicationContext(),
getApplicationContext().getPackageName() + ".provider", file);
//设置权限
com.blankj.utilcode.util.LogUtils.e(fileUri);
startPhotoZoom(fileUri);
// Log.e(TAG, "call: imagePath "+imagePath );
// photo = BitmapFactory.decodeFile(imagePath);//压缩图片
// if (ImageUtils.readPictureDegree(imagePath) != 0 ){
// photo = imageZoom(ImageUtils.toturn(photo));
// }else {
// photo = imageZoom(photo);
// }
// if (photo != null) {
// iconPic.setImageBitmap(photo);
// }
}
} else {
ToastUtil.showToast(getApplicationContext(), "data为null", Toast.LENGTH_SHORT);
}
break;
case 1:
if (SDCardUtil.hasSdcard()) {
cropImageUri = Uri.fromFile(fileCropUri);
Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
newUri = FileProvider.getUriForFile(this, "com.electric.chargingpile.provider", new File(newUri.getPath()));
PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, output_X, output_Y, 3);
} else {
Toast.makeText(UserInfoActivity.this, "设备没有SD卡!", Toast.LENGTH_SHORT).show();
}
break;
// 如果是调用相机拍照时
case 2:
cropImageUri = Uri.fromFile(fileCropUri);
PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, output_X, output_Y, 3);
break;
// 取得裁剪后的图片
case 3:
photo = imageZoom(PhotoUtils.getBitmapFromUri(cropImageUri, this));
if (photo != null) {
iconPic.setImageBitmap(photo);
}
break;
default:
break;
}
;
}
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);
// iv_2.setImageBitmap(bitmap);
// tv_2.setText(bitmap.getRowBytes() * bitmap.getHeight() + "");
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;
}
public void saveBitmap(Bitmap mBitmap) {
String dir_path = Environment.getExternalStorageDirectory() + File.separator + "d1ev/";
File directory = new File(dir_path);
File f = new File(dir_path, "usericon");
try {
if (!directory.exists()) {
directory.mkdir();//没有目录先创建目录
}
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
}
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (Exception e) {
e.printStackTrace();
}
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/*
*bitmap转base64
*/
// public static Bitmap base64ToBitmap(String base64String){
// byte[] bytes = Base64.decode(base64String);
// Bitmap bitmap= BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
// return bitmap;
// }
Handler handle = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case StatusConstants.REQUEST_WHAT_SUCCESS:
LogUtils.getLogger().e(msg.obj.toString());
// Toast.makeText(UserInfoActivity.this, msg.obj.toString(), 1).show();
break;
case 1:
//
// Gson g = new Gson();
// pr.clear();
// pr = g.fromJson(msg.obj.toString(), new TypeToken<List<Province>>() {
// }.getType());
// String s=msg.obj.toString();
// JSONObject
// Province p= new Province(s.get, code, cities)
// pr.add(arg0)
// spinner();
// if (!chexing.equals("") && yichexing.equals("")){
// String[] strarray=chexing.split("\\$\\$");
//
// if(strarray.length>1){
// name0=strarray[0];//江淮
// name1=strarray[1];//iEV3
// }
// Log.e("name0+name1",name0+name1);
// et_che.setText(name0 + " - " + name1);
// Log.e(TAG, "handleMessage: "+ et_che.getText().toString());
// if (et_che.getText().toString().equals(" - ")){
// tv_buy.setText("未购买");
// rl_select_car.setVisibility(View.GONE);
// }else {
// tv_buy.setText("已购买");
// rl_select_car.setVisibility(View.VISIBLE);
// }
// car_brand = name0;
// car_type = name1;
// }else if(chexing.equals("") && !yichexing.equals("")){
// String[] strarray=yichexing.split("\\$\\$");
//
// if(strarray.length>1){
// name0=strarray[0];//江淮
// name1=strarray[1];//iEV3
// }
// Log.e("name0+name1",name0+name1);
// et_che.setText(name0 + " - " + name1);
// car_brand = name0;
// car_type = name1;
// }
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);
// spinnerProvince.setSelection(de);
// spinnerCity
}
} catch (JSONException e) {
e.printStackTrace();
}
// pr =(List<Province>) JsonUtils.parseToObjectBean(msg.obj.toString(), Province.class);
// Log.e("pe", pr.size()+"");
// Log.e("pe", pr.get(0).getCities().size()+"");
// Log.e("pe", pr.get(1).getCities().size()+"");
// Log.e("pe", pr.get(2).getCities().size()+"");
// Log.e("pe", pr.get(3).getCities().size()+"");
// Log.e("pe", pr.size()+"");
// Log.e("pe", pr.size()+"");
//
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();
// SharedPreferences mySharedPreferences= getSharedPreferences("userInfo",
// Activity.MODE_PRIVATE);
// SharedPreferences.Editor editor = mySharedPreferences.edit();
// editor.putString("nickname", et_nickName.getText().toString());
// editor.putString("username", et_realName.getText().toString());
// editor.putString("sex", sex);
// editor.putString("chexing", havecar);
// editor.putString("yichexing", nocar);
//
//// String data = JsonUtils.getKeyResult(msg.obj.toString(),"data");
//// String userid = JsonUtils.getKeyResult(data,"userid");
//// String username = JsonUtils.getKeyResult(data,"username");
//// String userpic = JsonUtils.getKeyResult(data,"userpic");
//// String nickname = JsonUtils.getKeyResult(data,"nickname");
//// LogUtils.getLogger().e(userid+"---"+username+"---"+userpic+"---"+nickname);
//// Log.e(TAG, "handleMessage: "+userid+"---"+username+"---"+userpic+"---"+nickname );
//
// editor.commit();
String picurl = JsonUtils.getKeyResult(msg.obj.toString(), "picurl");
MainApplication.userIcon = MainApplication.url + picurl;
ProfileManager.getInstance().setUsericon(getApplicationContext(), MainApplication.userIcon);
MainApplication.userCar = havecar;
ProfileManager.getInstance().setUsercar(getApplicationContext(), havecar);
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);
// MainApplication.userIcon="V";
// ProfileManager.getInstance().setUsericon(UserInfoActivity.this, "V");
// ImageTools.saveImageToGallery(getApplicationContext(),photo,"user_icon");
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);
// if (photo != null) {
// photo.recycle();
// photo = null;
//// bitmap.recycle();
//
// }
new Handler().postDelayed(new Runnable() {
public void run() {
UserInfoActivity.this.finish();
}
}, 1500);
} else {
ToastUtil.showToast(UserInfoActivity.this, "保存成功", Toast.LENGTH_SHORT);
// if (photo != null) {
// photo.recycle();
// photo = null;
//
// }
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();
}
// Toast.makeText(UserInfoActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
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);
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPause(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
|