Android封装ImageGetter接口

Html.ImageGetter接口实现类NetworkImageGetter

public final class NetworkImageGetter implements Html.ImageGetter {

    private static final String TAG = "yezhou";

    private Context context;
    private NetworkImageAsyncLoader loader;

    public NetworkImageGetter(Context context, NetworkImageAsyncLoader loader) {
        this.context = context;
        this.loader = loader;
    }

    @Override
    public Drawable getDrawable(String source) {
        Drawable drawable = null;
        // 封装路径
        Log.i(TAG, "source: " + source);
        String imageName = source.substring(source.lastIndexOf('/') + 1);
        Log.i(TAG, "imageName: " + imageName);
        File file = new File(EnvironmentUtil.getInstance().getRootDirectory(), "/images/" + imageName);
        // 判断是否以http开头
        if (source.startsWith("http")) {
            // 判断路径是否存在
            if (file.exists()) {
                // 存在即获取drawable
                drawable = Drawable.createFromPath(file.getAbsolutePath());
                int dpWidth = drawable.getIntrinsicWidth();
                int dpHeight = drawable.getIntrinsicHeight();
                int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpWidth, context.getResources().getDisplayMetrics());
                int heigth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpHeight, context.getResources().getDisplayMetrics());
                drawable.setBounds(0, 0, width, heigth);
            } else {
                // 不存在即开启异步任务加载网络图片
                loader.execute(source, imageName);
            }
        }
        return drawable;
    }
}

网络图片资源异步下载类NetworkImageAsyncLoader

public class NetworkImageAsyncLoader extends AsyncTask<String, Integer, Void> {

    private static final String TAG = "yezhou";

    private String imageName;

    @Override
    protected Void doInBackground(String... params) {
        // 加载网络图片
        loadNetPic(params[0]);
        imageName = params[1];
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // 图片加载完成回调
        mOnNetworkImageLoader.onImageLoaded();
    }

    /**加载网络图片*/
    private void loadNetPic(String... params) {
        String urlStr = params[0];
        File file = new File(Environment.getExternalStorageDirectory(), "/images/" + imageName);
        InputStream in = null;
        FileOutputStream out = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connUrl = (HttpURLConnection) url.openConnection();
            connUrl.setConnectTimeout(5000);
            connUrl.setRequestMethod("GET");
            if (connUrl.getResponseCode() == 200) {
                in = connUrl.getInputStream();
                out = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer))!= -1) {
                    out.write(buffer, 0, len);
                }
            } else {
                Log.i(TAG, connUrl.getResponseCode() + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private OnNetworkImageLoader mOnNetworkImageLoader = null;

    public void setOnNetworkImageLoader(OnNetworkImageLoader loader) {
        mOnNetworkImageLoader = loader;
    }

    public interface OnNetworkImageLoader {
        void onImageLoaded();
    }
}

Activity调用:

public class MainActivity extends AppCompatActivity implements NetworkImageAsyncLoader.OnNetworkImageLoader {

    private NetworkImageGetter mImageGetter;
    private NetworkImageAsyncLoader mImageLoader;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();

        mImageLoader = new NetworkImageAsyncLoader();
        mImageGetter = new NetworkImageGetter(this, mImageLoader);
        mImageLoader.setOnNetworkImageLoader(this);
    }

    private void updateData() {
        mTvNewsContent.setText(Html.fromHtml(mNews.getContent(), mImageGetter, null));
    }

    @Override
    public void onImageLoaded() {
        // 当执行完成后再次为其设置一次
        mTvNewsContent.setText(Html.fromHtml(mNews.getContent(), mImageGetter, null));
    }

}

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/02/18/android-integrate-imagegetter/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Android封装ImageGetter接口
Html.ImageGetter接口实现类NetworkImageGetter: public final class NetworkImageGetter implements Html.ImageGetter { private static final String……
<<上一篇
下一篇>>
文章目录
关闭
目 录