gpt4 book ai didi

java - 如何从 url 中提取图像并在 android 中转换为位图

转载 作者:行者123 更新时间:2023-11-29 08:43:36 24 4
gpt4 key购买 nike

<分区>

我是 Android 的新手,我想发送带有图像的通知。如果我使用可绘制文件夹中的图像意味着我可以做到。但是,我想从 url 中提取图像,然后发送给它……我尝试了一些代码,它使我的应用程序崩溃。怎么做任何人指导我!

我的代码在这里:

protected static void postNotification(Intent intentAction, Context context,String msg,String url){
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentAction, Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL);
Bitmap bitmap = new ImageDownloaderTask().doInBackground(url);
Notification notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.tapn)
.setContentTitle("Notification")
.setContentText(msg)
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmap))
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.getNotification();
mNotificationManager.notify(R.string.notification_number, notification);
}

ImageDownloaderTask.java:

public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private Exception exception;
@Override
public Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}

private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();

int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}

InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {

Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
Log.d("URLCONNECTIONERROR", e.toString());
if (urlConnection != null) {
urlConnection.disconnect();
}
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();

}
}
return null;
}

protected void onPostExecute(Bitmap feed) {
// TODO: check this.exception
// TODO: do something with the feed
}

我的日志:

D/URLCONNECTIONERROR: android.os.NetworkOnMainThreadException

W/ImageDownloader:从 https://www.google.com/intl/en_ALL/images/logo.gif 下载图像时出错

提前致谢!

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com