转载请注明出处:王亟亟的大牛之路
强行安利下自己的收纳库(日更):https://github.com/ddwhan0123/Useful-Open-Source-Android
昨天写了个CardView的貌似,不太受欢迎,今天上午没啥大事就继续翻源码,这一篇讲的是WebView的授权实现(WebView这个坑大家怨声载道,现在看看官方是如何操作的吧)
先看下运行效果
OK,来看看包结构
比平时的那些sample东西稍微多点 其实主要业务就在 PermissionRequestFragment和ConfirmationDialogFragment里
我们一个个看(主要看授权行为)
MainActivity初始化一些UI 然后把 Log部分和WebView部分以及bar逻辑的一些相关内容做了处理,不涉及授权操作(主要做呈现)
他继承于SampleActivityBase,也是做一些初始化Log的行为,这里不做解释
接下来是授权行为操作的PermissionRequestFragment(重要步骤已经注释)
/**
* This fragment shows a {@link WebView} and loads a web app from the {@link SimpleWebServer}.
*/
public class PermissionRequestFragment extends Fragment
implements ConfirmationDialogFragment.Listener {
private static final String TAG = PermissionRequestFragment.class.getSimpleName();
private static final String FRAGMENT_DIALOG = "dialog";
/**
* We use this web server to serve HTML files in the assets folder. This is because we cannot
* use the JavaScript method "getUserMedia" from "file:///android_assets/..." URLs.
* 异步对WebView的操作
*/
private SimpleWebServer mWebServer;
/**
* A reference to the {@link WebView}.
* 嵌入的ViewView
*/
private WebView mWebView;
/**
* This field stores the {@link PermissionRequest} from the web application until it is allowed
* or denied by user.
* 授权行为
*/
private PermissionRequest mPermissionRequest;
/**
* For testing.
* 控制台行为
*/
private ConsoleMonitor mConsoleMonitor;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
//布局处理
return inflater.inflate(R.layout.fragment_permission_request, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
//初始化WebView相关操作
mWebView = (WebView) view.findViewById(R.id.web_view);
// Here, we use #mWebChromeClient with implementatio