2009-12-09 19 views
28

Vorrei che la mia app carichi un'immagine su un server web. Quella parte funziona.Barra di avanzamento nella barra di notifica durante il caricamento dell'immagine?

Mi chiedo se è possibile mostrare in qualche modo l'avanzamento del caricamento inserendo una voce nella "barra di notifica". Vedo che l'app di Facebook fa questo.

Quando si scatta una foto e si sceglie di caricare, l'app consente di continuare e in qualche modo inserisce le notifiche di caricamento delle immagini in una barra di avanzamento nella barra delle notifiche. Penso che sia piuttosto lucido. Immagino che generino un nuovo servizio o qualcosa per gestire il caricamento e aggiornare la barra di avanzamento nella barra delle notifiche ogni tanto.

Grazie per tutte le idee

+2

http://united-coders.com/nico-heid/show-progressbar-in- ho notato che questo ha funzionato molto bene – morty346

+0

[Visualizzazione dei progressi in una notifica] (http://developer.android.com/guide/topics/ui/notifiers/notifications .html # Progress) per chiunque altro trovi questo ... – aecl755

risposta

16

È possibile progettare una notifica personalizzata, anziché solo la vista di notifica predefinita dell'intestazione e dell'intestazione secondaria.

quello che vuoi è here

2

Io non sono un utente di Facebook, quindi non so esattamente quello che stai vedendo.

È certamente possibile aggiornare un Notification, cambiando l'icona per riflettere i progressi completati. Come sospetti, lo faresti da uno Service con un thread in background che sta gestendo il caricamento.

+0

D'accordo, immagino che mi stia chiedendo quale API hanno usato per mettere la barra di avanzamento nella barra delle notifiche - il pannello dell'interfaccia utente globale che puoi scorrere con il dito che mostra l'avanzamento del download dal market ecc. Sembra che il pannello sia esterno alla app sono ancora in grado di mettere la loro barra di avanzamento lì? Grazie – Mark

+0

Bene, ecco come funzionano le notifiche ... li invii con il servizio di piattaforma di notifica, e appariranno in quel pannello. Come ha detto Klondike, puoi rendere qualsiasi vista come il corpo della notifica, quindi nessuna magia qui. La domanda più interessante è come ottenere informazioni sul progresso da un caricamento di foto. Dovresti suddividere il tuo caricamento in blocchi e caricarli uno per uno. Sembra molto lavoro per un effetto piuttosto inutile. Voglio dire, che nelle loro menti continuerebbe a fissare una barra di avanzamento in una notifica ... – Matthias

+0

Questo è stato diretto @Mark – Matthias

12

In Android, in modo da visualizzare una barra di avanzamento in un Notification, basta inizializzare setProgress(...) nella Notification.Builder.

Nota che, nel tuo caso, probabilmente vorrai usare anche il flag setOngoing(true).

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

Quindi, il servizio dovrà notificare l'avanzamento. Supponendo che si memorizza la vostra (in percentuale) i progressi in un Integer chiamato progresso (ad es progresso = 10):

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

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

è possibile trovare maggiori informazioni sulle Notifiche API pagina: http://developer.android.com/guide/topics/ui/notifiers/notifications.html#Progress

-1

public class loadVideo estende AsyncTask {

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

controlla questo se può aiutarti

0

Tu this biblioteca e divertiti ..! controllare esempio per maggiori dettagli ..

1

È possibile provare questa classe vi aiuterà a generare la notifica

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