1

Im new for android, I want to send notification with image.If i use image from drawable folder means i can do. But, i want to pull image from url and then send to it... I tried some code its crash my app. How to do Anyone guide to me!

My code here:

protected static void postNotification(Intent intentAction, Context context,String msg,String url){
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentAction, Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL);
    Bitmap bitmap = new ImageDownloaderTask().doInBackground(url);
    Notification notification = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.tapn)
            .setContentTitle("Notification")
            .setContentText(msg)
            .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmap))
            .setContentIntent(pendingIntent)
            .setDefaults(Notification.DEFAULT_SOUND)
            .setAutoCancel(true)
            .getNotification();
    mNotificationManager.notify(R.string.notification_number, notification);
}

ImageDownloaderTask.java:

public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private Exception exception;
@Override
public Bitmap doInBackground(String... params) {
    return downloadBitmap(params[0]);
}

private Bitmap downloadBitmap(String url) {
    HttpURLConnection urlConnection = null;
    try {
        URL uri = new URL(url);
        urlConnection = (HttpURLConnection) uri.openConnection();

        int statusCode = urlConnection.getResponseCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }

        InputStream inputStream = urlConnection.getInputStream();
        if (inputStream != null) {

            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            return bitmap;
        }
    } catch (Exception e) {
        Log.d("URLCONNECTIONERROR", e.toString());
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        Log.w("ImageDownloader", "Error downloading image from " + url);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();

        }
    }
    return null;
}

protected void onPostExecute(Bitmap feed) {
    // TODO: check this.exception
    // TODO: do something with the feed
}

}

My logcat:

D/URLCONNECTIONERROR: android.os.NetworkOnMainThreadException

W/ImageDownloader: Error downloading image from https://www.google.com/intl/en_ALL/images/logo.gif

Thanks in advance!

hikoo
  • 517
  • 4
  • 10
  • 20
  • You should not do network operations on the main thread. Create an AsyncTask where you call your getImage method in the background. – Victor Santiago Jul 01 '16 at 05:33
  • Call this method in a thread or asynctask – lal Jul 01 '16 at 05:33
  • You need to use async task or image loader for getting image from network, as it will not allow you to perform any network related task on main thread. – Vickyexpert Jul 01 '16 at 05:34
  • Anyone edit my code, how to use AsyncTask – hikoo Jul 01 '16 at 05:36
  • See my edit.. Now this time app not crash. But, image cannot be show – hikoo Jul 01 '16 at 06:10
  • Try using this library for this purpose. It is very efficient for this purpose and has tons of other network image related features. https://github.com/nostra13/Android-Universal-Image-Loader – priyankvex Jul 01 '16 at 07:54

4 Answers4

2

yes because you try to do networking with main-thread for solving the problem you have 3 solution

  1. use AsyncTask
  2. use CallBack Pattern (i like this one a lot)
  3. use vinci lightweight android library

    • first implement the Request on class have postNotification method (like this )
    • two use library like this

      Vinci.base(context) .process() .load(uri, this);

    • three get bitmap from onSuccess method, that's it .

      @Override public void onSuccess(Bitmap bitmapparam) { //bitmap is ready here bitmapvar = bitmapparam; }

Hosseini
  • 547
  • 3
  • 15
1

You can't perform any network task in your main thread in latest versions of Android. You have to use AsyncTask for that.

To know more about AysncTask follow this

Kunu
  • 5,078
  • 6
  • 33
  • 61
1

As before me you already know the reason behind the failure of your app bitmap operation . You may use my code

   private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public LoadProfileImage(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {

       //mImage.setBackground(result);
        bmImage.setImageBitmap(result);
    }}
Umar Ata
  • 4,170
  • 3
  • 23
  • 35
0

As the answers before me clarify the cause of use problem is that you perform network task in your main thread. to know how to solve that error please take a look at this answer

but if you want to just get an image from URI you can use some of the amazing libraries that help you to that in one step my preferred one is Glide is fast and super simple to use.

Community
  • 1
  • 1
humazed
  • 74,687
  • 32
  • 99
  • 138