Android - use external profile image in notification bar like Facebook

29,584

Solution 1

This statement will use a method to convert a URL (naturally, one that points to an image) into a Bitmap.

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

Note: Since you mention a Facebook profile, I have included an URL that gets your the large size profile picture of a Facebook User. You can however, change this to any URL that points to an image that you need to display in the Notification.

And the method that will get the image from the URL you specified in the statement above:

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 pass the bitmap instance created above to the Notification.Builder instance. I call it builder in this example code. It is used in this line: builder.setLargeIcon(bitmap);. I am assuming you know how to display the actual Notification and it's configurations. So I will skip that part and add just the 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);

Oh, almost forgot, if you haven't already done so, you will need this permission setup in the Manifest:

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

Solution 2

enter image description here

download image first using below code:

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

use that image as bitmap in below code:

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());

i thing you k'no about android permission:

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

for more detail check this artical and android developer

Share:
29,584
Panama Jack
Author by

Panama Jack

Web enthusiast that enjoys all aspects of the internet and programming. I'm a fan of open source. Mostly my personal setups include Linux (RHEL/CentOS), Apache 2.4, PostgreSQL 9.X, RabbitMQ, Redis cluster Most of my web development is using PHP, jQuery, HTML5, CSS, some python. My servers include many cloud services working as Web, Email, DB, Redis Caching cluster, DNS, RabbitMQ, Media encoding(FFMPEG). Anyway, I help out here when I can.

Updated on November 08, 2020

Comments

  • Panama Jack
    Panama Jack over 3 years

    I know you can send info in the push notification parameters like message, title, image URL, etc. How does Facebook show your profile pic with your message in the notification area? I want to use an external image in the notification area, so when you pull it down you see the profile image with the message. Right now, mine just shows the default icon from the drawable folder. I figured this might be a common question but couldn't find anything. Any help would be nice.

  • Panama Jack
    Panama Jack about 11 years
    Very nice, I like the links to the articles. Question, does this make the entire screen the photo or just the notification bar have the photo? I currently only want it to show in the notification are only that has the title with it.
  • Panama Jack
    Panama Jack about 11 years
    Ahh. nevermind.. I see where you set it in the builder parmaters. Nice. thanks for this and I will try your other layouts as well.
  • Dhaval Parmar
    Dhaval Parmar about 11 years
    @Pjack: wel Come... and accept this as ans if it help you : meta.stackexchange.com/a/5235
  • Panama Jack
    Panama Jack about 11 years
    Question, when I added the code I'm getting two errors. Utils cannot be resolved and fileCache cannot be resolved. How do i fix those?
  • Dhaval Parmar
    Dhaval Parmar about 11 years
  • Panama Jack
    Panama Jack about 11 years
    Thanks for the answer. However I think it's a bit complicated for a simple avatar. The link requires several classes and the use is for display general images. I would need time to dissect it and use the parts I need. I might revisit caching the photo at another time.
  • Panama Jack
    Panama Jack about 11 years
    This is plain and simple and meets what I needed and it works.
  • Siddharth Lele
    Siddharth Lele about 11 years
    @Pjack: I am glad to have been of help. :-)
  • Mahmoud Badri
    Mahmoud Badri over 10 years
    any idea how to load the image in ImageView inside a RemoteViews ?
  • Siddharth Lele
    Siddharth Lele over 10 years
    @MahmoudBadri: I am mobile ATM and don't have access to my code base (I am vacationing. :-) ). But I found this in my Chrome bookmarks. See if this is helpful. I will post an update or, if you post a question, and answer in a couple of days. android.codota.com/scenarios/518915e1da0a0401949d16f2/…
  • grebulon
    grebulon almost 10 years
    Note that this code is synchronous and will delay the notification in case of disconnect. It's best to set short connect and read timeouts in the connection.
  • drindt
    drindt about 9 years
    This code leads some day seriously to an OutOfMemoryError. Depends on the currently used heap space of the app itself and how big the image is. You need a scaling algorithm instead. Also this Bitmap.decode() shouldn't be executed on the UI thread. Think about good software quality.
  • Siddharth Lele
    Siddharth Lele about 9 years
    @drindt: Of course there is potential for OOMs as well as, in it's current form, NetworkOnThread error. But this answer is merely a pointer on what is needed to display a Bitmap in the NotificationBar. Not it's optimization. Combining this answer with others on SO that specifically deal with the OOM and NoT issues is really not the purpose nor my intention. Moving the contents of the try..catch block in an AsyncTask is a fairly ease thing to do eh?
  • user303730
    user303730 over 7 years
    If you use picasso. Bitmap bitmap = Picasso.with(app.context).load(sender.getPicture()).placehol‌​der(R.mipmap.dummy_u‌​ser).get();
  • Siddharth Lele
    Siddharth Lele over 7 years
    @user303730: That is now an option. Yes. However, if I recall correctly, Picasso wasn't released when this answer was posted.