WebViewActivity.java 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. package com.rdgk.cemetery.weiview;
  2. import android.Manifest;
  3. import android.annotation.TargetApi;
  4. import android.app.Activity;
  5. import android.content.ClipData;
  6. import android.content.ContentValues;
  7. import android.content.Intent;
  8. import android.content.pm.PackageManager;
  9. import android.content.pm.ResolveInfo;
  10. import android.graphics.Bitmap;
  11. import android.icu.text.SimpleDateFormat;
  12. import android.media.MediaPlayer;
  13. import android.net.Uri;
  14. import android.os.Build;
  15. import android.os.Bundle;
  16. import android.os.Environment;
  17. import android.provider.MediaStore;
  18. import android.util.Base64;
  19. import android.util.Log;
  20. import android.view.KeyEvent;
  21. import android.view.View;
  22. import android.webkit.ValueCallback;
  23. import android.webkit.WebSettings;
  24. import android.webkit.WebView;
  25. import android.widget.LinearLayout;
  26. import android.widget.Toast;
  27. import androidx.annotation.NonNull;
  28. import androidx.annotation.Nullable;
  29. import androidx.appcompat.app.AppCompatActivity;
  30. import androidx.core.app.ActivityCompat;
  31. import androidx.core.content.ContextCompat;
  32. import androidx.core.content.FileProvider;
  33. import androidx.core.os.EnvironmentCompat;
  34. import com.just.agentweb.AgentWeb;
  35. import com.just.agentweb.PermissionInterceptor;
  36. import com.just.agentweb.WebChromeClient;
  37. import com.just.agentweb.WebViewClient;
  38. //import com.king.zxing.CameraScan;
  39. import com.rdgk.cemetery.activity.NfcActivity;
  40. import com.rdgk.cemetery.event.EventData;
  41. import com.rdgk.cemetery.R;
  42. import com.rdgk.cemetery.event.EventMp3;
  43. import com.tencent.trtc.videocall.TrtcEvent;
  44. import com.rdgk.cemetery.utils.ToastUtil;
  45. import org.greenrobot.eventbus.EventBus;
  46. import org.greenrobot.eventbus.Subscribe;
  47. import org.greenrobot.eventbus.ThreadMode;
  48. import org.json.JSONException;
  49. import org.json.JSONObject;
  50. import java.io.File;
  51. import java.io.FileInputStream;
  52. import java.io.FileNotFoundException;
  53. import java.io.IOException;
  54. import java.io.InputStream;
  55. import java.util.Date;
  56. import java.util.List;
  57. import java.util.Locale;
  58. /**
  59. * @Author pwxmax
  60. * @Date 2020.6.11
  61. * @Discription 对接H5通用的 Activity
  62. */
  63. public class WebViewActivity extends NfcActivity {
  64. private MediaPlayer mMediaPlayer = null;//媒体播放器
  65. LinearLayout linearLayout;
  66. protected AgentWeb mAgentWeb;
  67. private String url;
  68. private int REQUEST_CODE = 200;
  69. // 拍照的requestCode
  70. private static final int CAMERA_REQUEST_CODE = 0x00000010;
  71. // 申请相机权限的requestCode
  72. private static final int PERMISSION_CAMERA_REQUEST_CODE = 0x00000012;
  73. /**
  74. * 用于保存拍照图片的uri
  75. */
  76. private Uri mCameraUri;
  77. /**
  78. * 用于保存图片的文件路径,Android 10以下使用图片路径访问图片
  79. */
  80. private String mCameraImagePath;
  81. /**
  82. * 是否是Android 10以上手机
  83. */
  84. private boolean isAndroidQ = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
  85. private ValueCallback<Uri> uploadMessage;
  86. private ValueCallback<Uri[]> uploadMessageAboveL;
  87. private final static int FILE_CHOOSER_RESULT_CODE = 10000;
  88. @Override
  89. protected void onCreate(@Nullable Bundle savedInstanceState) {
  90. super.onCreate(savedInstanceState);
  91. setContentView(R.layout.activity_web);
  92. EventBus.getDefault().register(this);
  93. initView();
  94. }
  95. @Override
  96. protected void onNfcTouch() {
  97. readNfc();
  98. }
  99. public void playjieting() {
  100. mMediaPlayer = MediaPlayer.create(this, R.raw.jieting);//加载res/raw的happyis.mp3文件
  101. mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
  102. @Override
  103. public void onCompletion(MediaPlayer mediaPlayer) {
  104. if (mMediaPlayer != null) {
  105. mMediaPlayer.start();
  106. }
  107. }
  108. });
  109. mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
  110. @Override
  111. public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
  112. mediaPlayer.seekTo(0);
  113. return false;
  114. }
  115. });
  116. mMediaPlayer.start();
  117. }
  118. public void playhujiao() {
  119. mMediaPlayer = MediaPlayer.create(this, R.raw.hujiao);//加载res/raw的happyis.mp3文件
  120. mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
  121. @Override
  122. public void onCompletion(MediaPlayer mediaPlayer) {
  123. if (mMediaPlayer != null) {
  124. mMediaPlayer.start();
  125. }
  126. }
  127. });
  128. mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
  129. @Override
  130. public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
  131. mediaPlayer.seekTo(0);
  132. return false;
  133. }
  134. });
  135. mMediaPlayer.start();
  136. }
  137. public void playguaduan() {
  138. //加载res/raw的happyis.mp3文件
  139. mMediaPlayer = MediaPlayer.create(this, com.tencent.trtc.videocall.R.raw.guaduan);
  140. mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
  141. @Override
  142. public void onCompletion(MediaPlayer mp) {
  143. if (mMediaPlayer != null) {
  144. }
  145. }
  146. });
  147. mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
  148. @Override
  149. public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
  150. mediaPlayer.seekTo(0);
  151. return false;
  152. }
  153. });
  154. mMediaPlayer.start();
  155. }
  156. public void stophujiao() {
  157. if (mMediaPlayer != null) {
  158. mMediaPlayer.stop();
  159. mMediaPlayer = null;
  160. }
  161. }
  162. public void readNfc() {
  163. String s = null;
  164. try {
  165. //read nfc content from tag;
  166. s = this.readNfcContent();
  167. s = s.substring(4);
  168. mAgentWeb.getJsAccessEntrace().quickCallJs("FsNfc", s);
  169. ToastUtil.showToast(s);
  170. } catch (Exception e) {
  171. Log.e("pwx", e.toString() );
  172. ToastUtil.showToast("NFC读取失败");
  173. }
  174. }
  175. public void writeNfcContent() {
  176. SimpleDateFormat dateFormat = null;
  177. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
  178. dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
  179. }
  180. String content = dateFormat.format(System.currentTimeMillis());
  181. try {
  182. //write something to tag;
  183. this.writeNfc(content);
  184. } catch (Exception e) {
  185. ToastUtil.showToast("NFC读取失败");
  186. }
  187. }
  188. public void clearNfc() {
  189. try {
  190. //clear nfcContent
  191. this.deleteNfc();
  192. } catch (Exception e) {
  193. ToastUtil.showToast("NFC读取失败");
  194. }
  195. }
  196. private void initView() {
  197. url = getIntent().getStringExtra("url");
  198. // url="http://192.168.1.11:8080";
  199. linearLayout = findViewById(R.id.ll_webview);
  200. AndroidWebView.assistActivity(this);
  201. mAgentWeb = AgentWeb.with(this)
  202. .setAgentWebParent(linearLayout, new LinearLayout.LayoutParams(-1, -1))
  203. .closeIndicator()
  204. .setWebChromeClient(mWebChromeClient)
  205. .setWebViewClient(mWebViewClient)
  206. // .setPermissionInterceptor(mPermissionInterceptor)
  207. .createAgentWeb()
  208. .go(url);
  209. if (mAgentWeb != null) {
  210. mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new AndroidInterface(mAgentWeb, this));
  211. //注入对象
  212. WebSettings webSettings = mAgentWeb.getAgentWebSettings().getWebSettings();
  213. webSettings.setUseWideViewPort(true);//关键点
  214. webSettings.setDomStorageEnabled(true);
  215. webSettings.setDefaultTextEncodingName("UTF-8");
  216. webSettings.setAllowContentAccess(true); // 是否可访问Content Provider的资源,默认值 true
  217. webSettings.setLoadWithOverviewMode(true);
  218. webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
  219. webSettings.setBuiltInZoomControls(false); // 设置显示缩放按钮
  220. // webSettings.setAppCacheEnabled(true);//是否使用缓存
  221. webSettings.setSupportZoom(false); // 支持缩放
  222. webSettings.setAllowFileAccess(true); //允许加载本地文件html file协议, 这可能会造成不安全 , 建议重写关闭
  223. webSettings.setAllowFileAccessFromFileURLs(true); //通过 file url 加载的 Javascript 读取其他的本地文件 .建议关闭
  224. webSettings.setAllowUniversalAccessFromFileURLs(true);//允许通过 file url 加载的 Javascript 可以访问其他的源,包括其他的文件和 http,https 等其他的源
  225. mAgentWeb.getWebCreator().getWebView().setOverScrollMode(WebView.OVER_SCROLL_NEVER);
  226. }
  227. }
  228. protected PermissionInterceptor mPermissionInterceptor = new PermissionInterceptor() {
  229. /**
  230. * PermissionInterceptor 能达到 url1 允许授权, url2 拒绝授权的效果。
  231. * @param url
  232. * @param permissions
  233. * @param action
  234. * @return true 该Url对应页面请求权限进行拦截 ,false 表示不拦截。
  235. */
  236. @Override
  237. public boolean intercept(String url, String[] permissions, String action) {
  238. //Log.i(TAG, "mUrl:" + url + " permission:" + mGson.toJson(permissions) + " action:" + action);
  239. return false;
  240. }
  241. };
  242. private WebViewClient mWebViewClient = new WebViewClient() {
  243. @Override
  244. public void onPageStarted(WebView view, String url, Bitmap favicon) {
  245. //do you work
  246. }
  247. };
  248. private WebChromeClient mWebChromeClient = new WebChromeClient() {
  249. @Override
  250. public void onProgressChanged(WebView view, int newProgress) {
  251. //do you work
  252. }
  253. // For Android < 3.0
  254. public void openFileChooser(ValueCallback<Uri> valueCallback) {
  255. uploadMessage = valueCallback;
  256. openImageChooserActivity();
  257. }
  258. // For Android >= 3.0
  259. public void openFileChooser(ValueCallback valueCallback, String acceptType) {
  260. uploadMessage = valueCallback;
  261. openImageChooserActivity();
  262. }
  263. //For Android >= 4.1
  264. public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
  265. uploadMessage = valueCallback;
  266. openImageChooserActivity();
  267. }
  268. // For Android >= 5.0
  269. @Override
  270. public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
  271. uploadMessageAboveL = filePathCallback;
  272. openImageChooserActivity();
  273. return true;
  274. }
  275. };
  276. // 2.回调方法触发本地选择文件
  277. private void openImageChooserActivity() {
  278. // checkPermissionAndCamera();
  279. Intent i = new Intent(Intent.ACTION_GET_CONTENT);
  280. i.addCategory(Intent.CATEGORY_OPENABLE);
  281. i.setType("image/*");//图片上传
  282. // i.setType("file/*");//文件上传
  283. // i.setType("*/*");//文件上传
  284. startActivityForResult(Intent.createChooser(i, "File Chooser"), FILE_CHOOSER_RESULT_CODE);
  285. }
  286. @Override
  287. public boolean onKeyDown(int keyCode, KeyEvent event) {
  288. if (mAgentWeb.handleKeyEvent(keyCode, event)) {
  289. return true;
  290. }
  291. if (keyCode == KeyEvent.KEYCODE_BACK) {
  292. }
  293. return super.onKeyDown(keyCode, event);
  294. }
  295. @Override
  296. protected void onPause() {
  297. // mAgentWeb.getWebLifeCycle().onPause();
  298. super.onPause();
  299. }
  300. // @Override
  301. // protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
  302. // super.onActivityResult(requestCode, resultCode, data);
  303. // /**
  304. // * 处理二维码扫描结果
  305. // */
  306. // if (resultCode == RESULT_OK) {
  307. // switch (requestCode) {
  308. // case 200:
  309. // Bundle bundle = data.getExtras();
  310. // String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
  311. //// String result = CameraScan.parseScanResult(data);
  312. // mAgentWeb.getJsAccessEntrace().quickCallJs("QRCode", scanResult);
  313. // break;
  314. // case CAMERA_REQUEST_CODE:
  315. // if (uploadMessageAboveL != null) {
  316. // Uri[] results = new Uri[]{mCameraUri};
  317. // uploadMessageAboveL.onReceiveValue(results);
  318. // uploadMessageAboveL = null;
  319. //// onActivityResultAboveL(requestCode, resultCode, data);
  320. // } else if (uploadMessage != null) {
  321. // uploadMessage.onReceiveValue(mCameraUri);
  322. // uploadMessage = null;
  323. // }
  324. //// String uploadpath = Uri2PathUtil.getRealPathFromUri(this, mCameraUri);
  325. //// mAgentWeb.getJsAccessEntrace().quickCallJs("Camera", uploadpath);
  326. // break;
  327. // }
  328. // } else {
  329. // //这里uploadMessage跟uploadMessageAboveL在不同系统版本下分别持有了
  330. // //WebView对象,在用户取消文件选择器的情况下,需给onReceiveValue传null返回值
  331. // //否则WebView在未收到返回值的情况下,无法进行任何操作,文件选择器会失效
  332. // if (uploadMessage != null) {
  333. // uploadMessage.onReceiveValue(null);
  334. // uploadMessage = null;
  335. // } else if (uploadMessageAboveL != null) {
  336. // uploadMessageAboveL.onReceiveValue(null);
  337. // uploadMessageAboveL = null;
  338. // }
  339. // }
  340. // }
  341. //
  342. // // 3.选择图片后处理
  343. @Override
  344. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  345. super.onActivityResult(requestCode, resultCode, data);
  346. if (requestCode == FILE_CHOOSER_RESULT_CODE) {
  347. if (null == uploadMessage && null == uploadMessageAboveL) return;
  348. Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
  349. // Uri result = (((data == null) || (resultCode != RESULT_OK)) ? null : data.getData());
  350. if (uploadMessageAboveL != null) {
  351. onActivityResultAboveL(requestCode, resultCode, data);
  352. } else if (uploadMessage != null) {
  353. uploadMessage.onReceiveValue(result);
  354. uploadMessage = null;
  355. }
  356. } else {
  357. //这里uploadMessage跟uploadMessageAboveL在不同系统版本下分别持有了
  358. //WebView对象,在用户取消文件选择器的情况下,需给onReceiveValue传null返回值
  359. //否则WebView在未收到返回值的情况下,无法进行任何操作,文件选择器会失效
  360. if (uploadMessage != null) {
  361. uploadMessage.onReceiveValue(null);
  362. uploadMessage = null;
  363. } else if (uploadMessageAboveL != null) {
  364. uploadMessageAboveL.onReceiveValue(null);
  365. uploadMessageAboveL = null;
  366. }
  367. }
  368. }
  369. // 4. 选择内容回调到Html页面
  370. @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  371. private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
  372. if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
  373. return;
  374. Uri[] results = null;
  375. if (resultCode == Activity.RESULT_OK) {
  376. if (intent != null) {
  377. String dataString = intent.getDataString();
  378. ClipData clipData = intent.getClipData();
  379. if (clipData != null) {
  380. results = new Uri[clipData.getItemCount()];
  381. for (int i = 0; i < clipData.getItemCount(); i++) {
  382. ClipData.Item item = clipData.getItemAt(i);
  383. results[i] = item.getUri();
  384. }
  385. }
  386. if (dataString != null)
  387. results = new Uri[]{Uri.parse(dataString)};
  388. }
  389. }
  390. uploadMessageAboveL.onReceiveValue(results);
  391. uploadMessageAboveL = null;
  392. }
  393. @Subscribe(threadMode = ThreadMode.MAIN)
  394. public void evemp3(EventMp3 eventData) {
  395. if (eventData.getCode() == 1) {
  396. playhujiao();
  397. } else if (eventData.getCode() == 2) {
  398. playjieting();
  399. } else if (eventData.getCode() == 3) {
  400. stophujiao();
  401. } else if (eventData.getCode() == 4) {
  402. playguaduan();
  403. }
  404. }
  405. @Subscribe(threadMode = ThreadMode.MAIN)
  406. public void stopServiceEvent(EventData eventData) {
  407. if (eventData.getCode() == 1) {
  408. mAgentWeb.getJsAccessEntrace().quickCallJs("StartService", "1");
  409. } else if (eventData.getCode() == 2) {
  410. mAgentWeb.getJsAccessEntrace().quickCallJs("StartService", "2");
  411. } else if (eventData.getCode() == 3) {
  412. checkPermissionAndCamera();
  413. }
  414. }
  415. @Subscribe(threadMode = ThreadMode.MAIN)
  416. public void stopTrtcEvent(TrtcEvent trtcEvent) {
  417. if (trtcEvent.getCode() == 2) {
  418. JSONObject j = new JSONObject();
  419. try {
  420. j.put("type", trtcEvent.getTrtcType());
  421. mAgentWeb.getJsAccessEntrace().quickCallJs("TRtc", j.toString());
  422. } catch (JSONException e) {
  423. }
  424. }
  425. }
  426. /**
  427. * 检查权限并拍照。
  428. * 调用相机前先检查权限。
  429. */
  430. private void checkPermissionAndCamera() {
  431. int hasCameraPermission = ContextCompat.checkSelfPermission(getApplication(),
  432. Manifest.permission.CAMERA);
  433. if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) {
  434. //有权限,调起相机拍照。
  435. openCamera();
  436. } else {
  437. //没有权限,申请权限。
  438. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
  439. PERMISSION_CAMERA_REQUEST_CODE);
  440. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
  441. PERMISSION_CAMERA_REQUEST_CODE);
  442. }
  443. }
  444. /**
  445. * 处理权限申请的回调。
  446. *
  447. * @param requestCode
  448. * @param permissions
  449. * @param grantResults
  450. */
  451. @Override
  452. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  453. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  454. if (requestCode == PERMISSION_CAMERA_REQUEST_CODE) {
  455. if (grantResults.length > 0
  456. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  457. //允许权限,有调起相机拍照。
  458. openCamera();
  459. } else {
  460. //拒绝权限,弹出提示框。
  461. Toast.makeText(this, "拍照权限被拒绝", Toast.LENGTH_LONG).show();
  462. }
  463. }
  464. }
  465. /**
  466. * 调起相机拍照
  467. */
  468. private void openCamera() {
  469. Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  470. // 判断是否有相机
  471. if (captureIntent.resolveActivity(getPackageManager()) != null) {
  472. File photoFile = null;
  473. Uri photoUri = null;
  474. if (isAndroidQ) {
  475. // 适配android 10
  476. photoUri = createImageUri();
  477. } else {
  478. try {
  479. photoFile = createImageFile();
  480. } catch (IOException e) {
  481. e.printStackTrace();
  482. }
  483. if (photoFile != null) {
  484. mCameraImagePath = photoFile.getAbsolutePath();
  485. System.out.println("path = " + mCameraImagePath);
  486. photoUri = FileProvider.getUriForFile(WebViewActivity.this,
  487. "com.rdgk.cemetery.fileprovider", photoFile);
  488. }
  489. }
  490. System.out.println("photoUri = " + photoUri);
  491. mCameraUri = photoUri;
  492. if (photoUri != null) {
  493. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  494. List<ResolveInfo> resInfoList = getPackageManager()
  495. .queryIntentActivities(captureIntent, PackageManager.MATCH_DEFAULT_ONLY);
  496. for (ResolveInfo resolveInfo : resInfoList) {
  497. String packageName = resolveInfo.activityInfo.packageName;
  498. grantUriPermission(packageName, photoUri,
  499. Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
  500. }
  501. }
  502. captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
  503. captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
  504. startActivityForResult(captureIntent, CAMERA_REQUEST_CODE);
  505. }
  506. }
  507. }
  508. /**
  509. * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
  510. *
  511. * @return 图片的uri
  512. */
  513. private Uri createImageUri() {
  514. //设置保存参数到ContentValues中
  515. ContentValues contentValues = new ContentValues();
  516. //设置文件名
  517. contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, System.currentTimeMillis() + "");
  518. //兼容Android Q和以下版本
  519. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
  520. //android Q中不再使用DATA字段,而用RELATIVE_PATH代替
  521. //TODO RELATIVE_PATH是相对路径不是绝对路径;照片存储的地方为:内部存储/Pictures/preventpro
  522. contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/preventpro");
  523. }
  524. //设置文件类型
  525. contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG");
  526. //执行insert操作,向系统文件夹中添加文件
  527. //EXTERNAL_CONTENT_URI代表外部存储器,该值不变
  528. Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
  529. return uri;
  530. }
  531. /**
  532. * 创建保存图片的文件
  533. *
  534. * @return
  535. * @throws IOException
  536. */
  537. private File createImageFile() throws IOException {
  538. String imageName = null;
  539. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
  540. imageName = new SimpleDateFormat("yyyyMMdd_HHmmss",
  541. Locale.getDefault()).format(new Date()) + ".jpg";
  542. }
  543. // File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
  544. // File storageDir = Environment.getExternalStoragePublicDirectory(
  545. // Environment.DIRECTORY_PICTURES);
  546. File storageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
  547. + File.separator + "Pictures" + File.separator + "abc");
  548. if (!storageDir.exists()) storageDir.mkdirs();
  549. File tempFile = new File(storageDir, imageName);
  550. if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
  551. return null;
  552. }
  553. return tempFile;
  554. }
  555. /**
  556. * 文件转base64字符串
  557. *
  558. * @param file
  559. * @return
  560. */
  561. public String fileToBase64(File file) {
  562. String base64 = null;
  563. InputStream in = null;
  564. try {
  565. in = new FileInputStream(file);
  566. byte[] bytes = new byte[in.available()];
  567. int length = in.read(bytes);
  568. base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT);
  569. } catch (FileNotFoundException e) {
  570. // TODO Auto-generated catch block
  571. ToastUtil.showToast("文件读取异常");
  572. } catch (IOException e) {
  573. // TODO Auto-generated catch block
  574. ToastUtil.showToast("IO读取异常");
  575. } finally {
  576. try {
  577. if (in != null) {
  578. in.close();
  579. }
  580. } catch (IOException e) {
  581. // TODO Auto-generated catch block
  582. ToastUtil.showToast("IO关闭异常");
  583. }
  584. }
  585. return base64;
  586. }
  587. @Override
  588. protected void onResume() {
  589. // mAgentWeb.getWebLifeCycle().onResume();
  590. super.onResume();
  591. }
  592. @Override
  593. public void onDestroy() {
  594. super.onDestroy();
  595. mAgentWeb.getWebLifeCycle().onDestroy();
  596. EventBus.getDefault().unregister(this);
  597. }
  598. @Override
  599. public void onPointerCaptureChanged(boolean hasCapture) {
  600. }
  601. }