无论在什么情况下,按home键都要回到app的首页,其他情况都已经实现,但在Webview中全屏播放视频时,按home键回到app首页。这个问题困扰我很长时间,因为home键是系统按键,app中压根拦截不到home键的事件,所以没法处理。客户需求又不得不做,因此查看Browser++源码发现,全屏播放时在onShowCustomView()方法中传进来一个View,记录此时的view,按下home键时会回到launcher中的home属性的activity,此时当前apk的activity会走onPause()生命周期方法,在onPause()方法中调用onHideCustomView()方法就能实现home键回到launcher,然后在launcher中处理即可回到homepage。 (这对本人而言是难点,高手请绕道。)
下面看一下部分代码:
xml文件:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/frameLayout">
<WebView
android:id="@+id/webView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</FrameLayout>
activity中的处理:
private class MyChromClient extends WebChromeClient {
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {<strong> //This is used for Fullscreen video playback</strong>
super.onShowCustomView(view, callback);
if (mView != null) {
callback.onCustomViewHidden();
return;
}
mFrameLayout.removeView(mWebView);
mFrameLayout.addView(view);
mView = view; <strong><span style="color:#333333;">//用mView保存全屏播放视频的custom view</span></strong>
mCallback = callback;
}
@Override
public void onHideCustomView() { <strong>//Notify the host application that the current page would like to hide its custom view.</strong>
super.onHideCustomView();
if (mView == null) {
return;
}
mView.setVisibility(View.GONE);
mFrameLayout.removeView(mView);
mView = null;
mFrameLayout.addView(mWebView);
mCallback.onCustomViewHidden();
}
}
按home键时当前activity会走onPause()方法,所以在onPause()方法中调用onHideCustomVIew()将custom view隐藏:
@Override
protected void onPause() {
super.onPause();
if (mView != null) { <strong>//是全屏播放时调用隐藏的方法</strong>
mChromClient.onHideCustomView();
}
}