How to set bitmap as notification icon in Android

前端 未结 4 1733
囚心锁ツ
囚心锁ツ 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:26

    Already answered here: https://stackoverflow.com/a/16055373/1071594

    Summary: It's not possible to set a custom small icon, but from API level 11 you can use setLargeIcon() after you have downloaded your image and converted it to a Bitmap.

    [edit] There is another solution: If you create a completely custom notification with its own view, you could put anything inside that view, including downloaded images.

    0 讨论(0)
  • 2020-12-19 16:29

    In API level 23 , Android has introduced new method to setSmallIcon using bitmap downloaded from url.

        notificationBuilder.setSmallIcon(Icon.createWithBitmap(yourDownloadedBitmap));
    
    0 讨论(0)
  • 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:

    <uses-permission android:name="android.permission.INTERNET" />
    
    0 讨论(0)
  • 2020-12-19 16:39

    The Simple way to set up a custom png image to Notifications is by create a drawable folder in app/src/main/res folder and paste the image to that folder then you can access that image like this

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.imagename);

    0 讨论(0)
提交回复
热议问题