WebChromeClient常用API與功能使用詳解

原文連接 WebChromeClient常用API與功能使用詳解

在WebView的開發(fā)過程中當(dāng)你需要使用到一些高級功能可以通過設(shè)置WebChromeClient從而來輔助WebView處理 JavaScript 的對話框楼镐、網(wǎng)站圖標(biāo)诲祸、網(wǎng)站title、加載進(jìn)度等

WebChromeClient常用的API方法
1.通知應(yīng)用程序當(dāng)前網(wǎng)頁加載的進(jìn)度
@Override
public void onProgressChanged(WebView view, int newProgress)
2.獲取網(wǎng)頁title標(biāo)題
@Override
public void onReceivedTitle(WebView view, String title)

獲取標(biāo)題的時間主要取決于網(wǎng)頁前段設(shè)置標(biāo)題的位置爷抓,一般設(shè)置在頁面加載前面植阴,可以較早調(diào)用到這個函數(shù)

3.網(wǎng)頁中有H5播放flash video的時候按下全屏按鈕將會調(diào)用到這個方法腰湾,一般用作設(shè)置網(wǎng)頁播放全屏操作
@Override
public void onShowCustomView(View view, CustomViewCallback callback)

對應(yīng)的取消全屏方法

@Override
public void onHideCustomView()

WebView下載監(jiān)聽

通過設(shè)置webview下載監(jiān)聽進(jìn)而監(jiān)聽網(wǎng)頁下載

mWebView.setDownloadListener(new DownloadListener() {
    @Override
    public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
    }
});

一般可在downloadStart 處進(jìn)行下載處理

WebChromeClient高級功能實現(xiàn)
1.讓你的webview支持File Input 標(biāo)簽

在Android 5.0 API 21后 借助新的 onShowFileChooser() 方法,您現(xiàn)在不但可以在 WebView 中使用輸入表單字段,而且可以啟動文件選擇器從 Android 設(shè)備中選擇圖片和文件

public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                                 WebChromeClient.FileChooserParams fileChooserParams) {
    if (mFilePathCallback != null) {
        mFilePathCallback.onReceiveValue(null);
    }
    mFilePathCallback = filePathCallback;

    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
            takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
        } catch (IOException ex) {
            // Error occurred while creating the File
            Log.e(TAG, "Unable to create Image File", ex);
        }

        // Continue only if the File was successfully created
        if (photoFile != null) {
            mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
        } else {
            takePictureIntent = null;
        }
    }

    Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
    contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
    contentSelectionIntent.setType("image/*");

    Intent[] intentArray;
    if (takePictureIntent != null) {
        intentArray = new Intent[]{takePictureIntent};
    } else {
        intentArray = new Intent[0];
    }
    Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
    chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
    chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
    startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
    return true;
}

在選擇完圖片后回調(diào)onActivityResult 獲取圖片

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
        super.onActivityResult(requestCode, resultCode, data);
        return;
    }

    Uri[] results = null;

    // Check that the response is a good one
    if (resultCode == Activity.RESULT_OK) {
        if (data == null) {
            // If there is not data, then we may have taken a photo
            if (mCameraPhotoPath != null) {
                results = new Uri[]{Uri.parse(mCameraPhotoPath)};
            }
        } else {
            String dataString = data.getDataString();
            if (dataString != null) {
                results = new Uri[]{Uri.parse(dataString)};
            }
        }
    }

    mFilePathCallback.onReceiveValue(results);
    mFilePathCallback = null;
    return;
}

2.支持全屏視頻播放

設(shè)置webview視頻未播放時默認(rèn)顯示占位圖

@Override
public Bitmap getDefaultVideoPoster() {
    if(getActivity() == null) {
        return null;
    }

    return BitmapFactory.decodeResource(getActivity().getApplicationContext().getResources(),
            R.drawable.video_poster);
}

視頻播放全屏?xí)r調(diào)用

@Override
public void onShowCustomView(View view,
                             WebChromeClient.CustomViewCallback callback) {
    // if a view already exists then immediately terminate the new one
    if (mCustomView != null) {
        onHideCustomView();
        return;
    }

    // 1. Stash the current state
    mCustomView = view;
    mOriginalSystemUiVisibility = getActivity().getWindow().getDecorView().getSystemUiVisibility();
    mOriginalOrientation = getActivity().getRequestedOrientation();

    // 2. Stash the custom view callback
    mCustomViewCallback = callback;

    // 3. Add the custom view to the view hierarchy
    FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
    decor.addView(mCustomView, new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));


    // 4. Change the state of the window
    getActivity().getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                    View.SYSTEM_UI_FLAG_FULLSCREEN |
                    View.SYSTEM_UI_FLAG_IMMERSIVE);
    getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}

視頻取消全屏?xí)r候調(diào)用

@Override
public void onHideCustomView() {
    // 1. Remove the custom view
    FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
    decor.removeView(mCustomView);
    mCustomView = null;

    // 2. Restore the state to it's original form
    getActivity().getWindow().getDecorView()
            .setSystemUiVisibility(mOriginalSystemUiVisibility);
    getActivity().setRequestedOrientation(mOriginalOrientation);

    // 3. Call the custom view callback
    mCustomViewCallback.onCustomViewHidden();
    mCustomViewCallback = null;

}

具體實例可以參照 GoogleChrome高級使用實例
[https://github.com/GoogleChrome/chromium-webview-samples]

下篇將講解WebView優(yōu)化以及在開發(fā)過程中常遇到的問題

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末暑塑,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子驾茴,更是在濱河造成了極大的恐慌盼樟,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件锈至,死亡現(xiàn)場離奇詭異晨缴,居然都是意外死亡,警方通過查閱死者的電腦和手機峡捡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門击碗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人棋返,你說我怎么就攤上這事延都。” “怎么了睛竣?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵晰房,是天一觀的道長。 經(jīng)常有香客問我射沟,道長殊者,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任验夯,我火速辦了婚禮猖吴,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘挥转。我一直安慰自己海蔽,他們只是感情好共屈,可當(dāng)我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著党窜,像睡著了一般拗引。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上幌衣,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天矾削,我揣著相機與錄音,去河邊找鬼豁护。 笑死哼凯,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的楚里。 我是一名探鬼主播断部,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼腻豌!你這毒婦竟也來了家坎?” 一聲冷哼從身側(cè)響起嘱能,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤吝梅,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后惹骂,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體苏携,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年对粪,在試婚紗的時候發(fā)現(xiàn)自己被綠了右冻。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡著拭,死狀恐怖纱扭,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情儡遮,我是刑警寧澤乳蛾,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站鄙币,受9級特大地震影響肃叶,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜十嘿,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一因惭、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧绩衷,春花似錦蹦魔、人聲如沸激率。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽柱搜。三九已至,卻和暖如春剥险,著一層夾襖步出監(jiān)牢的瞬間聪蘸,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工表制, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留健爬,地道東北人。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓么介,卻偏偏與公主長得像娜遵,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子壤短,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容