【问题标题】:How to show the progress bar in notification area?如何在通知区域显示进度条?
【发布时间】:2012-08-26 06:32:44
【问题描述】:

嗨,我正在做一个 android 应用程序,其中我正在将视频上传到 PHP 服务器。
我正在使用 HTTPURLConnection 进行上传。在通知区域显示进度条并更新它时,我感到很震惊。
我正在搜索将近一周的时间。但无法得到提示。如果有人知道,请帮助我:

我的代码:

HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead;
        byte[] buffer;
        String urlString = "http://xxxxx/My_path.php";
        try {
            long total = 0;
            int count = 0;
            // ------------------ CLIENT REQUEST
            UUID uniqueKey = UUID.randomUUID();
            fname = uniqueKey.toString();
            Log.e("UNIQUE NAME", fname);
            FileInputStream fileInputStream = new FileInputStream(
                    new File(selectedPath));
            URL url = new URL(urlString);                       
            conn = (HttpURLConnection) url.openConnection();
            int length=selectedPath.length();
            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);                    
            }           
            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);
        }

【问题讨论】:

    标签: android notifications progress-bar


    【解决方案1】:

    经过长时间的搜索,我完成了在通知区域显示进度条的任务。我们需要的是asynctask。可能是我在这里显示的代码不能完美运行,它在我测试时运行良好。请检查并投票如果它运作良好,则为这个答案。

    我的代码:

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

    感谢和问候 孙达。

    【讨论】:

    • 我只是在寻找解决方案,我正在考虑做完全相同的事情(根本没有尝试过通知区域进度条)。唯一让我担心的是,当用户更改屏幕方向或离开应用程序时,线程将停止。但是......这不是这里的问题,就像看到其他人正在使用我正在考虑的解决方案一样 :) 如果其他人有更好的解决方案,当然请告诉我们
    【解决方案2】:

    使用 setProgress 的更简单的方法:

    public class loadVideo extends AsyncTask<Void, Integer, Void> {
    
            int progress = 0;
            NotificationCompat.Builder notificationBuilder;
            NotificationManager notificationManager;
            int id = 10;
    
            protected void onPreExecute() {
                //setup notification
                notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                notificationBuilder  = new NotificationCompat.Builder(getApplicationContext())
                      .setPriority(Notification.PRIORITY_MAX)
                      .setProgress(100,0,false)
                      .setContentTitle("Uploading Video")
                      .setSmallIcon(R.mipmap.ic_launcher)
                      .setContentIntent(pendingIntent)
                      .setAutoCancel(true);
    
                notificationManager.notify(id,notificationBuilder.build());
            }
    
            @Override
            protected Void doInBackground(Void... params) {
                //do whatever here
                return null;
            }
    
            @Override
            protected void onProgressUpdate(Integer... progress) {
              ...
                notificationBuilder.setContentText(""+intProgress+"%");
                notificationBuilder.setProgress(100, intProgress,false);
                notificationManager.notify(id, notificationBuilder.build());
            }
    
            protected void onPostExecute(Void result) {
                ...
                notificationBuilder.setContentText("Upload Complete");
                notificationManager.notify(1, notificationBuilder.build());
                //continue conquering the world here...
            }
        }
    

    【讨论】:

    • 你必须在doInBackground中使用publishProgress(progress_value);来调用onProgressUpdate(Integer... progress)
    【解决方案3】:

    在 RemoveView 中,您可以更新进度条。所以结合一些示例代码,我得到了这样的结果:

    public class MyActivity extends Activity {
    private static final int PROGRESS = 0x1;
    private static final int MAX_PROGRESS = 100;
    
    private int mProgressStatus = 0;
    
    private Handler mHandler = new Handler();
    
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
    
        //define Notification
        //...
    
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
        contentView.setProgressBar(R.id.progress_bar, MAX_PROGRESS, mProgressStatus, false);
        notification.contentView = contentView;
    
        // Start file upload in a background thread
        new Thread(new Runnable() {
            public void run() {
                while (mProgressStatus < MAX_PROGRESS) {
                    mProgressStatus = doWork();
    
                    // Update the progress bar
                    mHandler.post(new Runnable() {
                        public void run() {
                            contentView.setProgressBar(R.id.progress_bar, MAX_PROGRESS, mProgressStatus, false);
                        }
                    });
                }
            }
        }).start();
      }
    }
    

    这个blog post 有一个很好的实现相同的例子。希望这会有所帮助。

    【讨论】:

    • 以上代码出现空指针异常。你可以检查代码并告诉我吗?
    • 您查看了博文吗?我认为它会解决您的问题。
    • 是的,我看到了博客。但是不知道如何将上传代码与你提到的博客文章同步。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多