47

I'd like my app to upload an image to a web server. That part works.

I'm wondering if it's possible to somehow show the progress of the upload by entering an entry in the "notification bar". I see the Facebook app does this.

When you take a picture and choose to upload, the app lets you continue on, and somehow puts the picture upload notifications in a progress bar in the notification bar. I think that's pretty slick. I guess they spawn a new service or something to handle the upload and update that progress bar in the notification bar every so often.

Thanks for any ideas

Mark
  • 39,551
  • 15
  • 41
  • 47
  • 2
    http://united-coders.com/nico-heid/show-progressbar-in-notification-area-like-google-does-when-downloading-from-android I followed this worked great – GregM Jan 09 '11 at 21:56
  • [Displaying Progress in a Notification](http://developer.android.com/guide/topics/ui/notifiers/notifications.html#Progress) for anyone else that finds this... – aecl755 Jan 11 '13 at 04:38

6 Answers6

39

In Android, in order to display a progress bar in a Notification, you just need to initialize setProgress(...) into the Notification.Builder.

Note that, in your case, you would probably want to use even the setOngoing(true) flag.

Integer notificationID = 100;

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

//Set notification information:
Notification.Builder notificationBuilder = new Notification.Builder(getApplicationContext());
notificationBuilder.setOngoing(true)
                   .setContentTitle("Notification Content Title")
                   .setContentText("Notification Content Text")
                   .setProgress(100, 0, false);

//Send the notification:
Notification notification = notificationBuilder.build();
notificationManager.notify(notificationID, notification);

Then, your Service will have to notify the progress. Assuming that you store your (percentage) progress into an Integer called progress (e.g. progress = 10):

//Update notification information:
notificationBuilder.setProgress(100, progress, false);

//Send the notification:
notification = notificationBuilder.build();
notificationManager.notify(notificationID, notification);

You can find more information on the API Notifications page: http://developer.android.com/guide/topics/ui/notifiers/notifications.html#Progress

Paolo Rovelli
  • 9,396
  • 2
  • 58
  • 37
21

You can design a custom notification, instead of just the default notification view of header and sub-header.

What you want is here

Eric Mill
  • 3,455
  • 1
  • 25
  • 26
3
public class loadVideo extends AsyncTask<Void, Integer, Void> {

        int progress = 0;
        Notification notification;
        NotificationManager notificationManager;
        int id = 10;

        protected void onPreExecute() {

        }

        @Override
        protected Void doInBackground(Void... params) {
            HttpURLConnection conn = null;
            DataOutputStream dos = null;
            DataInputStream inStream = null;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            int bytesRead;
            int sentData = 0;               
            byte[] buffer;
            String urlString = "http://xxxxx/xxx/xxxxxx.php";
            try {
                UUID uniqueKey = UUID.randomUUID();
                fname = uniqueKey.toString();
                Log.e("UNIQUE NAME", fname);
                FileInputStream fileInputStream = new FileInputStream(new File(
                        selectedPath));
                int length = fileInputStream.available();
                URL url = new URL(urlString);
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);
                dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                        + fname + "" + lineEnd);
                dos.writeBytes(lineEnd);
                buffer = new byte[8192];
                bytesRead = 0;
                while ((bytesRead = fileInputStream.read(buffer)) > 0) {
                    dos.write(buffer, 0, bytesRead);
                    sentData += bytesRead;
                    int progress = (int) ((sentData / (float) length) * 100);
                    publishProgress(progress);
                }
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                Log.e("Debug", "File is written");
                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex) {
                Log.e("Debug", "error: " + ex.getMessage(), ex);
            } catch (IOException ioe) {
                Log.e("Debug", "error: " + ioe.getMessage(), ioe);
            }
            // ------------------ read the SERVER RESPONSE
            try {
                inStream = new DataInputStream(conn.getInputStream());
                String str;
                while ((str = inStream.readLine()) != null) {
                    Log.e("Debug", "Server Response " + str);
                }
                inStream.close();

            } catch (IOException ioex) {
                Log.e("Debug", "error: " + ioex.getMessage(), ioex);
            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {

            Intent intent = new Intent();
            final PendingIntent pendingIntent = PendingIntent.getActivity(
                    getApplicationContext(), 0, intent, 0);
            notification = new Notification(R.drawable.video_upload,
                    "Uploading file", System.currentTimeMillis());
            notification.flags = notification.flags
                    | Notification.FLAG_ONGOING_EVENT;
            notification.contentView = new RemoteViews(getApplicationContext()
                    .getPackageName(), R.layout.upload_progress_bar);
            notification.contentIntent = pendingIntent;
            notification.contentView.setImageViewResource(R.id.status_icon,
                    R.drawable.video_upload);
            notification.contentView.setTextViewText(R.id.status_text,
                    "Uploading...");
            notification.contentView.setProgressBar(R.id.progressBar1, 100,
                    progress[0], false);
            getApplicationContext();
            notificationManager = (NotificationManager) getApplicationContext()
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(id, notification);
        }

        protected void onPostExecute(Void result) {
            Notification notification = new Notification();
            Intent intent1 = new Intent(MultiThreadActivity.this,
                    MultiThreadActivity.class);
            final PendingIntent pendingIntent = PendingIntent.getActivity(
                    getApplicationContext(), 0, intent1, 0);
            int icon = R.drawable.check_16; // icon from resources
            CharSequence tickerText = "Video Uploaded Successfully"; // ticker-text
            CharSequence contentTitle = getResources().getString(
                    R.string.app_name); // expanded message
            // title
            CharSequence contentText = "Video Uploaded Successfully"; // expanded
                                                                        // message
            long when = System.currentTimeMillis(); // notification time
            Context context = getApplicationContext(); // application
                                                        // Context
            notification = new Notification(icon, tickerText, when);
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notification.setLatestEventInfo(context, contentTitle, contentText,
                    pendingIntent);
            String notificationService = Context.NOTIFICATION_SERVICE;
            notificationManager = (NotificationManager) context
                    .getSystemService(notificationService);
            notificationManager.notify(id, notification);
        }
    }

check this if it can help u

IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
SumeetP
  • 109
  • 1
  • 2
3

You can try out this class it will help you to generate notification

public class FileUploadNotification {
public static NotificationManager mNotificationManager;
static NotificationCompat.Builder builder;
static Context context;
static int NOTIFICATION_ID = 111;
static FileUploadNotification fileUploadNotification;

/*public static FileUploadNotification createInsance(Context context) {
    if(fileUploadNotification == null)
        fileUploadNotification = new FileUploadNotification(context);

    return fileUploadNotification;
}*/
public FileUploadNotification(Context context) {
    mNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    builder = new NotificationCompat.Builder(context);
    builder.setContentTitle("start uploading...")
            .setContentText("file name")
            .setSmallIcon(android.R.drawable.stat_sys_upload)
            .setProgress(100, 0, false)
            .setAutoCancel(false);
}

public static void updateNotification(String percent, String fileName, String contentText) {
    try {
        builder.setContentText(contentText)
                .setContentTitle(fileName)
                //.setSmallIcon(android.R.drawable.stat_sys_download)
                .setOngoing(true)
                .setContentInfo(percent + "%")
                .setProgress(100, Integer.parseInt(percent), false);

        mNotificationManager.notify(NOTIFICATION_ID, builder.build());
        if (Integer.parseInt(percent) == 100)
            deleteNotification();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        Log.e("Error...Notification.", e.getMessage() + ".....");
        e.printStackTrace();
    }
}

public static void failUploadNotification(/*int percentage, String fileName*/) {
    Log.e("downloadsize", "failed notification...");

    if (builder != null) {
       /* if (percentage < 100) {*/
        builder.setContentText("Uploading Failed")
                //.setContentTitle(fileName)
                .setSmallIcon(android.R.drawable.stat_sys_upload_done)
                .setOngoing(false);
        mNotificationManager.notify(NOTIFICATION_ID, builder.build());
        /*} else {
            mNotificationManager.cancel(NOTIFICATION_ID);
            builder = null;
        }*/
    } else {
        mNotificationManager.cancel(NOTIFICATION_ID);
    }
}

public static void deleteNotification() {
    mNotificationManager.cancel(NOTIFICATION_ID);
    builder = null;
}
}
Vivek Barai
  • 1,338
  • 13
  • 26
2

I'm not a Facebook user, so I do not know exactly what you're seeing.

It is certainly possible to keep updating a Notification, changing the icon to reflect completed progress. As you suspect, you would do this from a Service with a background thread that is managing the upload.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Agreed, I guess I'm wondering what API they used to put their progress bar in the notifications bar - the global UI panel you can slide down with your finger which shows download progress from marketplace etc. It seems that panel is external to the app yet they are able to put their progress bar in there? Thanks – Mark Dec 09 '09 at 15:04
  • Well, that's how notifications work... you send them with the notification platform service, and they'll appear in that panel. As Klondike said, you can render any view as the notification body, so no magic here. The more interesting question is how to get progress information from a photo upload. You'd need to break down your upload into chunks and upload them one by one. Sounds like a lot of work for a pretty useless effect. I mean, who in their right minds would keep staring at a progress bar in a notification... – mxk Dec 09 '09 at 16:25
  • 1
    @Matthias: it's easier to do this if you ask fresh questions (honest! SO can handle the load! :-) Anyway, I think HttpClient can tell you progress upload on the fly. http://stackoverflow.com/questions/254719/file-upload-with-java-with-progress-bar has info for the 3.x API, not Android's 4.x, but the concepts probably hold. – CommonsWare Dec 09 '09 at 16:49
0

You this library and enjoy..! check example for more details..

Gagan
  • 745
  • 10
  • 31