package com.damaiaolai.mall.activity.add;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.damaiaolai.mall.R;
import com.damaiaolai.mall.utils.HnUserUtil;
import com.damaiaolai.mall.utils.UploadDownloadUtils;
import com.facebook.common.time.CurrentThreadTimeClock;
import com.hn.library.base.BaseActivity;
import com.hn.library.http.UploadFileResponseModel;
import com.tencent.mm.opensdk.utils.Log;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.ycbjie.webviewlib.FileReaderView;
import com.ycbjie.webviewlib.X5WebView;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class FileShowActivity extends BaseActivity {
@BindView(R.id.web_view)
X5WebView webView;
@BindView(R.id.share)
ImageView share;
@BindView(R.id.file_show_img)
ImageView fileShowImg;
@BindView(R.id.file_show_filename)
TextView fileShowFilename;
@BindView(R.id.filereaderview)
FileReaderView filereaderview;
@Override
public int getContentViewId() {
return R.layout.activity_file_show;
}
@Override
public void onCreateNew(Bundle savedInstanceState) {
setShowTitleBar(false);
fileShowImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
final String filename = SPStaticUtils.getString("filename");
final String fileName = SPStaticUtils.getString("fileName");
fileShowFilename.setText(fileName);
Log.d("TAG",fileName+"============="+filename);
final String absolutePath = getFilesDir().getAbsolutePath();
new Thread(new Runnable() {
@Override
public void run() {
UploadDownloadUtils.getInstance().deleteFile(absolutePath);
UploadDownloadUtils.getInstance().downloadDocument(absolutePath,fileName,filename);
}
}).start();
new CountDownTimer(1000,1000){
@Override
public void onTick(long l) {
}
@Override
public void onFinish() {
List<String> localPic = UploadDownloadUtils.getLocalPic(absolutePath);
Log.d("file====",localPic.toString());
String s = localPic.get(0);
filereaderview.show(s);
}
}.start();
/* //webView.loadUrl(filename); //加载web资源
//webView.loadUrl("file:///android_asset/example.html"); //加载本地资源
//这个时候发现一个问题,启动应用后,自动的打开了系统内置的浏览器,解决这个问题需要为webview设置 WebViewClient,并重写方法:
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
//返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
return true;
}
//还可以重写其他的方法
});*/
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent textIntent = new Intent(Intent.ACTION_SEND);
textIntent.setType("text/plain");
textIntent.putExtra(Intent.EXTRA_TEXT, fileName + "\n" + filename);
startActivity(Intent.createChooser(textIntent, "分享"));
}
});
}
@Override
public void getInitData() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
ButterKnife.bind(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
filereaderview.stop();
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activity.add.FileShowActivity">
<RelativeLayout
android:layout_width="match_parent"
android:background="@color/white"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/file_show_img"
android:layout_width="22dp"
android:layout_height="22dp"
android:src="@drawable/back_k"
android:layout_marginTop="13dp"
android:layout_marginLeft="20dp"
/>
<TextView
android:id="@+id/file_show_filename"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="文件名字"
android:gravity="center"
android:textColor="@color/black"
android:textSize="17sp"
android:layout_marginTop="9dp"
android:layout_marginBottom="20dp"
/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:src="@drawable/goods_details_share"
android:id="@+id/share"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:textColor="@color/black"
android:layout_marginTop="11dp"
/>
</RelativeLayout>
<com.ycbjie.webviewlib.FileReaderView
android:id="@+id/filereaderview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.ycbjie.webviewlib.X5WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:scrollbarSize="3dp" />
</LinearLayout>
UploadDownloadUtils下载工具类如下:
package com.damaiaolai.mall.utils;
import android.annotation.SuppressLint;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.blankj.utilcode.util.LogUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.annotations.NonNull;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* Create by JiYaRuo on 2021/8/20.
* Describe:
*/
public class UploadDownloadUtils {
private static final String TAG = UploadDownloadUtils.class.getSimpleName();
private static UploadDownloadUtils mInstance;
public final static String DOCUMENT_PATH = Environment.getExternalStorageDirectory() + "/RecorderGuide/";
private OnImageLoadListener mOnImageLoadListener;
public UploadDownloadUtils() {
}
public void set0nImageLoadListener(OnImageLoadListener mOnImageLoadListener) {
this.mOnImageLoadListener = mOnImageLoadListener;
}
public interface OnImageLoadListener {
void onFileDownload(int type, float position, String filePath);
}
public static UploadDownloadUtils getInstance() {
if (mInstance == null) {
synchronized (UploadDownloadUtils.class) {
if (mInstance == null) {
mInstance = new UploadDownloadUtils();
}
}
}
return mInstance;
}
/**
* 下载文件
*
* @param path 下载路径
* @param fileName 文件命名(加后缀名)
* @param url 文件的url
*/
public void downloadDocument(final String path, final String fileName, final String url) {
new Thread(new Runnable() {
@SuppressLint("NewApi")
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request
.Builder()
.url(url)//要访问的链接
.get()
.build();
Call call = client.newCall(request);
Response execute = call.execute();
//获取下载的内容输入流
ResponseBody body = execute.body();
InputStream inputStream = body.byteStream();
final long lengh = body.contentLength();
// LogUtils.i(TAG,"downloadDocument","文件大小=="+lengh);
// 文件保存到本地
File file1 = null;
file1 = new File(path);
if (!file1.exists())
file1.mkdirs();
// LogUtils.i(TAG,"downloadDocument","文件名称=="+fileName);
File file = new File(file1, fileName);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream outputStream = new FileOutputStream(file);
int lien = 0;
int losing = 0;
byte[] bytes = new byte[1024];
while ((lien = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, lien);
losing += lien;
final float i = losing * 1.0f / lengh;
if (i == 1.0) {
LogUtils.i(TAG, "downloadDocument", "下载完成" + fileName);
//Log.d("TAG","downloadDocument 下载完成"+fileName);
} else {
// LogUtils.i(TAG,"downloadDocument","下载进度=="+i);
}
Message message = mHandler.obtainMessage();
message.obj = i;
message.what = 6;
mHandler.sendMessage(message);
}
outputStream.flush();
inputStream.close();
outputStream.close();
Message message = mHandler.obtainMessage();
message.obj = file.getAbsolutePath();
message.what = 2;
mHandler.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
mHandler.sendEmptyMessage(3);
}
}
}).start();
}
Handler mHandler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 2:
if (mOnImageLoadListener != null) {
String filePath = (String) msg.obj;
mOnImageLoadListener.onFileDownload(0, 1, filePath);
}
break;
case 3:
if (mOnImageLoadListener != null) {
mOnImageLoadListener.onFileDownload(1, 0, "");
}
break;
case 6:
if (mOnImageLoadListener != null) {
float position = (float) msg.obj;
mOnImageLoadListener.onFileDownload(3, position, "");
}
break;
}
}
};
/**
* 获取文件夹下的文件
*/
public static List<String> getLocalPic(String path) {
List<String> mList = new ArrayList<>();
File dir = new File(path);
if (dir == null || !dir.exists() || !dir.isDirectory())
return null;
for (File file : dir.listFiles()) {
if (file.isFile())
mList.add(file.getPath());
}
return mList;
}
/**
* 删除文件
*/
public void deleteFile(String path) {
File file = new File(path);
deleteDirWihtFile(file);
}
/**
* 删除文件
*
* @param dir
*/
private void deleteDirWihtFile(File dir) {
if (dir == null || !dir.exists() || !dir.isDirectory())
return;
for (File file : dir.listFiles()) {
if (file.isFile())
file.delete(); // 删除所有文件
else if (file.isDirectory())
deleteDirWihtFile(file); // 递规的方式删除文件夹
}
}
/**
* 销毁
*/
public void onDestroy() {
mOnImageLoadListener = null;
mInstance = null;
}
}
这里是用的github星比较多的一个YCwebview开源项目,这个里面集成了腾讯X5webview。切记下载操作必须在子线程,下载展示写一个延迟即可。