1

Hi guys i am trying to implement notifications into my application. The thing is that i want each notification to have a certain image taken from the imageview if possible.

Since the documentation says that the setSmallIcon() method can only take an int resId as parameter i have to use the setLargeIcon() method. How can i convert an Image that comes from URL into Bitmap?

Already Tried:

Bitmap bmp = BitmapFactory.decodeFile(getIntent().getStringExtra("stockImage"));
builder.setLargeIcon(bmp); 

It gives me this error:

02-15 11:34:34.576    1615-1615/com.kostas.stockpredictions E/BitmapFactory﹕ Unable to decode stream: java.io.FileNotFoundException: http:/www.chatapp.info/myProject/images/ALPHA.png: open failed: ENOENT (No such file or directory)

I set this url into an Imageview using Ion library like this:

iv = (ImageView)findViewById(R.id.currentStockImageViewItem);
Ion.with(iv).placeholder(R.drawable.ic_chat).error(R.drawable.ic_chat).load(i.getStringExtra("stockImage"));

EDIT:

class GetBitmapUrl extends AsyncTask<String, Void, Bitmap>{

        @Override
        protected Bitmap doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);
                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;
            }
        }



        @Override
        protected void onPostExecute(Bitmap result) {
            builder.setLargeIcon(result);
        }
    }

    public void getBitmap(){
        GetBitmapUrl task = new GetBitmapUrl();
        task.execute(getIntent().getStringExtra("stockImage"));
    }

And i call this method here:

Button notify = (Button)findViewById(R.id.buttonNotify);
                    notify.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            builder = new NotificationCompat.Builder(StockItem.this);
                            builder.setContentTitle(name);
                            builder.setContentText(getString(R.string.notifyText) + " " + new DecimalFormat("###.##").format(avg));
                            builder.setWhen(System.currentTimeMillis());
                            getBitmap();
                            //builder.setSmallIcon(R.drawable.ic_launcher_stock_custom_icon);
                            builder.setTicker(getString(R.string.notifyTicker));
                            builder.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                                    + "://" + getPackageName() + "/raw/carme"));
                            builder.setDefaults(NotificationCompat.DEFAULT_LIGHTS | NotificationCompat.DEFAULT_VIBRATE);
                            builder.setAutoCancel(true);
                            Intent intent = new Intent(StockItem.this, ListLoaderActivity.class);
                            TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(StockItem.this);

                            taskStackBuilder.addNextIntent(intent);
                            taskStackBuilder.addParentStack(ListLoaderActivity.class);

                            PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
                            builder.setContentIntent(pendingIntent);
                            NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                            manager.notify(1, builder.build());

                        }
                    });

Now the notification does not show up..

Is it possible to have a Bitmap with the image from imageview?

Thanks in advance!!!

Kostas Drak
  • 3,222
  • 6
  • 28
  • 60
  • Refer this http://stackoverflow.com/questions/16007401/android-use-external-profile-image-in-notification-bar-like-facebook – Fahim Feb 15 '15 at 11:55
  • i already tried the accepted answer but it gave me an error: `02-15 11:44:49.997 1735-1735/com.kostas.stockpredictions E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.kostas.stockpredictions, PID: 1735 android.os.NetworkOnMainThreadException` – Kostas Drak Feb 15 '15 at 12:00
  • If you search a major search engine for `NetworkOnMainThreadException`, you will come up with: http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – CommonsWare Feb 15 '15 at 12:06

2 Answers2

2

Use this code either

Notification notification = new Notification(R.drawable.images, getText(R.string.time),
                System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, ActivityStart.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, "The Service has started",
               "This is a foreground service", pendingIntent);
        startForeground(3, notification);

To download the image use the following code in the doInBackgroundMethod of an AsyncTask.

  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 override the onPostExecute method in the Asynctask as follows:

// change the return type of doInBackGround to InputStream
@Override
public void onPostExecute(InputStream in){
// let the bitmap in the activity be activityBitmap

 Bitmap activityBitmap = BitmapFactory.decodeStream(input);
}

an example is

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private int data = 0;

public BitmapWorkerTask(ImageView imageView) {
    // Use a WeakReference to ensure the ImageView can be garbage collected
    imageViewReference = new WeakReference<ImageView>(imageView);
}

// Decode image in background.
@Override
protected Bitmap doInBackground(Integer... params) {
    data = params[0];
    return decodeSampledBitmapFromResource(getResources(), data, 100, 100));
}

// Once complete, see if ImageView is still around and set bitmap.
@Override
protected void onPostExecute(Bitmap bitmap) {
    if (imageViewReference != null && bitmap != null) {
        final ImageView imageView = imageViewReference.get();
        if (imageView != null) {
            imageView.setImageBitmap(bitmap);
        }
    }
}

}

Nagabhushan Baddi
  • 1,164
  • 10
  • 18
2

Custom Notification Layouts

  1. The notifications framework allows you to define a custom notification layout, which defines the notification's appearance in a RemoteViews object. Custom layout notifications are similar to normal notifications, but they're based on a RemoteViews defined in a XML layout file.

    The height available for a custom notification layout depends on the notification view. Normal view layouts are limited to 64 dp, and expanded view layouts are limited to 256 dp.

    To define a custom notification layout, start by instantiating a RemoteViews object that inflates an XML layout file. Then, instead of calling methods such as setContentTitle(), call setContent(). To set content details in the custom notification, use the methods in RemoteViews to set the values of the view's children:

    Create an XML layout for the notification in a separate file. You can use any file name you wish, but you must use the extension .xml In your app, use RemoteViews methods to define your notification's icons and text. Put this RemoteViews object into your NotificationCompat.Builder by calling setContent(). Avoid setting a background Drawable on your RemoteViews object, because your text color may become unreadable.

for more detail please go to http://developer.android.com/guide/topics/ui/notifiers/notifications.html

Yogendra
  • 4,817
  • 1
  • 28
  • 21