How to set bitmap as notification icon in Android

前端 未结 4 1748
囚心锁ツ
囚心锁ツ 2020-12-19 15:49

Hello I am looking for the way to set the bitmap which are not in res directory. Actually I am getting that icon from the URL and want to set it in the notifica

4条回答
  •  忘掉有多难
    2020-12-19 16:33

    I think you can't use directly the URL, but you can use the following statement, but only if you use a large icon.

    This statement converts a URL into a BitMap:

    Bitmap bitmap = getBitmapFromURL("Your URL");
    
    
    public Bitmap getBitmapFromURL(String strURL) {
        try {
            URL url = new URL(strURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    

    Now, in your notification builder you can use the following code:

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
        .setLargeIcon(bitmap)
        .setContentTitle(Util.notificationTitle)
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(notificationMessage))
        .setAutoCancel(true)
        .setDefaults(Notification.DEFAULT_SOUND)
        .setContentText(notificationMessage);
    

    Don't forget the permissions in your Manifest:

    
    

提交回复
热议问题