AgentWeb使用

项目地址:https://github.com/Justson/AgentWeb

AgentWeb 介绍

AgentWeb 是一个基于的 Android WebView ,极度容易使用以及功能强大的库,提供了 Android WebView 一系列的问题解决方案 ,并且轻量和极度灵活。

引入

  • Gradle

     compile 'com.just.agentweb:agentweb:4.0.2' // (必选)
     compile 'com.just.agentweb:download:4.0.2' // (可选)
     compile 'com.just.agentweb:filechooser:4.0.2'// (可选) 
    
  • Maven

     <dependency>
       <groupId>com.just.agentweb</groupId>
       <artifactId>agentweb</artifactId>
       <version>4.0.2</version>
       <type>pom</type>
     </dependency>
     
    

使用

基础用法

mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent((LinearLayout) view, new LinearLayout.LayoutParams(-1, -1))                
                .useDefaultIndicator()
                .createAgentWeb()
                .ready()
                .go("http://www.jd.com");

 

  • 调用 Javascript 方法拼接太麻烦 ? 请看 。

function callByAndroid(){
      console.log("callByAndroid")
  }
mAgentWeb.getJsAccessEntrace().quickCallJs("callByAndroid");
  • Javascript 调 Java ?

mAgentWeb.getJsInterfaceHolder().addJavaObject("android",new AndroidInterface(mAgentWeb,this));
window.android.callAndroid();
  • 事件处理

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
  • 跟随 Activity Or Fragment 生命周期 , 释放 CPU 更省电 。

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause(); 
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }
    @Override
    public void onDestroyView() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroyView();
    }    
  • 全屏视频播放

<!--如果你的应用需要用到视频 , 那么请你在使用 AgentWeb 的 Activity 对应的清单文件里加入如下配置-->
android:hardwareAccelerated="true"
android:configChanges="orientation|screenSize"
  • 定位

<!--AgentWeb 是默认允许定位的 ,如果你需要该功能 , 请在你的 AndroidManifest 文件里面加入如下权限 。-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  • WebChromeClient 与 WebViewClient

AgentWeb.with(this)
                .setAgentWebParent(mLinearLayout,new LinearLayout.LayoutParams(-1,-1) )
                .useDefaultIndicator()
                .setReceivedTitleCallback(mCallback)
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setSecutityType(AgentWeb.SecurityType.strict)
                .createAgentWeb()
                .ready()
                .go(getUrl());
private WebViewClient mWebViewClient=new WebViewClient(){
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
           //do you  work
        }
    };
private WebChromeClient mWebChromeClient=new WebChromeClient(){
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //do you work
        }
    };                
  • 返回上一页

if (!mAgentWeb.back()){
       AgentWebFragment.this.getActivity().finish();
}
  • 获取 WebView

	mAgentWeb.getWebCreator().getWebView();
  • 文件下载监听

protected DownloadListenerAdapter mDownloadListenerAdapter = new DownloadListenerAdapter() {


		@Override
		public boolean onStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength, AgentWebDownloader.Extra extra) {
			extra.setOpenBreakPointDownload(true)
					.setIcon(R.drawable.ic_file_download_black_24dp)
					.setConnectTimeOut(6000)
					.setBlockMaxTime(2000)
					.setDownloadTimeOut(60L * 5L * 1000L)
					.setAutoOpen(true)
					.setForceDownload(false);
			return false;
		}


		@Override
		public void onBindService(String url, DownloadingService downloadingService) {
			super.onBindService(url, downloadingService);
			mDownloadingService = downloadingService;
			LogUtils.i(TAG, "onBindService:" + url + "  DownloadingService:" + downloadingService);
		}


		@Override
		public void onUnbindService(String url, DownloadingService downloadingService) {
			super.onUnbindService(url, downloadingService);
			mDownloadingService = null;
			LogUtils.i(TAG, "onUnbindService:" + url);
		}


		@Override
		public void onProgress(String url, long loaded, long length, long usedTime) {
			int mProgress = (int) ((loaded) / Float.valueOf(length) * 100);
			LogUtils.i(TAG, "onProgress:" + mProgress);
			super.onProgress(url, loaded, length, usedTime);
		}


		@Override
		public boolean onResult(String path, String url, Throwable throwable) {
			if (null == throwable) { 
				//do you work
			} else {

			}
			return false; 
		}
	};
  • 查看 Cookies

String cookies=AgentWebConfig.getCookiesByUrl(targetUrl);
  • 同步 Cookie

AgentWebConfig.syncCookie("http://www.jd.com","ID=XXXX");
  • MiddlewareWebChromeBase 支持多个 WebChromeClient

//略,请查看 Sample
  • MiddlewareWebClientBase 支持多个 WebViewClient

//略,请查看 Sample
  • 清空缓存

AgentWebConfig.clearDiskCache(this.getContext());
  • 权限拦截

