目录
- 效果
- activity_main.xml
- MainActivity
- ImageItem
- ImageAdapter
效果
项目本来是要做成图片保存到手机然后读取数据后瀑布流展示,但是有问题,目前只能做到保存到手机
activity_main.xml
<?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"
tools:context=".MainActivity"
android:orientation="horizontal">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="生成瀑布流"
tools:ignore="MissingConstraints" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MainActivity
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private static final String TAG = "MainActivity";
private static final int PERMISSION_REQUEST_CODE = 1;
private Button mButton;
private List<ImageItem> mImageList;
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = findViewById(R.id.button);
mImageList = new ArrayList<>();
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new ImageAdapter(mImageList, this);
mRecyclerView.setAdapter(mAdapter);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_CODE);
} else {
// 开始解析HTML并下载图片
startParsingAndDownloading();
imageView = findViewById(R.id.image_view);
Log.e(TAG,"开始解析HTML并下载图片");
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 写入外部存储权限已授予,解析HTML并下载图片
new ParseHtmlTask().execute("https://example.com"); // 替换为你要解析的HTML网页URL
} else {
// 用户拒绝了权限请求,可以根据需要进行处理
}
}
}
//开始解析HTML
private void startParsingAndDownloading() {
new ParseHtmlTask().execute("https://home.meishichina.com/show-top-type-recipe.html");
}
private class ParseHtmlTask extends AsyncTask<String, Void, List<ImageItem>> {
@Override
protected List<ImageItem> doInBackground(String... urls) {
String url = urls[0];
Document document = null;
try {
document = Jsoup.connect(url).get();
Elements imgElements = document.select("div.pic");
for (Element element : imgElements) {
String imgUrl = element.select("a").select("img").attr("data-src");
mImageList.add(new ImageItem(imgUrl));
downloadImage(imgUrl);
}
} catch (IOException e) {
Log.e(TAG,"111");
//throw new RuntimeException(e);
}
return mImageList;
}
@Override
protected void onPostExecute(List<ImageItem> imageList) {
mAdapter.notifyDataSetChanged();
}
private void downloadImage(String imgUrl) {
Glide.with(MainActivity.this)
.downloadOnly()
.load(imgUrl)
.into(new CustomTarget<File>() {
@Override
public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
// 下载完成后的处理逻辑,可根据需求进行保存或其他操作
// 这里将图片文件保存到手机的公共图片目录下
String fileName = "image_" + System.currentTimeMillis() + ".jpg";
File destFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);
try {
copyFile(resource, destFile);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
// 可选的清除逻辑
}
});
}
private void copyFile(File sourceFile, File destFile) throws IOException {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(sourceFile);
outputStream = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
ImageItem
public class ImageItem {
private String imageUrl;
public ImageItem(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getImageUrl() {
return imageUrl;
}
}
ImageAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.List;
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
private List<ImageItem> imageList;
private Context context;
public ImageAdapter(List<ImageItem> imageList, Context context) {
this.imageList = imageList;
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_image, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
ImageItem item = imageList.get(position);
String imageUrl = item.getImageUrl();
// 使用Glide加载图片
Glide.with(context)
.load(imageUrl)
.into(holder.imageView);
}
@Override
public int getItemCount() {
return imageList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image_view);
}
}
}