2018-01-02

关于技术分享的一种思路

  1. 登陆网站 用 markdown 可视化编写文档(https://www.jianshu.com/)并发布
  2. 下载写好的文档,导出为pdf
  3. 上传到移动办公 OA 文档库

这样做有2个好处:文章格式排板,markdown已经帮我们做了很多工作,可以专注要分享的内容创作上; OA app 2018年在单位推开后,可以通过手机随时查看分享的文章

markdown 语法简单介绍

https://www.jianshu.com/p/1e402922ee32/

代码分享例子

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;![屏幕快照 2018-01-02 16.16.47.png](http://upload-images.jianshu.io/upload_images/9896733-68939db0e561629c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.PermissionRequest;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.szse.scoa.R;
import com.szse.scoa.data.LocalDataInterface;
import com.szse.scoa.log.Logger;
import com.szse.scoa.net.HttpInterface;
import com.szse.scoa.ui.fragment.LifecycleFragment;
import com.szse.scoa.ui.js.JsInterface;

import java.util.Arrays;

/**
 * 通用的webview界面
 *
 * @author y
 */
public class WebCommonFragment extends LifecycleFragment {

    public static final String PARAM_URL = "param_url";
    private WebView mWebView;
    private boolean mIsWebViewAvailable;
    protected String url;

    /**
     * 页面是否已经加载完成
     */
    protected boolean pageFinished;
    protected JsInterface js;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("action_web_refresh".equals(action)) {
                refresh(intent.getStringExtra("extra_url"), intent.getStringExtra("extra_method"));
            } else {
                syncCookie(mWebView);
            }
        }
    };

    public static WebCommonFragment newInstance(String url) {
        WebCommonFragment fragment = new WebCommonFragment();
        Bundle b = new Bundle();
        b.putString(PARAM_URL, url);
        fragment.setArguments(b);
        return fragment;
    }

    private void refresh(String url, String method) {
        if (getActivity() == null) {
            return;
        }
        String webViewUrl = mWebView.getUrl();
        log("refresh:" + webViewUrl + " " + url);
        if (url == null || webViewUrl == null) {
            return;
        }
        if (webViewUrl.endsWith(url)) {
            log("refresh method:" + method);
            if (TextUtils.isEmpty(method)) {
                mWebView.reload();
            } else {
                loadUrl("javascript:" + method);
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bs = getArguments();
        if (bs != null) {
            initArguments(bs);
        }
    }

    protected void initArguments(Bundle bs) {
        url = bs.getString(PARAM_URL);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.layout_webview, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mWebView = (WebView) view.findViewById(R.id.webview);
        initWebView(mWebView);
        mIsWebViewAvailable = true;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        syncCookie(mWebView);
        mWebView.loadUrl(url);
        IntentFilter intent = new IntentFilter();
        intent.addAction("action_login_success");
        intent.addAction("action_web_refresh");
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, intent);
    }

    protected void syncCookie(WebView webView) {
        CookieSyncManager cs = CookieSyncManager.createInstance(getActivity());
        CookieManager cm = CookieManager.getInstance();
        setAcceptThirdPartyCookies(webView, cm);
        cm.setAcceptCookie(true);
        HttpInterface http = HttpInterface.Factory.create();
        String host = http.getHost(getActivity());
        String v = http.getCookies(host);
        log("cookies:" + v);
        cm.setCookie(host, v);
        cs.sync();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    protected void setAcceptThirdPartyCookies(WebView webView, CookieManager cm) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cm.setAcceptThirdPartyCookies(webView, true);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mWebView.onPause();
    }

    /**
     * Called when the fragment is no longer resumed. Pauses the WebView.
     */
    @Override
    public void onResume() {
        mWebView.onResume();
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        mIsWebViewAvailable = false;
        super.onDestroyView();
    }

    /**
     * Called when the fragment is no longer in use. Destroys the internal state
     * of the WebView.
     */
    @Override
    public void onDestroy() {
        if (mWebView != null) {
            mWebView.destroy();
            mWebView = null;
        }
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
        super.onDestroy();
    }

    /**
     * Gets the WebView.
     */
    public WebView getWebView() {
        return mIsWebViewAvailable ? mWebView : null;
    }

    @SuppressLint("JavascriptInterface")
    protected void initWebView(WebView webView) {
        // 防止js注入漏洞
        webView.removeJavascriptInterface("searchBoxJavaBridge_");
        webView.removeJavascriptInterface("accessibility");
        webView.removeJavascriptInterface("accessibilityTraversal");
        js = createJsInterface(webView);
        webView.addJavascriptInterface(js, "android");
        // 设置webview属性
        webView.setInitialScale(0);
        webView.setWebViewClient(new MyWebViewClient());
        webView.setWebChromeClient(new MyWebChromeClient());
        initWebSettings(webView.getSettings());
        setWebContentsDebuggingEnabled();
        webView.requestFocus();
    }

    protected JsInterface createJsInterface(WebView webView) {
        return new JsInterface(this, webView, LocalDataInterface.Factory.create().getUserId(getActivity()));
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void setWebContentsDebuggingEnabled() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(Logger.isDebug());
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    protected void initWebSettings(WebSettings settings) {
        String databasePath = getActivity().getDir("database", Context.MODE_PRIVATE).getPath();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
        settings.setSaveFormData(false);
        settings.setSavePassword(false);
        // settings.setAllowFileAccess(true);
        // settings.setAllowContentAccess(true);
        settings.setDatabaseEnabled(true);
        settings.setDatabasePath(databasePath);

        settings.setAppCacheMaxSize(5 * 1048576);
        settings.setAppCachePath(databasePath);
        settings.setAppCacheEnabled(true);

        setAllowUniversalAccessFromFileURLs(settings, true);
        setMediaPlaybackRequiresUserGesture(settings, false);
        settings.setDomStorageEnabled(true);
        settings.setGeolocationEnabled(true);
        settings.setGeolocationDatabasePath(databasePath);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void setMediaPlaybackRequiresUserGesture(WebSettings settings, boolean b) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            settings.setMediaPlaybackRequiresUserGesture(b);
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void setAllowUniversalAccessFromFileURLs(WebSettings settings, boolean b) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowUniversalAccessFromFileURLs(b);
        }
    }

    public void log(String msg) {
        Logger.d("webview", msg);
    }

    public boolean onBackPressed() {
        WebView webView = getWebView();
        if (webView == null) {
            return false;
        }
        log("onBackPressed " + webView.getUrl());
        if (webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return false;
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            log("onReceivedError url:" + failingUrl + ",errorCode:" + errorCode + ",description:" + description);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            log("onPageStarted " + url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            log("onPageFinished " + url);
            pageFinished(view, url);
        }

        @SuppressWarnings("deprecation")
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            log("shouldInterceptRequest " + url);
            return super.shouldInterceptRequest(view, url);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler,
                                       SslError error) {
            log("onReceivedSslError " + error.toString());
            handler.proceed();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            log("shouldOverrideUrlLoading " + url);
            if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mms:")
                    || url.startsWith("mmsto:")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            }
            view.loadUrl(url);
            return true;
        }
    }

    private class MyWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            log("onProgressChanged " + newProgress);
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            String msg = "CONSOLE MESSAGE: line " + consoleMessage.lineNumber() + " in " + consoleMessage.sourceId()
                    + " : " + consoleMessage.message();
            log(msg);
            return super.onConsoleMessage(consoleMessage);
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onPermissionRequest(final PermissionRequest request) {
            log("onPermissionRequest:" + Arrays.toString(request.getResources()));
            request.grant(request.getResources());
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage(message);
            builder.setPositiveButton(R.string.action_confirm, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            });
            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    result.confirm();
                }
            });
            Dialog d = builder.create();
            d.setCanceledOnTouchOutside(false);
            d.show();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage(message);
            builder.setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.cancel();
                }
            });
            builder.setPositiveButton(R.string.action_confirm, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            });
            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    result.cancel();
                }
            });
            Dialog d = builder.create();
            d.setCanceledOnTouchOutside(false);
            d.show();
            return true;
        }
    }

    protected void loadUrl(String url) {
        log("loadUrl " + url);
        mWebView.loadUrl(url);
    }


    protected void pageFinished(WebView view, String url) {
        pageFinished = true;
    }
}

Debug截图分享例子

2018-01-02_第1张图片
屏幕快照 2018-01-02 16.16.47.png

你可能感兴趣的:(2018-01-02)