PageRenderTime 55ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/app/src/main/java/com/gzsll/hupu/widget/HuPuWebView.java

https://gitlab.com/gzsll/TLint
Java | 323 lines | 286 code | 31 blank | 6 comment | 38 complexity | 63fa7efd0fbe695120cc096b494333b7 MD5 | raw file
  1. package com.gzsll.hupu.widget;
  2. import android.content.Context;
  3. import android.net.Uri;
  4. import android.os.Build;
  5. import android.text.TextUtils;
  6. import android.util.AttributeSet;
  7. import android.webkit.ConsoleMessage;
  8. import android.webkit.CookieManager;
  9. import android.webkit.CookieSyncManager;
  10. import android.webkit.WebChromeClient;
  11. import android.webkit.WebResourceError;
  12. import android.webkit.WebResourceRequest;
  13. import android.webkit.WebSettings;
  14. import android.webkit.WebView;
  15. import android.webkit.WebViewClient;
  16. import com.gzsll.hupu.AppManager;
  17. import com.gzsll.hupu.Constants;
  18. import com.gzsll.hupu.MyApplication;
  19. import com.gzsll.hupu.components.retrofit.RequestHelper;
  20. import com.gzsll.hupu.components.storage.UserStorage;
  21. import com.gzsll.hupu.ui.browser.BrowserActivity;
  22. import com.gzsll.hupu.ui.content.ContentActivity;
  23. import com.gzsll.hupu.ui.imagepreview.ImagePreviewActivity;
  24. import com.gzsll.hupu.ui.login.LoginActivity;
  25. import com.gzsll.hupu.ui.post.PostActivity;
  26. import com.gzsll.hupu.ui.report.ReportActivity;
  27. import com.gzsll.hupu.ui.thread.list.ThreadListActivity;
  28. import com.gzsll.hupu.ui.userprofile.UserProfileActivity;
  29. import com.gzsll.hupu.util.StringUtils;
  30. import com.gzsll.hupu.util.ToastUtils;
  31. import java.net.URLEncoder;
  32. import java.util.ArrayList;
  33. import java.util.HashMap;
  34. import java.util.Map;
  35. import javax.inject.Inject;
  36. import org.apache.log4j.Logger;
  37. import org.json.JSONArray;
  38. import org.json.JSONException;
  39. import org.json.JSONObject;
  40. /**
  41. * Created by sll on 2015/12/10.
  42. */
  43. public class HuPuWebView extends WebView {
  44. private Logger logger = Logger.getLogger(HuPuWebView.class.getSimpleName());
  45. private String basicUA;
  46. private Map<String, String> header;
  47. @Inject UserStorage mUserStorage;
  48. @Inject RequestHelper mRequestHelper;
  49. public HuPuWebView(Context context) {
  50. super(context);
  51. init();
  52. }
  53. public HuPuWebView(Context context, AttributeSet attrs) {
  54. super(context, attrs);
  55. init();
  56. }
  57. public void setCallBack(HuPuWebViewCallBack callBack) {
  58. this.callBack = callBack;
  59. }
  60. public class HuPuChromeClient extends WebChromeClient {
  61. @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
  62. logger.debug(
  63. "onConsoleMessage:" + consoleMessage.message() + ":" + consoleMessage.lineNumber());
  64. return true;
  65. }
  66. }
  67. private void init() {
  68. ((MyApplication) getContext().getApplicationContext()).getApplicationComponent().inject(this);
  69. WebSettings settings = getSettings();
  70. settings.setBuiltInZoomControls(false);
  71. settings.setSupportZoom(false);
  72. settings.setJavaScriptEnabled(true);
  73. settings.setAllowFileAccess(true);
  74. settings.setSupportMultipleWindows(false);
  75. settings.setJavaScriptCanOpenWindowsAutomatically(true);
  76. settings.setDomStorageEnabled(true);
  77. settings.setCacheMode(1);
  78. settings.setUseWideViewPort(true);
  79. if (Build.VERSION.SDK_INT > 6) {
  80. settings.setAppCacheEnabled(true);
  81. settings.setLoadWithOverviewMode(true);
  82. }
  83. settings.setCacheMode(WebSettings.LOAD_DEFAULT);
  84. String path = getContext().getFilesDir().getPath();
  85. settings.setGeolocationEnabled(true);
  86. settings.setGeolocationDatabasePath(path);
  87. settings.setDomStorageEnabled(true);
  88. this.basicUA = settings.getUserAgentString() + " kanqiu/7.05.6303/7059";
  89. setBackgroundColor(0);
  90. initWebViewClient();
  91. setWebChromeClient(new HuPuChromeClient());
  92. try {
  93. if (mUserStorage.isLogin()) {
  94. String token = mUserStorage.getToken();
  95. CookieManager cookieManager = CookieManager.getInstance();
  96. cookieManager.setCookie("http://bbs.mobileapi.hupu.com",
  97. "u=" + URLEncoder.encode(mUserStorage.getCookie(), "utf-8"));
  98. cookieManager.setCookie("http://bbs.mobileapi.hupu.com",
  99. "_gamesu=" + URLEncoder.encode(token, "utf-8"));
  100. cookieManager.setCookie("http://bbs.mobileapi.hupu.com", "_inKanqiuApp=1");
  101. cookieManager.setCookie("http://bbs.mobileapi.hupu.com", "_kanqiu=1");
  102. CookieSyncManager.getInstance().sync();
  103. }
  104. } catch (Exception e) {
  105. e.printStackTrace();
  106. }
  107. }
  108. private void initWebViewClient() {
  109. CookieManager.getInstance().setAcceptCookie(true);
  110. setWebViewClient(new HupuWebClient());
  111. }
  112. private class HupuWebClient extends WebViewClient {
  113. @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
  114. logger.debug(Uri.decode(url));
  115. Uri uri = Uri.parse(url);
  116. String scheme = uri.getScheme();
  117. if (url.startsWith("hupu") || url.startsWith("kanqiu")) {
  118. if (scheme != null) {
  119. handleScheme(scheme, url);
  120. }
  121. } else if (scheme.equals("http") || scheme.equals("https")) {
  122. BrowserActivity.startActivity(getContext(), url);
  123. }
  124. return true;
  125. }
  126. @Override public void onPageFinished(WebView view, String url) {
  127. super.onPageFinished(view, url);
  128. if (callBack != null) {
  129. callBack.onFinish();
  130. }
  131. }
  132. @Override
  133. public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
  134. super.onReceivedError(view, request, error);
  135. if (callBack != null) {
  136. callBack.onError();
  137. }
  138. }
  139. }
  140. private void handleScheme(String scheme, String url) {
  141. if (scheme != null) {
  142. if (scheme.equalsIgnoreCase("kanqiu")) {
  143. handleKanQiu(url);
  144. } else if (scheme.equalsIgnoreCase("browser")
  145. || scheme.equalsIgnoreCase("http")
  146. || scheme.equalsIgnoreCase("https")) {
  147. BrowserActivity.startActivity(getContext(), url);
  148. } else if (scheme.equalsIgnoreCase("hupu")) {
  149. try {
  150. JSONObject object = new JSONObject(Uri.decode(url.substring("hupu".length() + 3)));
  151. String method = object.optString("method");
  152. String successcb = object.optString("successcb");
  153. handleHuPu(method, object.getJSONObject("data"), successcb);
  154. } catch (Exception e) {
  155. e.printStackTrace();
  156. }
  157. }
  158. }
  159. }
  160. private void handleKanQiu(String url) {
  161. if (url.contains("topic")) {
  162. Uri uri = Uri.parse(url);
  163. String tid = uri.getLastPathSegment();
  164. logger.debug("tid:" + tid);
  165. String page = uri.getQueryParameter("page");
  166. logger.debug("page:" + page);
  167. String pid = uri.getQueryParameter("pid");
  168. logger.debug("pid:" + pid);
  169. ContentActivity.startActivity(getContext(), "", tid, pid,
  170. TextUtils.isEmpty(page) ? 1 : Integer.valueOf(page));
  171. } else if (url.contains("board")) {
  172. String boardId = url.substring(url.lastIndexOf("/") + 1);
  173. ThreadListActivity.startActivity(getContext(), boardId);
  174. } else if (url.contains("people")) {
  175. String uid = url.substring(url.lastIndexOf("/") + 1);
  176. UserProfileActivity.startActivity(getContext(), uid);
  177. }
  178. }
  179. private void handleHuPu(String method, JSONObject data, String successcb) throws Exception {
  180. switch (method) {
  181. case "bridgeReady":
  182. JSONObject jSONObject = new JSONObject();
  183. try {
  184. jSONObject.put("hybridVer", "1.0");
  185. jSONObject.put("supportAjax", true);
  186. jSONObject.put("appVer", "7.0.5.6303");
  187. jSONObject.put("appName", "com.hupu.games");
  188. jSONObject.put("lowDevice", false);
  189. jSONObject.put("scheme", "hupu");
  190. jSONObject.put("did", mRequestHelper.getDeviceId());
  191. jSONObject.put("platform", "Android");
  192. jSONObject.put("device", Build.PRODUCT);
  193. jSONObject.put("osVer", Build.VERSION.RELEASE);
  194. } catch (JSONException e) {
  195. e.printStackTrace();
  196. }
  197. String js = "javascript:HupuBridge._handle_('"
  198. + successcb
  199. + "','"
  200. + jSONObject.toString()
  201. + "','null','null');";
  202. loadUrl(js);
  203. break;
  204. case "hupu.ui.updatebbspager":
  205. int page = data.getInt("page");
  206. int total = data.getInt("total");
  207. if (callBack != null) {
  208. callBack.onUpdatePager(page, total);
  209. }
  210. break;
  211. case "hupu.ui.bbsreply":
  212. boolean open = data.getBoolean("open");
  213. JSONObject extra = data.getJSONObject("extra");
  214. String tid = extra.getString("tid");
  215. long pid = extra.getLong("pid");
  216. String userName = extra.getString("username");
  217. String content = extra.getString("content");
  218. if (open) {
  219. PostActivity.startActivity(getContext(), Constants.TYPE_REPLY, "", tid,
  220. String.valueOf(pid), content);
  221. }
  222. break;
  223. case "hupu.album.view":
  224. int index = data.getInt("index");
  225. JSONArray images = data.getJSONArray("images");
  226. ArrayList<String> extraPics = new ArrayList<>();
  227. for (int i = 0; i < images.length(); i++) {
  228. JSONObject image = images.getJSONObject(i);
  229. extraPics.add(image.getString("url"));
  230. }
  231. ImagePreviewActivity.startActivity(getContext(), extraPics.get(index), extraPics);
  232. break;
  233. case "hupu.ui.copy":
  234. String copy = data.getString("content");
  235. StringUtils.copy(getContext(), copy);
  236. break;
  237. case "hupu.ui.report":
  238. JSONObject reportExtra = data.getJSONObject("extra");
  239. String reportTid = reportExtra.getString("tid");
  240. long reportPid = reportExtra.getLong("pid");
  241. ReportActivity.startActivity(getContext(), reportTid, String.valueOf(reportPid));
  242. break;
  243. case "hupu.user.login":
  244. LoginActivity.startActivity(getContext());
  245. ToastUtils.showToast("请先登录");
  246. break;
  247. case "hupu.ui.pageclose":
  248. AppManager.getAppManager().finishActivity();
  249. break;
  250. }
  251. }
  252. private void setUA(int i) {
  253. if (this.basicUA != null) {
  254. getSettings().setUserAgentString(this.basicUA + " isp/" + i + " network/" + i);
  255. }
  256. }
  257. public void loadUrl(String url) {
  258. logger.debug("loadUrl:" + url);
  259. setUA(-1);
  260. if (header == null) {
  261. header = new HashMap<>();
  262. header.put("Accept-Encoding", "gzip");
  263. }
  264. super.loadUrl(url, header);
  265. }
  266. private HuPuWebViewCallBack callBack;
  267. public interface HuPuWebViewCallBack {
  268. void onFinish();
  269. void onUpdatePager(int page, int total);
  270. void onError();
  271. }
  272. private OnScrollChangedCallback mOnScrollChangedCallback;
  273. @Override
  274. protected void onScrollChanged(final int l, final int t, final int oldl, final int oldt) {
  275. super.onScrollChanged(l, t, oldl, oldt);
  276. if (mOnScrollChangedCallback != null) {
  277. mOnScrollChangedCallback.onScroll(l - oldl, t - oldt);
  278. }
  279. }
  280. public OnScrollChangedCallback getOnScrollChangedCallback() {
  281. return mOnScrollChangedCallback;
  282. }
  283. public void setOnScrollChangedCallback(final OnScrollChangedCallback onScrollChangedCallback) {
  284. mOnScrollChangedCallback = onScrollChangedCallback;
  285. }
  286. /**
  287. * Impliment in the activity/fragment/view that you want to listen to the webview
  288. */
  289. public interface OnScrollChangedCallback {
  290. void onScroll(int dx, int dy);
  291. }
  292. }