編輯:關於 Android 程式設計
前言:在 Android HTML5 開發中,不少人遇到過 audio 標籤的 autoplay 在某些裝置上失效的問題。網上的做法大多是在 JS 中於特定時刻呼叫 audio 的 play() 方法,但在 Android 上依然無效。
Android 4.2 加入了一個「允許使用者手勢觸發音視頻播放」的介面,該介面預設為 true,也就是預設不允許自動播放音視頻,只能透過使用者互動、由使用者自行觸發播放。
WebView webView = this.finishActivity(R.id.main_act_webview); // ... ... // 其他配置 // ... ... // 設置4.2以後版本支持autoPlay,非用戶手勢促發 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { webView.getSettings().setMediaPlaybackRequiresUserGesture(false); }
透過以上設定,就能載入帶有自動播放的音視頻了!
下面我們沿著這個問題來窺探 WebView 的系統源碼:
1、透過 getSettings() 取得的 WebView 設定
/** * Gets the WebSettings object used to control the settings for this * WebView. * * @return a WebSettings object that can be used to control this WebView's * settings */ public WebSettings getSettings() { checkThread(); return mProvider.getSettings(); }
這裡透過一個 mProvider 來取得設定資訊。查看 WebView 源碼可以看到,WebView 的所有操作都交給 mProvider 進行。
2、mProvider 是在哪初始化的?
/** * @hide */ @SuppressWarnings("deprecation") // for super() call into deprecated base class constructor. protected WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes, Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) { super(context, attrs, defStyleAttr, defStyleRes); if (context == null) { throw new IllegalArgumentException("Invalid context argument"); } sEnforceThreadChecking = context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN_MR2; checkThread(); ensureProviderCreated(); mProvider.init(javaScriptInterfaces, privateBrowsing); // Post condition of creating a webview is the CookieSyncManager.getInstance() is allowed. CookieSyncManager.setGetInstanceIsAllowed(); }
可以看到有個 ensureProviderCreated() 方法,就是在這裡建立 mProvider:
private void ensureProviderCreated() { checkThread(); if (mProvider == null) { // As this can get called during the base class constructor chain, pass the minimum // number of dependencies here; the rest are deferred to init(). mProvider = getFactory().createWebView(this, new PrivateAccess()); } }
至此可以知道,mProvider 是在 WebView 的建構子中建立的,而且 WebView 的所有操作都交給 mProvider 進行。
3、這個 mProvider 究竟是誰派來的?
看看 WebViewFactory#getFactory() 做了什麼:
static WebViewFactoryProvider getProvider() { synchronized (sProviderLock) { // For now the main purpose of this function (and the factory abstraction) is to keep // us honest and minimize usage of WebView internals when binding the proxy. if (sProviderInstance != null) return sProviderInstance; final int uid = android.os.Process.myUid(); if (uid == android.os.Process.ROOT_UID || uid == android.os.Process.SYSTEM_UID) { throw new UnsupportedOperationException( "For security reasons, WebView is not allowed in privileged processes"); } Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.getProvider()"); try { Class<WebViewFactoryProvider> providerClass = getProviderClass(); StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "providerClass.newInstance()"); try { sProviderInstance = providerClass.getConstructor(WebViewDelegate.class) .newInstance(new WebViewDelegate()); if (DEBUG) Log.v(LOGTAG, "Loaded provider: " + sProviderInstance); return sProviderInstance; } catch (Exception e) { Log.e(LOGTAG, "error instantiating provider", e); throw new AndroidRuntimeException(e); } finally { Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW); StrictMode.setThreadPolicy(oldPolicy); } } finally { Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW); } } }
可見第 23 行回傳了 sProviderInstance,它是由 providerClass 透過反射建立的;第 15 行透過 getProviderClass() 取得 providerClass。
private static Class<WebViewFactoryProvider> getProviderClass() { try { // First fetch the package info so we can log the webview package version. sPackageInfo = fetchPackageInfo(); Log.i(LOGTAG, "Loading " + sPackageInfo.packageName + " version " + sPackageInfo.versionName + " (code " + sPackageInfo.versionCode + ")"); Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.loadNativeLibrary()"); loadNativeLibrary(); Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW); Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.getChromiumProviderClass()"); try { return getChromiumProviderClass(); } catch (ClassNotFoundException e) { Log.e(LOGTAG, "error loading provider", e); throw new AndroidRuntimeException(e); } finally { Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW); } } catch (MissingWebViewPackageException e) { // If the package doesn't exist, then try loading the null WebView instead. // If that succeeds, then this is a device without WebView support; if it fails then // swallow the failure, complain that the real WebView is missing and rethrow the // original exception. try { return (Class<WebViewFactoryProvider>) Class.forName(NULL_WEBVIEW_FACTORY); } catch (ClassNotFoundException e2) { // Ignore. } Log.e(LOGTAG, "Chromium WebView package does not exist", e); throw new AndroidRuntimeException(e); } }
主要在第 14 行回傳了一個 getChromiumProviderClass(),是不是有點熟悉?沒錯,Android 從 4.4 開始就使用強大的 Chromium 替換掉了原來的 WebKit。來看看這個 getChromiumProviderClass()。
// throws MissingWebViewPackageException private static Class<WebViewFactoryProvider> getChromiumProviderClass() throws ClassNotFoundException { Application initialApplication = AppGlobals.getInitialApplication(); try { // Construct a package context to load the Java code into the current app. Context webViewContext = initialApplication.createPackageContext( sPackageInfo.packageName, Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY); initialApplication.getAssets().addAssetPath( webViewContext.getApplicationInfo().sourceDir); ClassLoader clazzLoader = webViewContext.getClassLoader(); Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "Class.forName()"); try { return (Class<WebViewFactoryProvider>) Class.forName(CHROMIUM_WEBVIEW_FACTORY, true, clazzLoader); } finally { Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW); } } catch (PackageManager.NameNotFoundException e) { throw new MissingWebViewPackageException(e); } }
最後找到了 CHROMIUM_WEBVIEW_FACTORY,可以看到它在 WebViewFactory 中的定義:
private static final String CHROMIUM_WEBVIEW_FACTORY = "com.android.webview.chromium.WebViewChromiumFactoryProvider";
回到第 2 小節 mProvider 的初始化,其實是在 WebViewChromiumFactoryProvider 的 createWebView(…) 中進行的:
@Override public WebViewProvider createWebView(WebView webView, WebView.PrivateAccess privateAccess) { WebViewChromium wvc = new WebViewChromium(this, webView, privateAccess); synchronized (mLock) { if (mWebViewsToStart != null) { mWebViewsToStart.add(new WeakReference<WebViewChromium>(wvc)); } } ResourceProvider.registerResources(webView.getContext()); return wvc; }
至此才真正找到 mProvider 的初始化位置,它其實就是一個 WebViewChromium。別忘了我們費這麼大勁找 mProvider,其實是為了分析 webView.getSettings(),這樣就回到了第一小節。
4、Settings 的初始化
透過第一小節我們知道 Settings 是 mProvider 的一個變數,要找到它就得回到 WebViewChromium:
@Override public WebSettings getSettings() { return mWebSettings; }
接下來就是 Settings 初始化的地方:
@Override // BUG=6790250 |javaScriptInterfaces| was only ever used by the obsolete DumpRenderTree // so is ignored. TODO: remove it from WebViewProvider. public void init(final Map<String, Object> javaScriptInterfaces, final boolean privateBrowsing) { if (privateBrowsing) { mFactory.startYourEngines(true); final String msg = "Private browsing is not supported in WebView."; if (mAppTargetSdkVersion >= Build.VERSION_CODES.KITKAT) { throw new IllegalArgumentException(msg); } else { Log.w(TAG, msg); TextView warningLabel = new TextView(mWebView.getContext()); warningLabel.setText(mWebView.getContext().getString( com.android.internal.R.string.webviewchromium_private_browsing_warning)); mWebView.addView(warningLabel); } } // We will defer real initialization until we know which thread to do it on, unless: // - we are on the main thread already (common case), // - the app is targeting >= JB MR2, in which case checkThread enforces that all usage // comes from a single thread. (Note in JB MR2 this exception was in WebView.java). if (mAppTargetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN_MR2) { mFactory.startYourEngines(false); checkThread(); } else if (!mFactory.hasStarted()) { if (Looper.myLooper() == Looper.getMainLooper()) { mFactory.startYourEngines(true); } } final boolean isAccessFromFileURLsGrantedByDefault = mAppTargetSdkVersion < Build.VERSION_CODES.JELLY_BEAN; final boolean areLegacyQuirksEnabled = mAppTargetSdkVersion < Build.VERSION_CODES.KITKAT; mContentsClientAdapter = new WebViewContentsClientAdapter(mWebView); mWebSettings = new ContentSettingsAdapter(new AwSettings( mWebView.getContext(), isAccessFromFileURLsGrantedByDefault, areLegacyQuirksEnabled)); mRunQueue.addTask(new Runnable() { @Override public void run() { initForReal(); if (privateBrowsing) { // Intentionally irreversibly disable the webview instance, so that private // user data cannot leak through misuse of a non-privateBrowing WebView // instance. Can't just null out mAwContents as we never null-check it // before use. destroy(); } } }); }
在第 39 行進行了 mWebSettings 的初始化,原來是 ContentSettingsAdapter。
5、setMediaPlaybackRequiresUserGesture() 分析
經過以上對 Google 工程師的膜拜,我們找到了 mWebSettings,下面來看 setMediaPlaybackRequiresUserGesture 方法:
@Override public void setMediaPlaybackRequiresUserGesture(boolean require) { mAwSettings.setMediaPlaybackRequiresUserGesture(require); }
好吧,又是呼叫 mAwSettings 的 setMediaPlaybackRequiresUserGesture 方法,那 mAwSettings 是什麼呢?
public ContentSettingsAdapter(AwSettings awSettings) { mAwSettings = awSettings; }
原來是在建構子中注入的,回到第 4 小節最後,這裡 new 了一個 AwSettings。
mWebSettings = new ContentSettingsAdapter(new AwSettings( mWebView.getContext(), isAccessFromFileURLsGrantedByDefault, areLegacyQuirksEnabled));
那麼就來 AwSettings 中看看 setMediaPlaybackRequiresUserGesture 吧。該類位於系統源碼 external/chromium_org/android_webview/java/src/org/chromium/android_webview/AwSettings.java:
/** * See {@link android.webkit.WebSettings#setMediaPlaybackRequiresUserGesture}. */ public void setMediaPlaybackRequiresUserGesture(boolean require) { synchronized (mAwSettingsLock) { if (mMediaPlaybackRequiresUserGesture != require) { mMediaPlaybackRequiresUserGesture = require; mEventHandler.updateWebkitPreferencesLocked(); } } }
可以看到這裡只是給變數 mMediaPlaybackRequiresUserGesture 設定了值,接著看到下面這個方法,豁然開朗:
@CalledByNative private boolean getMediaPlaybackRequiresUserGestureLocked() { return mMediaPlaybackRequiresUserGesture; }
該方法由 JNI 層呼叫,在 external/chromium_org/android_webview/native/aw_settings.cc 中我們看到了:
web_prefs->user_gesture_required_for_media_playback = Java_AwSettings_getMediaPlaybackRequiresUserGestureLocked(env, obj);
可見在內核中會呼叫該介面,判斷是否允許音視頻的自動播放。
以上就是關於 Android HTML5 audio autoplay 無效問題的解決方案,希望對你有所幫助。
Android UI 布局技巧:重複背景與 layer-list 圖片組合
在 Android UI 開發中,除了常規的布局標籤,Drawable 資源還有許多實用技巧。本文介紹兩個常見場景:設定重複平鋪背景,以及用 layer-list 組合多
Android 模擬美團風格進度提示框
實作概念 美團風格的等待提示框通常以動畫呈現。這裡可透過兩張圖片輪流切換,模擬人物奔跑或等待中的動畫效果。 建立動畫資源 <animation-list xml
Android 音樂播放器實作:已存在歌曲的歌詞下載與顯示
在本機音樂播放器開發中,歌詞顯示是提升使用體驗的重要功能之一。當歌曲已經存在於裝置中時,若能自動下載並載入對應歌詞,就能讓播放介面更完整。本文將說明如何在 Android
仿微信聊天界面:ListView 多種 item 布局的實現
IM 類應用的聊天畫面,通常是左右分開的氣泡形式;而我們平時寫的 ListView 往往只有一種布局。其實 BaseAdapter 裡有兩個方法在多數情況下被忽略了: