static final Map<String, WeakReference<Drawable>> mDrawableCache = Collections.synchronizedMap(new WeakHashMap<String, WeakReference<Drawable>>()); @Override public void onCreate(Bundle savedInstanceState) { //... // ImageGetter Html.ImageGetter igLoader = new Html.ImageGetter() { public Drawable getDrawable(String source) { // , if (mDrawableCache.containsKey(source)) return mDrawableCache.get(source).get(); // , new ImageDownloadAsyncTask(source, message, messageView).execute(); // return new BitmapDrawable(getResources()); } }; // messageView.setText(Html.fromHtml(message, igLoader, null)); } // ImageGetter. // , Html.ImageGetter igCached = new Html.ImageGetter() { public Drawable getDrawable(String source) { // if (mDrawableCache.containsKey(source)) return mDrawableCache.get(source).get(); return null; } };
class ImageDownloadAsyncTask extends AsyncTask<Void, Void, Void> { private String source; private String message; private TextView textView; public ImageDownloadAsyncTask(String source, String message, TextView textView) { this.source = source; this.message = message; this.textView = textView; } @Override protected Void doInBackground(Void... params) { if (!mDrawableCache.containsKey(source)) { try { // URL url = new URL(source); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); Drawable drawable = Drawable.createFromStream(is, "src"); // , , // // . /* Bitmap bmp = BitmapFactory.decodeStream(is); DisplayMetrics dm = MainActivity.this.getResources().getDisplayMetrics(); bmp.setDensity(dm.densityDpi); Drawable drawable=new BitmapDrawable(MainActivity.this.getResources(),bmp); */ is.close(); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); mDrawableCache.put(source, new WeakReference<Drawable>( drawable)); } catch (MalformedURLException e) { e.printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } } return null; } @Override protected void onPostExecute(Void result) { // textView.setText(Html.fromHtml(message, igCached, null)); } }
android.permission.INTERNET
.Source: https://habr.com/ru/post/155879/
All Articles