gabbhack

Untitled

Nov 17th, 2016
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.62 KB | None | 0 0
  1. package biz.zismo.m.providers.web;
  2.  
  3. import biz.zismo.m.BackPressFragment;
  4. import biz.zismo.m.MainActivity;
  5. import biz.zismo.m.R;
  6. import biz.zismo.m.fav.FavDbAdapter;
  7. import biz.zismo.m.util.Helper;
  8.  
  9. import android.content.pm.ActivityInfo;
  10. import android.graphics.Color;
  11. import android.annotation.SuppressLint;
  12. import android.app.Activity;
  13. import android.os.Environment;
  14. import android.provider.MediaStore;
  15. import android.support.v4.app.Fragment;
  16. import android.support.v4.widget.SwipeRefreshLayout;
  17. import android.support.v7.app.ActionBar;
  18. import android.support.v7.app.ActionBar.LayoutParams;
  19. import android.support.v7.app.AppCompatActivity;
  20. import android.content.Context;
  21. import android.content.Intent;
  22. import android.net.ConnectivityManager;
  23. import android.net.NetworkInfo;
  24. import android.net.Uri;
  25. import android.os.Bundle;
  26. import android.view.Gravity;
  27. import android.view.LayoutInflater;
  28. import android.view.Menu;
  29. import android.view.MenuInflater;
  30. import android.view.MenuItem;
  31. import android.view.MotionEvent;
  32. import android.view.View;
  33. import android.view.ViewGroup;
  34. import android.webkit.DownloadListener;
  35. import android.webkit.ValueCallback;
  36. import android.webkit.WebChromeClient;
  37. import android.webkit.WebSettings.PluginState;
  38. import android.webkit.WebView;
  39. import android.webkit.WebViewClient;
  40. import android.widget.FrameLayout;
  41. import android.widget.ImageButton;
  42. import android.widget.LinearLayout;
  43. import android.widget.Toast;
  44.  
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.text.SimpleDateFormat;
  48. import java.util.Date;
  49.  
  50. /**
  51. * This activity is used to display webpages
  52. */
  53.  
  54. public class WebviewFragment extends Fragment implements BackPressFragment {
  55.  
  56. //Static
  57. public static final String HIDE_NAVIGATION = "hide_navigation";
  58. public static final String LOAD_DATA = "loadwithdata";
  59.  
  60. //File upload
  61. public static final int INPUT_FILE_REQUEST_CODE = 1;
  62. public static final String EXTRA_FROM_NOTIFICATION = "EXTRA_FROM_NOTIFICATION";
  63.  
  64. private WebView mWebView;
  65. private ValueCallback<Uri[]> mFilePathCallback;
  66. private String mCameraPhotoPath;
  67.  
  68. //References
  69. private Activity mAct;
  70. private FavDbAdapter mDbHelper;
  71.  
  72. //Layout with interaction
  73. private WebView browser;
  74. private SwipeRefreshLayout mSwipeRefreshLayout;
  75.  
  76. //Layouts
  77. private ImageButton webBackButton;
  78. private ImageButton webForwButton;
  79. private LinearLayout ll;
  80.  
  81. //HTML5 video
  82. private View mCustomView;
  83. private int mOriginalSystemUiVisibility;
  84. private WebChromeClient.CustomViewCallback mCustomViewCallback;
  85.  
  86. @SuppressLint("InflateParams")
  87. @Override
  88. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  89. Bundle savedInstanceState) {
  90. super.onCreate(savedInstanceState);
  91.  
  92. //Return the existing layout if there is a savedInstance of this fragment
  93. if (savedInstanceState != null) { return ll; }
  94.  
  95. ll = (LinearLayout) inflater.inflate(R.layout.fragment_webview,
  96. container, false);
  97.  
  98. setHasOptionsMenu(true);
  99.  
  100. browser = (WebView) ll.findViewById(R.id.webView);
  101. mSwipeRefreshLayout = (SwipeRefreshLayout) ll.findViewById(R.id.refreshlayout);
  102.  
  103. // settings some settings like zooming etc in seperate method for
  104. // suppresslint
  105. browserSettings();
  106.  
  107. browser.setWebViewClient(new WebViewClient() {
  108. // Make sure any url clicked is opened in webview
  109. @Override
  110. public boolean shouldOverrideUrlLoading(WebView view, String url) {
  111. if ((url.contains("market://") || url.contains("mailto:")
  112. || url.contains("play.google") || url.contains("tel:") || url
  113. .contains("vid:")) == true) {
  114. // Load new URL Don't override URL Link
  115. view.getContext().startActivity(
  116. new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
  117.  
  118. return true;
  119. }
  120. // Return true to override url loading (In this case do
  121. // nothing).
  122. return false;
  123. }
  124.  
  125. @Override
  126. public void onPageFinished(WebView view, String url) {
  127. super.onPageFinished(browser, url);
  128.  
  129. adjustControls();
  130. }
  131.  
  132. });
  133.  
  134. // has all to do with progress bar
  135. browser.setWebChromeClient(new WebChromeClient() {
  136. public boolean onShowFileChooser(
  137. WebView webView, ValueCallback<Uri[]> filePathCallback,
  138. WebChromeClient.FileChooserParams fileChooserParams) {
  139. if(mFilePathCallback != null) {
  140. mFilePathCallback.onReceiveValue(null);
  141. }
  142. mFilePathCallback = filePathCallback;
  143.  
  144. Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  145. if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
  146. // Create the File where the photo should go
  147. File photoFile = null;
  148. try {
  149. photoFile = createImageFile();
  150. takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
  151. } catch (IOException ex) {
  152. // Error occurred while creating the File
  153. }
  154.  
  155. // Continue only if the File was successfully created
  156. if (photoFile != null) {
  157. mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
  158. takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
  159. Uri.fromFile(photoFile));
  160. } else {
  161. takePictureIntent = null;
  162. }
  163. }
  164.  
  165. Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
  166. contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
  167. contentSelectionIntent.setType("image/*");
  168.  
  169. Intent[] intentArray;
  170. if(takePictureIntent != null) {
  171. intentArray = new Intent[]{takePictureIntent};
  172. } else {
  173. intentArray = new Intent[0];
  174. }
  175.  
  176. Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
  177. chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
  178. chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
  179. chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
  180.  
  181. startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
  182.  
  183. return true;
  184. }
  185.  
  186. @Override
  187. public void onProgressChanged(WebView view, int progress) {
  188. if (mSwipeRefreshLayout.isRefreshing()) {
  189. if (progress == 100) {
  190. mSwipeRefreshLayout.setRefreshing(false);
  191. }
  192. } else if (progress < 100){
  193. //If we do not hide the navigation, show refreshing
  194. if (!WebviewFragment.this.getArguments().containsKey(HIDE_NAVIGATION) ||
  195. WebviewFragment.this.getArguments().getBoolean(HIDE_NAVIGATION) == false)
  196. mSwipeRefreshLayout.setRefreshing(true);
  197. }
  198. }
  199.  
  200. @SuppressLint("InlinedApi")
  201. @Override
  202. public void onShowCustomView(View view,
  203. WebChromeClient.CustomViewCallback callback) {
  204. // if a view already exists then immediately terminate the new one
  205. if (mCustomView != null) {
  206. onHideCustomView();
  207. return;
  208. }
  209.  
  210. // 1. Stash the current state
  211. mCustomView = view;
  212. mCustomView.setBackgroundColor(Color.BLACK);
  213. mOriginalSystemUiVisibility = getActivity().getWindow().getDecorView().getSystemUiVisibility();
  214.  
  215. // 2. Stash the custom view callback
  216. mCustomViewCallback = callback;
  217.  
  218. // 3. Add the custom view to the view hierarchy
  219. FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
  220. decor.addView(mCustomView, new FrameLayout.LayoutParams(
  221. ViewGroup.LayoutParams.MATCH_PARENT,
  222. ViewGroup.LayoutParams.MATCH_PARENT));
  223.  
  224.  
  225. // 4. Change the state of the window
  226. getActivity().getWindow().getDecorView().setSystemUiVisibility(
  227. View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
  228. View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
  229. View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
  230. View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
  231. View.SYSTEM_UI_FLAG_FULLSCREEN |
  232. View.SYSTEM_UI_FLAG_IMMERSIVE);
  233. getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
  234. }
  235.  
  236. @Override
  237. public void onHideCustomView() {
  238. // 1. Remove the custom view
  239. FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
  240. decor.removeView(mCustomView);
  241. mCustomView = null;
  242.  
  243. // 2. Restore the state to it's original form
  244. getActivity().getWindow().getDecorView()
  245. .setSystemUiVisibility(mOriginalSystemUiVisibility);
  246.  
  247. //TODO Find a better solution to the keyboard not showing after custom view is hidden
  248. //The user will come from landscape, so we'll first 'rotate' to portrait (rotation fixes a bug of the keybaord not showing)
  249. getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  250. //The we'll restore to the detected orientation (by immediately rotating back, the user should not notice any difference and/or flickering).
  251. getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
  252.  
  253. // 3. Call the custom view callback
  254. mCustomViewCallback.onCustomViewHidden();
  255. mCustomViewCallback = null;
  256.  
  257.  
  258. }
  259.  
  260. });
  261.  
  262. browser.setDownloadListener(new DownloadListener() {
  263. public void onDownloadStart(String url, String userAgent,
  264. String contentDisposition, String mimetype,
  265. long contentLength) {
  266. Intent i = new Intent(Intent.ACTION_VIEW);
  267. i.setData(Uri.parse(url));
  268. startActivity(i);
  269. }
  270. });
  271.  
  272. // setting an on touch listener
  273. browser.setOnTouchListener(new View.OnTouchListener() {
  274. @SuppressLint("ClickableViewAccessibility")
  275. @Override
  276. public boolean onTouch(View v, MotionEvent event) {
  277. switch (event.getAction()) {
  278. case MotionEvent.ACTION_DOWN:
  279. case MotionEvent.ACTION_UP:
  280. if (!v.hasFocus()) {
  281. v.requestFocus();
  282. }
  283. break;
  284. }
  285. return false;
  286. }
  287. });
  288.  
  289. mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
  290. @Override
  291. public void onRefresh() {
  292. browser.reload();
  293. }
  294. });
  295.  
  296. return ll;
  297. }// of oncreateview
  298.  
  299. @Override
  300. public void onActivityCreated(Bundle savedInstanceState) {
  301. super.onActivityCreated(savedInstanceState);
  302. mAct = getActivity();
  303.  
  304. setRetainInstance(true);
  305.  
  306. String weburl = getArguments().getStringArray(MainActivity.FRAGMENT_DATA)[0];
  307. String data = getArguments().containsKey(LOAD_DATA) ? getArguments().getString(LOAD_DATA) : null;
  308. if (checkConnectivity() || weburl.startsWith("file:///android_asset/")) {
  309. //If this is the first time, load the initial url, otherwise restore the view if necessairy
  310. if (savedInstanceState == null) {
  311. //If we have HTML data to load, do so, else load the url.
  312. if (data != null) {
  313. browser.loadDataWithBaseURL(weburl, data, "text/html", "UTF-8", "");
  314. } else {
  315. browser.loadUrl(weburl);
  316. }
  317. } else if (mCustomView != null){
  318. FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
  319. ((ViewGroup) mCustomView.getParent()).removeView(mCustomView);
  320. decor.addView(mCustomView, new FrameLayout.LayoutParams(
  321. ViewGroup.LayoutParams.MATCH_PARENT,
  322. ViewGroup.LayoutParams.MATCH_PARENT));
  323. }
  324. }
  325.  
  326. }
  327.  
  328. @Override
  329. public void onPause() {
  330. super.onPause();
  331. browser.onPause();
  332. }
  333.  
  334. @Override
  335. public void onResume() {
  336. super.onResume();
  337. browser.onResume();
  338.  
  339. if (!this.getArguments().containsKey(HIDE_NAVIGATION) ||
  340. this.getArguments().getBoolean(HIDE_NAVIGATION) == false){
  341.  
  342. ActionBar actionBar = ((AppCompatActivity) mAct)
  343. .getSupportActionBar();
  344.  
  345. if (mAct instanceof WebviewActivity) {
  346. actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_HOME_AS_UP);
  347. } else {
  348. actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
  349. }
  350.  
  351. View view = mAct.getLayoutInflater().inflate(R.layout.fragment_webview_actionbar, null);
  352. LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.END | Gravity.CENTER_VERTICAL);
  353. actionBar.setCustomView(view, lp);
  354.  
  355. webBackButton = (ImageButton) mAct.findViewById(R.id.goBack);
  356. webForwButton = (ImageButton) mAct.findViewById(R.id.goForward);
  357.  
  358. webBackButton.setOnClickListener(new View.OnClickListener() {
  359. @Override
  360. public void onClick(View v) {
  361. if (browser.canGoBack())
  362. browser.goBack();
  363. }
  364. });
  365. webForwButton.setOnClickListener(new View.OnClickListener() {
  366. @Override
  367. public void onClick(View v) {
  368. if (browser.canGoForward())
  369. browser.goForward();
  370. }
  371. });
  372. } else {
  373. mSwipeRefreshLayout.setEnabled(false);
  374. }
  375.  
  376. adjustControls();
  377. }
  378.  
  379. @Override
  380. public void onStop() {
  381. super.onStop();
  382.  
  383. if (!this.getArguments().containsKey(HIDE_NAVIGATION) ||
  384. this.getArguments().getBoolean(HIDE_NAVIGATION) == false) {
  385.  
  386. ActionBar actionBar = ((AppCompatActivity) getActivity())
  387. .getSupportActionBar();
  388.  
  389. actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
  390. }
  391.  
  392. }
  393.  
  394. /**
  395. * More info this method can be found at
  396. * http://developer.android.com/training/camera/photobasics.html
  397. *
  398. * @return
  399. * @throws IOException
  400. */
  401. private File createImageFile() throws IOException {
  402. // Create an image file name
  403. String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
  404. String imageFileName = "JPEG_" + timeStamp + "_";
  405. File storageDir = Environment.getExternalStoragePublicDirectory(
  406. Environment.DIRECTORY_PICTURES);
  407. File imageFile = File.createTempFile(
  408. imageFileName, /* prefix */
  409. ".jpg", /* suffix */
  410. storageDir /* directory */
  411. );
  412. return imageFile;
  413. }
  414.  
  415. @Override
  416. public boolean onOptionsItemSelected(MenuItem item) {
  417. switch (item.getItemId()) {
  418. case R.id.share:
  419. shareURL();
  420. return true;
  421. case R.id.favorite:
  422. mDbHelper = new FavDbAdapter(mAct);
  423. mDbHelper.open();
  424.  
  425. String title = browser.getTitle();
  426. String url = browser.getUrl();
  427.  
  428. if (mDbHelper.checkEvent(title, url, FavDbAdapter.KEY_WEB)) {
  429. // This item is new
  430. mDbHelper.addFavorite(title, url, FavDbAdapter.KEY_WEB);
  431. Toast toast = Toast.makeText(mAct,
  432. getResources().getString(R.string.favorite_success),
  433. Toast.LENGTH_LONG);
  434. toast.show();
  435. } else {
  436. Toast toast = Toast.makeText(mAct,
  437. getResources().getString(R.string.favorite_duplicate),
  438. Toast.LENGTH_LONG);
  439. toast.show();
  440. }
  441. return true;
  442. default:
  443. return super.onOptionsItemSelected(item);
  444. }
  445. }
  446.  
  447. @Override
  448. public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  449. inflater.inflate(R.menu.webview_menu, menu);
  450. }
  451.  
  452. // Checking for an internet connection
  453. private boolean checkConnectivity() {
  454. boolean enabled = true;
  455.  
  456. ConnectivityManager connectivityManager = (ConnectivityManager) mAct
  457. .getSystemService(Context.CONNECTIVITY_SERVICE);
  458. NetworkInfo info = connectivityManager.getActiveNetworkInfo();
  459.  
  460. if ((info == null || !info.isConnected() || !info.isAvailable())) {
  461. enabled = false;
  462.  
  463. Helper.noConnection(mAct);
  464. }
  465.  
  466. return enabled;
  467. }
  468.  
  469. public void adjustControls() {
  470. webBackButton = (ImageButton) mAct.findViewById(R.id.goBack);
  471. webForwButton = (ImageButton) mAct.findViewById(R.id.goForward);
  472.  
  473. if (webBackButton == null || webForwButton == null) return;
  474.  
  475. if (browser.canGoBack()) {
  476. webBackButton.setColorFilter(Color.argb(255, 255, 255, 255));
  477. } else {
  478. webBackButton.setColorFilter(Color.argb(255, 0, 0, 0));
  479. }
  480. if (browser.canGoForward()) {
  481. webForwButton.setColorFilter(Color.argb(255, 255, 255, 255));
  482. } else {
  483. webForwButton.setColorFilter(Color.argb(255, 0, 0, 0));
  484. }
  485. }
  486.  
  487. // sharing
  488. private void shareURL() {
  489. Intent shareIntent = new Intent(Intent.ACTION_SEND);
  490. shareIntent.setType("text/plain");
  491. String appname = getString(R.string.app_name);
  492. shareIntent.putExtra(Intent.EXTRA_TEXT,
  493. (getResources().getString(R.string.web_share_begin)) + appname
  494. + getResources().getString(R.string.web_share_end)
  495. + browser.getUrl());
  496. startActivity(Intent.createChooser(shareIntent, getResources()
  497. .getString(R.string.share)));
  498. }
  499.  
  500. @SuppressLint("SetJavaScriptEnabled")
  501. @SuppressWarnings("deprecation")
  502. private void browserSettings() {
  503. // set javascript and zoom and some other settings
  504. browser.getSettings().setJavaScriptEnabled(true);
  505. browser.getSettings().setBuiltInZoomControls(true);
  506. browser.getSettings().setDisplayZoomControls(false);
  507. browser.getSettings().setAppCacheEnabled(true);
  508. browser.getSettings().setDatabaseEnabled(true);
  509. browser.getSettings().setDomStorageEnabled(true);
  510. browser.getSettings().setUseWideViewPort(true);
  511. browser.getSettings().setLoadWithOverviewMode(true);
  512.  
  513. // enable all plugins (flash)
  514. browser.getSettings().setPluginState(PluginState.ON);
  515. }
  516.  
  517. @Override
  518. public boolean handleBackPress() {
  519. if (browser.canGoBack()){
  520. browser.goBack();
  521. return true;
  522. }
  523.  
  524. return false;
  525. }
  526.  
  527. @Override
  528. public void onActivityResult (int requestCode, int resultCode, Intent data) {
  529. if(requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
  530. super.onActivityResult(requestCode, resultCode, data);
  531. return;
  532. }
  533.  
  534. Uri[] results = null;
  535.  
  536. // Check that the response is a good one
  537. if(resultCode == Activity.RESULT_OK) {
  538. if(data == null) {
  539. // If there is not data, then we may have taken a photo
  540. if(mCameraPhotoPath != null) {
  541. results = new Uri[]{Uri.parse(mCameraPhotoPath)};
  542. }
  543. } else {
  544. String dataString = data.getDataString();
  545. if (dataString != null) {
  546. results = new Uri[]{Uri.parse(dataString)};
  547. }
  548. }
  549. }
  550.  
  551. mFilePathCallback.onReceiveValue(results);
  552. mFilePathCallback = null;
  553. return;
  554. }
  555. }
Advertisement
Add Comment
Please, Sign In to add comment