Load image from url in notification Android

前端 未结 8 830
北海茫月
北海茫月 2020-11-28 21:48

In my android application, i want to set Notification icons dynamically which will be loaded from URL. For that, i have used setLargeIcon property of Notificati

8条回答
  •  情书的邮戳
    2020-11-28 22:28

    Changed my code as below and its working now :

    private class sendNotification extends AsyncTask {
    
            Context ctx;
            String message;
    
            public sendNotification(Context context) {
                super();
                this.ctx = context;
            }
    
            @Override
            protected Bitmap doInBackground(String... params) {
    
                InputStream in;
                message = params[0] + params[1];
                try {
    
                      URL url = new URL(params[2]);
                      HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                      connection.setDoInput(true);
                      connection.connect();
                      in = connection.getInputStream();
                      Bitmap myBitmap = BitmapFactory.decodeStream(in);
                      return myBitmap;
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
    
            @Override
            protected void onPostExecute(Bitmap result) {
    
                super.onPostExecute(result);
                try {
                    NotificationManager notificationManager = (NotificationManager) ctx
                            .getSystemService(Context.NOTIFICATION_SERVICE);
    
                    Intent intent = new Intent(ctx, NotificationsActivity.class);
                    intent.putExtra("isFromBadge", false);
    
    
                    Notification notification = new Notification.Builder(ctx)
                            .setContentTitle(
                                    ctx.getResources().getString(R.string.app_name))
                            .setContentText(message)
                            .setSmallIcon(R.drawable.ic_launcher)
                            .setLargeIcon(result).build();
    
                    // hide the notification after its selected
                    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    
                    notificationManager.notify(1, notification);
    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    

提交回复
热议问题