上传图片时通知栏中的进度条?

时间:2009-12-09 04:03:35

标签: android

我希望我的应用将图片上传到网络服务器。那部分有效。

我想知道是否可以通过在“通知栏”中输入条目来以某种方式显示上传的进度。我看到Facebook应用程序就是这样做的。

当你拍照并选择上传时,该应用程序可让你继续,并以某种方式将图片上传通知放在通知栏的进度条中。我觉得这很漂亮。我猜他们会产生一个新服务或其他东西来处理上传,并经常更新通知栏中的进度条。

感谢您的任何想法

5 个答案:

答案 0 :(得分:15)

您可以设计自定义通知,而不仅仅是标题和子标题的默认通知视图。

你想要的是here

答案 1 :(得分:15)

在Android中,为了在Notification中显示进度条,您只需将setProgress(...)初始化为Notification.Builder

请注意,在您的情况下,您可能希望使用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);

然后,您的服务必须通知进度。假设您将(百分比)进度存储到名为进度整数中(例如 progress = 10 ):

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

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

您可以在 API通知页面找到更多信息:http://developer.android.com/guide/topics/ui/notifiers/notifications.html#Progress

答案 2 :(得分:2)

我不是Facebook用户,所以我不确切知道你在看什么。

当然可以继续更新Notification,更改图标以反映已完成的进度。正如您所怀疑的那样,您可以使用管理上传的后台线程从Service执行此操作。

答案 3 :(得分:2)

您可以试用此课程,它可以帮助您生成通知

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

答案 4 :(得分:1)

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

检查这是否可以帮助你