安卓H5交互——讓界面不再單一

大家先先簡單的瞭解下 HTML5

HTML5是萬維網的核心語言、標準通用標記語言下的一個應用超文本標記語言HTML)的第五次重大修改

      HTML5的設計目的是爲了在移動設備上支持多媒體。

優勢HTML5可以提供:

1.提高可用性和改進用戶的友好體驗;
2.有幾個新的標籤,這將有助開發人員定義重要的內容;
3.可以給站點帶來更多的多媒體元素(視頻和音頻);
4.可以很好的替代FLASH和Silverlight;
5.當涉及到網站的抓取和索引的時候,對於SEO很友好;
6.將被大量應用於移動應用程序和遊戲。
接下來說下我們安卓開發中h5交互過程,並附上一個h5可複用的幫助類
首先,我們在xml佈局中聲明一個webview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clipToPadding="true"
    android:fitsSystemWindows="true"
    android:orientation="vertical">
    <TextView
        android:text="加載失敗請點擊重試!"
        android:gravity="center"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:visibility="gone"
        android:id="@+id/tv_load_error" />
    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">


    </WebView>
</RelativeLayout>

在實現過程中我們直接給webview設置一個url鏈接,就可以正常展示了
mWebView.loadUrl(url);

這裏分享下我們項目中的一個幫助類
public class H5LoadActivity extends BaseActivity {

    private WebView mWebView;
    private TextView tv_load_error;
    private String url = "";
    public static H5LoadActivity instance = null;
    private static final String TAG = H5LoadActivity.class.getSimpleName();
    private static final String APP_CACAHE_DIRNAME = "/webcache";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_h5_load);
        initView();
    }

    protected void initView() {
        instance = this;
        tv_load_error = (TextView) findViewById(R.id.tv_load_error);
        mWebView = (WebView) findViewById(R.id.webview);
        WebSettings mWebSettings = mWebView.getSettings();
        mWebSettings.setDomStorageEnabled(true);//持久化本地存儲  讓前端自己做頁面緩存 否則他們拿不到storage裏的數據會報錯
        mWebSettings.setJavaScriptEnabled(true);
        url = getIntent().getExtras().getString("url");
        LLog.e("url  ==  " + url);
        mWebView.loadUrl(url);
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //  重寫此方法表明點擊網頁裏面的鏈接還是在當前的webview裏跳轉,不跳到瀏覽器那邊
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                tv_load_error.setVisibility(View.VISIBLE);
                view.setVisibility(View.GONE);
            }
        });
        mWebView.addJavascriptInterface(new JsAndroidImpl() {//增加接口方法,讓html頁面調用

            @JavascriptInterface //別漏了這個註解
            public void finish() {
                H5LoadActivity.this.finish();
            }

            @JavascriptInterface //別漏了這個註解
            public void getShopsInfo(String shopInfo) {
                LLog.e("--------------" + shopInfo);
                Intent intent = new Intent(H5LoadActivity.this, ConfirmationActivity.class);
                intent.putExtra("shopInfo", shopInfo);
                intent.putExtra("TYPE", 3);
                startActivity(intent);
            }
        }, "android");
        tv_load_error.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mWebView.loadUrl(url);
            }
        });
        mWebView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (!v.hasFocus()) {
                            v.requestFocus();
                        }
                        break;
                }
                return false;
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearWebViewCache();
    }

    @Override
    //設置回退
    //覆蓋Activity類的onKeyDown(int keyCoder,KeyEvent event)方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack(); //goBack()表示返回WebView的上一頁面
            return true;
        }
        finish();//結束退出程序
        return false;
    }

    /**
     * 清除WebView緩存
     */
    public void clearWebViewCache() {

        //清理Webview緩存數據庫
        try {
            deleteDatabase("webview.db");
            deleteDatabase("webviewCache.db");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //WebView 緩存文件
        File appCacheDir = new File(getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME);
        Log.e(TAG, "appCacheDir path=" + appCacheDir.getAbsolutePath());

        File webviewCacheDir = new File(getCacheDir().getAbsolutePath() + "/webviewCache");
        Log.e(TAG, "webviewCacheDir path=" + webviewCacheDir.getAbsolutePath());

        //刪除webview 緩存目錄
        if (webviewCacheDir.exists()) {
            deleteFile(webviewCacheDir);
        }
        //刪除webview 緩存 緩存目錄
        if (appCacheDir.exists()) {
            deleteFile(appCacheDir);
        }
    }

    /**
     * 遞歸刪除 文件/文件夾
     *
     * @param file
     */
    public void deleteFile(File file) {

        Log.i(TAG, "delete file path=" + file.getAbsolutePath());

        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            Log.e(TAG, "delete file no exists " + file.getAbsolutePath());
        }
    }

}

當我們想跳轉到h5界面時:
 Bundle bundle = new Bundle();
                bundle.putString("url", "http://118.186.18.36:6867/shangcheng/Examination_Analysis.html");
                startIntent(H5LoadActivity.class, bundle);
public void startIntent(Class aClass, Bundle bundle) {
        Intent intent = new Intent(context, aClass);
        if (null != bundle)
            intent.putExtras(bundle);
        startActivity(intent);
    }





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章