2009-12-09 12 views
28

Me gustaría que mi aplicación cargue una imagen en un servidor web. Esa parte funcionaBarra de progreso en la barra de notificaciones al cargar la imagen?

Me pregunto si es posible demostrar de alguna manera el progreso de la carga mediante la introducción de una entrada en la "barra de notificaciones". Veo que la aplicación de Facebook hace esto.

Cuando se toma una fotografía y decide cargar, la aplicación le permite seguir adelante, y de alguna manera pone las notificaciones de subida de imágenes en una barra de progreso en la barra de notificaciones. Creo que eso es bastante astuto. Supongo que generan un nuevo servicio o algo para manejar la carga y actualizar esa barra de progreso en la barra de notificaciones cada cierto tiempo.

Gracias por cualquier idea

+2

http://united-coders.com/nico-heid/show-progressbar-in- la notificación del área-like-google-hace-al-descarga-de-android he seguido este funcionó muy bien – morty346

+0

[Viendo el Progreso en una notificación] (http://developer.android.com/guide/topics/ui/notifiers/notifications .html # Progress) para cualquier otra persona que encuentre esto ... – aecl755

Respuesta

16

Puede diseñar una notificación personalizada, en lugar de solo la vista de notificación predeterminada del encabezado y el subencabezado.

Lo que queremos es here

2

No soy un usuario de Facebook, así que no sé exactamente lo que se está viendo.

Sin duda, es posible mantener la actualización de un Notification, cambiar el icono para reflejar el progreso completado. Como sospecha, haría esto desde un Service con un hilo de fondo que está gestionando la carga.

+0

De acuerdo, supongo que me pregunto qué API usaron para poner su barra de progreso en la barra de notificaciones: el panel de interfaz de usuario global puede deslizarse hacia abajo con el dedo que muestra el progreso de la descarga desde el mercado, etc. Parece que el panel es externo a la aplicación, sin embargo, ¿pueden poner su barra de progreso allí? Gracias – Mark

+0

Bueno, así es como funcionan las notificaciones ... las envía con el servicio de plataforma de notificación, y aparecerán en ese panel. Como dijo Klondike, puedes representar cualquier vista como el cuerpo de notificación, así que no hay magia aquí. La pregunta más interesante es cómo obtener información de progreso de una carga de fotos. Necesitarás dividir tu carga en trozos y subirlos uno por uno. Suena como un montón de trabajo para un efecto bastante inútil. Quiero decir, quién en sus mentes correctas seguiría mirando una barra de progreso en una notificación ... – Matthias

+0

Eso fue dirigido @Mark – Matthias

12

En Android, con el fin de mostrar una barra de progreso en un Notification, sólo tiene que inicializar setProgress(...) en el Notification.Builder.

Tenga en cuenta que, en su caso, es probable que desee utilizar incluso el setOngoing(true) bandera.

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

Luego, su Servicio deberá notificar el progreso. Suponiendo que vaya a guardar el progreso (porcentaje) en una Entero llamada progreso (por ejemplo progreso = 10):

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

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

usted puede encontrar más información sobre los Notificaciones API página: http://developer.android.com/guide/topics/ui/notifiers/notifications.html#Progress

-1

loadVideo clase pública se extiende 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); 
    } 
} 

verifique esto si puede ayudarlo u

0

¡Usted this biblioteca y disfrute ..! comprobar ejemplo para más detalles ..

1

Usted puede probar esta clase que le ayudará a generar la notificación

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