21

我知道您可以在消息、标题、图像 URL 等推送通知参数中发送信息。Facebook 如何在通知区域中显示您的个人资料图片和您的消息?我想在通知区域中使用外部图像,因此当您将其拉下时,您会看到带有消息的个人资料图像。现在,我的只是显示可绘制文件夹中的默认图标。我认为这可能是一个常见问题,但找不到任何东西。你能帮忙的话,我会很高兴。

4

5 回答 5

36

该语句将使用一种方法将 URL(自然地,指向图像的 URL)转换为Bitmap.

Bitmap bitmap = getBitmapFromURL("https://graph.facebook.com/YOUR_USER_ID/picture?type=large");

注意:由于您提到了 Facebook 个人资料,因此我提供了一个 URL,该 URL 可以获取您的 Facebook 用户的大尺寸个人资料图片。但是,您可以将其更改为指向您需要在Notification.

以及从您在上述语句中指定的 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;
    }
}

现在将bitmap上面创建的实例传递给Notification.Builder实例。我builder在这个示例代码中调用它。它用于此行:builder.setLargeIcon(bitmap);. 我假设您知道如何显示实际Notification及其配置。因此,我将跳过该部分并仅添加builder

// CONSTRUCT THE NOTIFICATION DETAILS
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Some Title");
builder.setContentText("Some Content Text");
builder.setLargeIcon(bitmap);
builder.setContentIntent(pendingIntent);

哦,差点忘了,如果你还没有这样做,你需要在 Manifest 中设置这个权限:

<uses-permission android:name="android.permission.INTERNET" />
于 2013-04-15T04:30:15.983 回答
18

在此处输入图像描述

首先使用以下代码下载图像:

private Bitmap getBitmap(String url)
    {
        File f=fileCache.getFile(url);

        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;

        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }

在下面的代码中使用该图像作为位图:

Bitmap icon1 = downloadedBitmap;

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                    this).setAutoCancel(true)
                    .setContentTitle("DJ-Android notification")
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentText("Hello World!");

            NotificationCompat.BigPictureStyle bigPicStyle = new NotificationCompat.BigPictureStyle();
            bigPicStyle.bigPicture(icon1);
            bigPicStyle.setBigContentTitle("Dhaval Sodha Parmar");
            mBuilder.setStyle(bigPicStyle);

            // Creates an explicit intent for an Activity in your app
            Intent resultIntent = new Intent(this, testActivity.class);

            // The stack builder object will contain an artificial back stack
            // for
            // the
            // started Activity.
            // This ensures that navigating backward from the Activity leads out
            // of
            // your application to the Home screen.
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

            // Adds the back stack for the Intent (but not the Intent itself)
            stackBuilder.addParentStack(testActivity.class);

            // Adds the Intent that starts the Activity to the top of the stack
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
                    0, PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);

            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            // mId allows you to update the notification later on.
            mNotificationManager.notify(100, mBuilder.build());

我知道你不知道关于 android 权限:

<uses-permission android:name="android.permission.INTERNET" />

有关更多详细信息,请查看此articalandroid 开发人员

于 2013-04-15T05:38:39.627 回答
0

我使用通用图像加载器来解决这个问题。查看 wiki 以了解如何设置它。实例化一次后,这是我在 GCM 侦听器中用于下载和显示图像的代码。我下载位图,然后在通知中设置它:

// Download profile picture of the user with Universal Image Loader
Bitmap bitmap =  ImageLoader.getInstance().loadImageSync(profilePhotoUrl);

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
        PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_my_app)
        .setLargeIcon(bitmap) // This is the image displayed on the lock screen
        .setContentTitle("My App")
        .setContentText(message)
        .setAutoCancel(true)
        .setSound(defaultSoundUri)
        .setContentIntent(pendingIntent);
于 2016-03-11T01:40:31.717 回答
0

由于图像是从互联网加载的,它应该在后台线程中异步完成。您可以使用 (1) 异步任务或 (2) Glide(用于有效的图像加载)。

要加载图像通知,您需要使用“ NotificationCompat.BigPictureStyle() ”。这需要一个位图(必须从图像 url 中提取)

Glide的大部分 API 和方法现在都被弃用了。以下适用于 Glide 4.9 和 Android 10。

第 1 步:从后台线程上的图像 url 加载位图

   private void getBitmapAsyncAndDoWork(String imageUrl) {

            final Bitmap[] bitmap = {null};

            Glide.with(getApplicationContext())
                    .asBitmap()
                    .load(imageUrl)
                    .into(new CustomTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                            bitmap[0] = resource;
                            // TODO Do some work: Load image notification from here
                            displayImageNotification(bitmap[0]);
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {
                        }
                    });
        }

步骤2:显示一次图像通知,位图准备就绪。

private void displayImageNotification(Bitmap bitmap) {

      NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), getChannelId());
            builder
                    .setContentTitle(title)
                    .setContentText(subtext)
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
                    .setSmallIcon(SMALL_ICON)
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setColor(getApplicationContext().getColor(color))
                    .setAutoCancel(true)
                    .setOngoing(false)
                    .setOnlyAlertOnce(true)
                    .setContentIntent(pendingIntent)
                     .setStyle(
                     new NotificationCompat.BigPictureStyle().bigPicture(bitmap))
                    .setPriority(Notification.PRIORITY_HIGH);

        getManager().notify(tag, id, builder.build());
}
于 2019-11-08T06:57:15.370 回答
-3
Notification notif = new Notification.Builder(context)
     .setContentTitle("Title")
     .setContentText("content")
     .setSmallIcon(R.drawable.ic_small)
     .setLargeIcon(bitmap)
     .setStyle(new Notification.BigPictureStyle()
         .bigPicture(bigBitmap)
         .setBigContentTitle("big title"))
     .build();
于 2015-02-03T08:48:52.177 回答