如何动态设置小图标通知

时间:2017-11-26 10:20:13

标签: android

我想设置从服务器收到的小图标通知。我的应用程序下载了一个图标,我希望用这个图标显示通知。

我看到了这个问题,但我找不到答案。

File myFile = new File(myPicAddress);
Notification noti = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setContentTitle("UPDATE APP")
                .setContentText(myNotificationText)
                .setDefaults(Notification.DEFAULT_ALL)
                .setSmallIcon(R.drawable.ic_launcher)//set myFile??
                .setTicker("force android update!")
                .setWhen(triggerTime)
                .build();

我的应用程序已连接到服务器并下载我的图标,然后我想要显示通知,并从服务器下载我的图标。

1 个答案:

答案 0 :(得分:0)

首先从网址下载位图,然后将其设置为如下图标

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;
    }
}

然后将位图设置为小图标

Notification noti = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setContentTitle("UPDATE APP")
                .setContentText(myNotificationText)
                .setDefaults(Notification.DEFAULT_ALL)
                .setSmallIcon(bitmap)//set myFile??
                .setTicker("force android update!")
                .setWhen(triggerTime)
                .build();

API 23及更高版本的更新使用,如下所示

notificationBuilder.setSmallIcon(Icon.createWithBitmap(yourDownloadedBitmap));