显示通知进度

时间:2017-08-24 12:48:31

标签: android firebase firebase-storage

我正在将视频上传到firebase,我想在搜索栏和通知中显示进度状态。我的搜索栏行为正常,但我的进度通知显示正在下载进行中状态

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
     if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
        Uri selectedImageUri = data.getData();

        // Get a reference to store file at chat_photos/<FILENAME>
        StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());

        // Upload file to Firebase Storage
        photoRef.putFile(selectedImageUri)
                .addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        // When the image has successfully uploaded, we get its download URL
                        //  progressBar.setVisibility(View.VISIBLE);
                        Uri downloadUrl = taskSnapshot.getDownloadUrl();

                        // Set the download URL to the message box, so that the user can send it to the database
                        Video video = new Video(downloadUrl.toString());
                        mMessagesDatabaseReference.push().setValue(video);

                    }
                }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                final int progress = (int) ((100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());

                seekBar.setProgress(progress);
                final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
                        .setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary))
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentText("Download in progress")
                        .setAutoCancel(true);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
                }

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

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int incr;
                        // Do the "lengthy" operation 20 times
                        for (incr = progress; incr <= 100; incr++) {
                            // Sets the progress indicator to a max value, the
                            // current completion percentage, and "determinate"
                            // state
                            notificationBuilder.setProgress(100, incr, false);
                            // Displays the progress bar for the first time.
                            notificationManager.notify(id, notificationBuilder.build());
                            // Sleeps the thread, simulating an operation
                            // that takes time
                            try {
                                // Sleep for 5 seconds
                                Thread.sleep(5*1000);
                            } catch (InterruptedException e) {
                                Log.d(TAG, "sleep failure");
                            }
                        }
                        notificationBuilder.setContentText("Download complete")
                                // Removes the progress bar
                                .setProgress(0,0,false);
                        notificationManager.notify(id, notificationBuilder.build());
                      }

                    }
                // Starts the thread by calling the run() method in its Runnable
                ).start();
            }
        });

    }
}

Seekbar工作正常,但是进度通知有时会显示下载完成,即使文件没有上传到firebase,并且在显示下载完成后,它会再次显示正在进行的通知。我做错了什么?请帮忙。我已经参考了以下文档&amp;按照步骤,但无法弄清楚为什么我的进展通知是这样的 https://developer.android.com/training/notify-user/display-progress.html

1 个答案:

答案 0 :(得分:2)

您的线程代码是主要问题。循环每5秒后迭代一次。因此,您的答案会再次显示正在进行的通知。&#34; 从代码中删除线程。这只是在Developer Guide

您可以使用AsyncTask执行此操作。代码如下:

private class YourTaskLoader extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
      notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      builder = new NotificationCompat.Builder(this);
      builder.setContentTitle("Picture upload")
                .setContentText("Uploading in progress")
                .setSmallIcon(R.drawable.ic_backup);
    }

    @Override
    protected Void doInBackground(Void... params) {
        UploadPicture();
        return null;
    }
}

在需要时通过以下代码致电AsyncTask

new YourTaskLoader().execute();

以及onProgress()方法的代码 在那个循环中

builder.setProgress(100,progress,false);
notificationManager.notify(1001,builder.build());

循环结束后调用以下行,以便删除通知栏中的进度 您可以在onSuccess()方法中添加这些行。

builder.setContentText("Upload Complete")
       .setProgress(0,0,false);
notificationManager.notify(1001,builder.build());

我希望它有所帮助。