RAUtil.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. package com.usai.util;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.graphics.Bitmap;
  5. import android.graphics.BitmapFactory;
  6. import android.graphics.Matrix;
  7. import android.media.ExifInterface;
  8. import android.os.Build;
  9. import android.os.Bundle;
  10. import android.support.v4.app.ActivityCompat;
  11. import android.support.v4.content.PermissionChecker;
  12. import android.util.Log;
  13. import com.usai.redant.raimage.RedAntApplication;
  14. import org.json.JSONArray;
  15. import org.json.JSONException;
  16. import org.json.JSONObject;
  17. import java.io.File;
  18. import java.io.FileOutputStream;
  19. import java.io.IOException;
  20. import java.lang.reflect.Array;
  21. import java.util.ArrayList;
  22. import java.util.Collection;
  23. import java.util.Iterator;
  24. import java.util.Map;
  25. import java.util.Set;
  26. /**
  27. * Created by ray on 27/06/2017.
  28. */
  29. public class RAUtil {
  30. public static final int MY_PERMISSIONS_REQUEST= 1;
  31. // public static void checkPermissions1(Activity activity, String[] permissions)
  32. // {
  33. // Log.d("_RAIMAGE", "checkPermissions1:==================================== ");
  34. // for(String permission : permissions) {
  35. // boolean bshow=ActivityCompat.shouldShowRequestPermissionRationale(activity,permission);
  36. // boolean granted= ContextCompat.checkSelfPermission(activity,
  37. // Manifest.permission.ACCESS_FINE_LOCATION)
  38. // == PackageManager.PERMISSION_GRANTED;
  39. // boolean pc = PermissionChecker.checkSelfPermission(activity,permission)==PermissionChecker.PERMISSION_GRANTED;
  40. // Log.d("_RAIMAGE", "checkPermissions1: "+permission+" SHOW "+bshow+" granted "+granted +","+pc);
  41. // }
  42. // Log.d("_RAIMAGE", "checkPermissions1:==================================== ");
  43. // }
  44. public static boolean isNumeric(String str){
  45. for (int i = 0; i < str.length(); i++){
  46. System.out.println(str.charAt(i));
  47. if (!Character.isDigit(str.charAt(i))){
  48. return false;
  49. }
  50. }
  51. return true;
  52. }
  53. public static Boolean checkPermissions(Activity activity, String[] permissions)
  54. {
  55. if (Build.VERSION.SDK_INT >= 23)
  56. {
  57. return checkPermissions_23(activity,permissions);
  58. }
  59. else
  60. {
  61. return false;
  62. // return checkPermissions_23(activity,permissions);
  63. }
  64. }
  65. public static Boolean checkPermissions_23(String[] permissions)
  66. {
  67. Log.d("_RAIMAGE", "checkPermissions23:==================================== ");
  68. ArrayList<String> request_list = new ArrayList<String>();
  69. Context context = RedAntApplication.getInstance().getApplicationContext();
  70. for(String permission : permissions) {
  71. boolean pc = PermissionChecker.checkSelfPermission(context,permission)==PermissionChecker.PERMISSION_GRANTED;
  72. if(!pc)
  73. return false;
  74. }
  75. Log.d("_RAIMAGE", "checkPermissions23:==================================== ");
  76. return true;
  77. }
  78. public static Boolean checkPermissions_23(Activity activity, String[] permissions)
  79. {
  80. Log.d("_RAIMAGE", "checkPermissions23:==================================== ");
  81. ArrayList<String> request_list = new ArrayList<String>();
  82. for(String permission : permissions) {
  83. boolean bshow=ActivityCompat.shouldShowRequestPermissionRationale(activity,permission);
  84. // boolean granted= ContextCompat.checkSelfPermission(activity,
  85. // Manifest.permission.ACCESS_FINE_LOCATION)
  86. // == PackageManager.PERMISSION_GRANTED;
  87. boolean pc = PermissionChecker.checkSelfPermission(activity,permission)==PermissionChecker.PERMISSION_GRANTED;
  88. // Log.d("_RAIMAGE", "checkPermissions23: "+permission+" SHOW "+bshow+" granted "+granted +","+pc);
  89. if(!pc)
  90. request_list.add(permission);
  91. }
  92. Log.d("_RAIMAGE", "checkPermissions23:==================================== ");
  93. if(request_list.isEmpty())
  94. return false;
  95. ActivityCompat.requestPermissions(activity,
  96. request_list.toArray(new String[0]),
  97. MY_PERMISSIONS_REQUEST);
  98. return true;
  99. }
  100. public static Boolean checkPermissions_24(Activity activity, String[] permissions)
  101. {
  102. // ArrayList<String> request_list = new ArrayList<String>();
  103. // for(String permission : permissions) {
  104. //
  105. //
  106. //// boolean bshow=ActivityCompat.shouldShowRequestPermissionRationale(activity,permission);
  107. ////
  108. ////
  109. //// AppOpsManager appOpsManager = (AppOpsManager) activity.getSystemService(Context.APP_OPS_SERVICE);
  110. //// String opsName = AppOpsManager.permissionToOp(permission);
  111. //// if (opsName == null) {
  112. //// return true;
  113. //// }
  114. //// int opsMode = appOpsManager.checkOpNoThrow(opsName, Process.myUid(), activity.getPackageName());
  115. ////// return opsMode == AppOpsManager.MODE_ALLOWED;
  116. //
  117. //
  118. //// if (ContextCompat.checkSelfPermission(activity,
  119. //// Manifest.permission.ACCESS_FINE_LOCATION)
  120. //// != PackageManager.PERMISSION_GRANTED||opsMode != AppOpsManager.MODE_ALLOWED)
  121. //
  122. // request_list.add(permission);
  123. //
  124. // }
  125. // File logfile = new File(Environment.getExternalStorageDirectory()
  126. // .getPath() + "/redant/pop/" + "debug" + ".log");
  127. //
  128. // // int mode = Application.MODE_APPEND;
  129. // if (!logfile.exists())
  130. // {
  131. // // mode = Application.MODE_PRIVATE;
  132. // try
  133. // {
  134. // logfile.createNewFile();
  135. // }
  136. // catch (IOException e)
  137. // {
  138. // // TODO Auto-generated catch block
  139. // e.printStackTrace();
  140. //
  141. // }
  142. // }
  143. if(permissions.length==0)
  144. return true;
  145. ActivityCompat.requestPermissions(activity,
  146. permissions,
  147. MY_PERMISSIONS_REQUEST);
  148. return true;
  149. //
  150. // if (ContextCompat.checkSelfPermission(activity,
  151. // Manifest.permission.ACCESS_FINE_LOCATION)
  152. // != PackageManager.PERMISSION_GRANTED)
  153. // {
  154. //
  155. //
  156. //// if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
  157. //// permission))
  158. //// {
  159. //// return false;
  160. //// }
  161. //// else
  162. // {
  163. // ActivityCompat.requestPermissions(activity,
  164. // new String[]{permission},
  165. // MY_PERMISSIONS_REQUEST);
  166. // return true;
  167. // }
  168. // } else
  169. // {
  170. // return true;
  171. // }
  172. // if(true)
  173. // return true;
  174. // 调用Context的checkCallingOrSelfPermission来检查权限
  175. // Activity activity1 = (Activity) activity;
  176. // if(activity==null)
  177. // return false;
  178. // if (PackageManager.PERMISSION_GRANTED!= context.checkCallingOrSelfPermission(permission)) {
  179. //
  180. //// String[] tmp = permission.split("\\.");
  181. //// String permission_name = tmp[tmp.length - 1];
  182. //// permission_name = permission_name.replace("_"," ");
  183. ////
  184. ////
  185. //// new AlertDialog.Builder(context)
  186. //// .setTitle("Warning")
  187. //// .setMessage("RA Image need " + permission_name.toLowerCase() + " permission")
  188. //// .setPositiveButton("OK", null)
  189. //// .show();
  190. ////
  191. //// return false;
  192. //
  193. //
  194. // if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
  195. // permission)) {
  196. //
  197. // Log.d("_RAIMAGE", "checkPermission: shouldShowRequestPermissionRationale TRUE " + permission);
  198. // // Show an expanation to the user *asynchronously* -- don't block
  199. // // this thread waiting for the user's response! After the user
  200. // // sees the explanation, try again to request the permission.
  201. //
  202. // } else {
  203. //
  204. // // No explanation needed, we can request the permission.
  205. //
  206. //
  207. // Log.d("_RAIMAGE", "checkPermission: shouldShowRequestPermissionRationale false "+ permission);
  208. // ActivityCompat.requestPermissions(activity,
  209. // new String[]{permission},
  210. // 123);
  211. //
  212. // // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
  213. // // app-defined int constant. The callback method gets the
  214. // // result of the request.
  215. // }
  216. //
  217. // }
  218. // return true;
  219. }
  220. public static String lastPathComponent(String path){
  221. int start=path.lastIndexOf("/");
  222. int end=path.lastIndexOf(".");
  223. if(start!=-1 && end!=-1){
  224. return path.substring(start+1,end);
  225. }else{
  226. return null;
  227. }
  228. }
  229. public static File routeBitmap(File sourceFile,String file_name)
  230. {
  231. /**
  232. * 获取图片的旋转角度,有些系统把拍照的图片旋转了,有的没有旋转
  233. */
  234. int degree = RAUtil.readPictureDegree(sourceFile.getAbsolutePath());
  235. BitmapFactory.Options opts=new BitmapFactory.Options();//获取缩略图显示到屏幕上
  236. opts.inSampleSize=1;
  237. Bitmap cbitmap=BitmapFactory.decodeFile(sourceFile.getAbsolutePath(),opts);
  238. /**
  239. * 把图片旋转为正的方向
  240. */
  241. Bitmap newbitmap = RAUtil.rotaingImageView(degree, cbitmap);
  242. //sourceFile.get
  243. String routedPath = "";
  244. if(file_name==null) {
  245. String path = sourceFile.getPath();
  246. routedPath=path.replace(".jpg", "_routed.jpg");
  247. }
  248. else
  249. {
  250. String path = sourceFile.getParent();
  251. routedPath = path+"/"+file_name;
  252. }
  253. File routedFile = new File(routedPath);
  254. try {
  255. FileOutputStream outputStream = new FileOutputStream(routedFile);
  256. newbitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
  257. outputStream.flush();
  258. outputStream.close();
  259. sourceFile.delete();
  260. // scaleFile.renameTo(new File(path));
  261. return routedFile;
  262. } catch (IOException e) {
  263. e.printStackTrace();
  264. return null;
  265. }
  266. }
  267. /**
  268. * 读取图片属性:旋转的角度
  269. * @param path 图片绝对路径
  270. * @return degree旋转的角度
  271. */
  272. public static int readPictureDegree(String path) {
  273. int degree = 0;
  274. try {
  275. ExifInterface exifInterface = new ExifInterface(path);
  276. int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
  277. switch (orientation) {
  278. case ExifInterface.ORIENTATION_ROTATE_90:
  279. degree = 90;
  280. break;
  281. case ExifInterface.ORIENTATION_ROTATE_180:
  282. degree = 180;
  283. break;
  284. case ExifInterface.ORIENTATION_ROTATE_270:
  285. degree = 270;
  286. break;
  287. }
  288. } catch (IOException e) {
  289. e.printStackTrace();
  290. }
  291. return degree;
  292. }
  293. /*
  294. * 旋转图片
  295. * @param angle
  296. * @param bitmap
  297. * @return Bitmap
  298. */
  299. public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {
  300. //旋转图片 动作
  301. Matrix matrix = new Matrix();;
  302. matrix.postRotate(angle);
  303. System.out.println("angle2=" + angle);
  304. // 创建新的图片
  305. Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
  306. bitmap.getWidth(), bitmap.getHeight(), matrix, true);
  307. return resizedBitmap;
  308. }
  309. public static JSONObject Bundle2Json(Bundle bundle)
  310. {
  311. JSONObject json = new JSONObject();
  312. Set<String> keys = bundle.keySet();
  313. for (String key : keys) {
  314. try {
  315. Log.d("", "Bundle2Json: key:"+key+" val: "+wrap(bundle.get(key)));
  316. json.put(key, wrap(bundle.get(key))); //see edit below
  317. // json.put(key, JSONObject.wrap(bundle.get(key)));
  318. } catch(JSONException e) {
  319. //Handle exception here
  320. }
  321. }
  322. return json;
  323. }
  324. private static Object wrap(Object o) {
  325. if (o == null) {
  326. return JSONObject.NULL;
  327. }
  328. if (o instanceof JSONArray || o instanceof JSONObject) {
  329. return o;
  330. }
  331. if (o.equals(JSONObject.NULL)) {
  332. return o;
  333. }
  334. try {
  335. if (o instanceof Bundle)
  336. {
  337. return Bundle2Json((Bundle) o);
  338. }
  339. if (o instanceof Collection) {
  340. return new JSONArray((Collection) o);
  341. } else if (o.getClass().isArray()) {
  342. return toJSONArray(o);
  343. }
  344. if (o instanceof Map) {
  345. return new JSONObject((Map) o);
  346. }
  347. if (o instanceof Boolean ||
  348. o instanceof Byte ||
  349. o instanceof Character ||
  350. o instanceof Double ||
  351. o instanceof Float ||
  352. o instanceof Integer ||
  353. o instanceof Long ||
  354. o instanceof Short ||
  355. o instanceof String) {
  356. return o;
  357. }
  358. if (o.getClass().getPackage().getName().startsWith("java.")) {
  359. return o.toString();
  360. }
  361. } catch (Exception ignored) {
  362. }
  363. return null;
  364. }
  365. private static JSONArray toJSONArray(Object array) throws JSONException {
  366. JSONArray result = new JSONArray();
  367. if (!array.getClass().isArray()) {
  368. throw new JSONException("Not a primitive array: " + array.getClass());
  369. }
  370. final int length = Array.getLength(array);
  371. for (int i = 0; i < length; ++i) {
  372. result.put(wrap(Array.get(array, i)));
  373. }
  374. return result;
  375. }
  376. public static Bundle Json2Bundle(JSONObject s) {
  377. Bundle bundle = new Bundle();
  378. for (Iterator<String> it = s.keys(); it.hasNext(); ) {
  379. String key = it.next();
  380. try {
  381. Object o = s.get(key);
  382. if (o == null) {
  383. continue;
  384. }
  385. else if ( o instanceof JSONObject) {
  386. bundle.putBundle(key,Json2Bundle((JSONObject) o));
  387. }
  388. else if(o instanceof JSONArray )
  389. {
  390. throw new JSONException("Json2Bundle does not support Json array: " + o.getClass());// bundle.putarr
  391. }
  392. else if (o.equals(JSONObject.NULL)) {
  393. continue;
  394. }
  395. else if (o instanceof Boolean)
  396. {
  397. bundle.putBoolean(key,((Boolean) o).booleanValue());
  398. }
  399. else if(o instanceof Byte)
  400. {
  401. bundle.putByte(key, ((Byte) o).byteValue());
  402. }
  403. else if(o instanceof Character)
  404. {
  405. bundle.putChar(key, ((Character) o).charValue());
  406. }
  407. else if(o instanceof Double)
  408. {
  409. bundle.putDouble(key, ((Double) o).doubleValue());
  410. }
  411. else if(o instanceof Float)
  412. {
  413. bundle.putFloat(key, ((Float) o).floatValue());
  414. }
  415. else if(o instanceof Integer)
  416. {
  417. bundle.putInt(key, ((Integer) o).intValue());
  418. }
  419. else if(o instanceof Long)
  420. {
  421. bundle.putLong(key, ((Long) o).longValue());
  422. }
  423. else if(o instanceof Short)
  424. {
  425. bundle.putShort(key, ((Short) o).shortValue());
  426. }
  427. else if(o instanceof String)
  428. {
  429. bundle.putString(key, o.toString());
  430. }
  431. // ArrayList<Parcelable> a = new ArrayList<>();
  432. // a.add("");
  433. // a.add(1);
  434. // bundle.putParcelableArrayList("arr", a);
  435. } catch (JSONException e) {
  436. e.printStackTrace();
  437. }
  438. }
  439. return bundle;
  440. }
  441. public static Bundle Json2Bundle1(JSONObject s) {
  442. Bundle bundle = new Bundle();
  443. for (Iterator<String> it = s.keys(); it.hasNext(); ) {
  444. String key = it.next();
  445. JSONArray arr = s.optJSONArray(key);
  446. Double num = s.optDouble(key);
  447. // Integer i = s.optInt(key);
  448. String str = s.optString(key);
  449. JSONObject obj = s.optJSONObject(key);
  450. if (arr != null && arr.length() <= 0)
  451. {
  452. bundle.putStringArray(key, new String[]{});
  453. }
  454. else if (arr != null && !Double.isNaN(arr.optDouble(0))) {
  455. double[] newarr = new double[arr.length()];
  456. for (int i=0; i<arr.length(); i++)
  457. newarr[i] = arr.optDouble(i);
  458. bundle.putDoubleArray(key, newarr);
  459. }
  460. else if (arr != null && arr.optString(0) != null) {
  461. String[] newarr = new String[arr.length()];
  462. for (int i=0; i<arr.length(); i++)
  463. newarr[i] = arr.optString(i);
  464. bundle.putStringArray(key, newarr);
  465. }
  466. else if (obj != null)
  467. {
  468. Bundle b=Json2Bundle(obj);
  469. bundle.putBundle(key, b);
  470. }
  471. else if (!num.isNaN())
  472. bundle.putDouble(key, num);
  473. else if (str != null)
  474. bundle.putString(key, str);
  475. else
  476. System.err.println("unable to transform json to bundle " + key);
  477. }
  478. return bundle;
  479. }
  480. // public static Bundle Json2Bundle(JSONObject jsonObject) throws JSONException {
  481. // Bundle bundle = new Bundle();
  482. // Iterator iter = jsonObject.keys();
  483. // while(iter.hasNext()){
  484. // String key = (String)iter.next();
  485. // String value = jsonObject.getString(key);
  486. // bundle.putString(key,value);
  487. // }
  488. // return bundle;
  489. // }
  490. }