protected PermissionInterceptor mPermissionInterceptor = new PermissionInterceptor() {

        @Override
        public boolean intercept(String url, String[] permissions, String action) {
            Log.i(TAG, "url:" + url + "  permission:" + permissions + " action:" + action);
            return false;
        }
    };
  • AgentWeb 完整用法

        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent((LinearLayout) view, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
                .useDefaultIndicator(-1, 3)
                .setAgentWebWebSettings(getSettings())
                .setWebViewClient(mWebViewClient)
                .setWebChromeClient(mWebChromeClient)
                .setPermissionInterceptor(mPermissionInterceptor) 
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) 
                .setAgentWebUIController(new UIController(getActivity())) 
                .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
                .useMiddlewareWebChrome(getMiddlewareWebChrome())
                .useMiddlewareWebClient(getMiddlewareWebClient()) 
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.DISALLOW)
                .interceptUnkownUrl() 
                .createAgentWeb()
                .ready()
                .go(getUrl()); 
  • AgentWeb 所需要的权限(在你工程中根据需求选择加入权限)

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
    <uses-permission android:name="android.permission.CAMERA"></uses-permission>
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"></uses-permission>
  • AgentWeb 所依赖的库

    compile "com.android.support:design:${SUPPORT_LIB_VERSION}" // (3.0.0开始该库可选)
    compile "com.android.support:support-v4:${SUPPORT_LIB_VERSION}"
    SUPPORT_LIB_VERSION=27.0.2(该值会更新)

混淆

如果你的项目需要加入混淆 , 请加入如下配置

-keep class com.just.agentweb.** {
    *;
}
-dontwarn com.just.agentweb.**

Java 注入类不要混淆 , 例如 sample 里面的 AndroidInterface 类 , 需要 Keep 。

-keepclassmembers class com.just.agentweb.sample.common.AndroidInterface{ *; }

 

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
AgentWeb 是一个基于 Android WebView 的框架,可以方便地进行网页浏览和文件下载。要实现文件下载,可以使用 AgentWeb 内置的下载管理器。 首先,在布局文件中添加一个 AgentWebWebView: ``` <com.just.agentweb.AgentWeb android:id="@+id/agentWeb" android:layout_width="match_parent" android:layout_height="match_parent" /> ``` 然后,在 Activity 中初始化 AgentWeb: ``` AgentWeb agentWeb = AgentWeb.with(this) .setAgentWebParent(layout, new LinearLayout.LayoutParams(-1, -1)) .useDefaultIndicator() .setWebViewClient(new WebViewClient()) .setWebChromeClient(new WebChromeClient()) .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) .createAgentWeb() .ready() .go(url); ``` 其中,`url` 是要访问的网页地址,`layout` 是 WebView 的父布局。 接着,在 WebView 的 WebViewClient 中监听下载事件: ``` agentWeb.getWebCreator().getWebView().setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { // 创建下载任务 DownloadTask downloadTask = new DownloadTask(MainActivity.this); downloadTask.execute(url); } }); ``` 在创建下载任务时,可以使用 Android 自带的 DownloadManager 或者自己实现下载功能。这里使用 AsyncTask 来实现下载任务: ``` private static class DownloadTask extends AsyncTask<String, Integer, String> { private WeakReference<Context> contextReference; DownloadTask(Context context) { contextReference = new WeakReference<>(context); } @Override protected String doInBackground(String... params) { String url = params[0]; try { URL downloadUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(); connection.setConnectTimeout(5000); connection.setRequestMethod("GET"); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { String fileName = getFileName(connection); File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName); FileOutputStream outputStream = new FileOutputStream(file); InputStream inputStream = connection.getInputStream(); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } inputStream.close(); outputStream.close(); return file.getAbsolutePath(); } } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { if (s != null) { Toast.makeText(contextReference.get(), "文件已保存到:" + s, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(contextReference.get(), "下载失败", Toast.LENGTH_SHORT).show(); } } private String getFileName(HttpURLConnection connection) { String contentDisposition = connection.getHeaderField("Content-Disposition"); if (contentDisposition != null && contentDisposition.contains("filename=")) { return contentDisposition.substring(contentDisposition.indexOf("filename=") + 9); } else { return "download"; } } } ``` 这里使用 HttpURLConnection 来下载文件,并将文件保存到 Android 的下载目录下。下载完成后,可以通过 Toast 提示用户文件保存的路径。 需要注意的是,Android 6.0 及以上版本需要动态申请写入存储的权限。可以使用以下代码来申请权限: ``` if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } ``` 在 onRequestPermissionsResult 回调中判断是否授权成功: ``` @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == 1) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // 权限已授予,可以进行文件下载操作 } else { Toast.makeText(this, "请授权存储权限", Toast.LENGTH_SHORT).show(); } } } ``` 以上就是使用 AgentWeb 实现文件下载的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值