android - 在通知中显示进度

标签 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 并且在显示下载完成后,它再次显示正在进行的通知。我做错了什么?请帮忙。我已经引用了以下文档并按照步骤操作但无法弄清楚为什么我的进度通知会以这种方式运行 https://developer.android.com/training/notify-user/display-progress.html

最佳答案

您的 Thread 代码是主要问题。循环每 5 秒迭代一次。因此,您对“它再次显示正在进行的通知”的回答。 从您的代码中删除线程。这只是在 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());

希望对你有帮助。

关于android - 在通知中显示进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45862094/

相关文章:

java - 确定方法是否为 `RemotableViewMethod`

java - 操作系统版本、API 级别和 Java 版本之间的关系

android - 如何在不使用 XMPP 或任何其他脚本的情况下使用 FCM 向设备发送设备通知。?

javascript - Firebase 在 "Undefined"上返回 "downloadURL"

angular - 即使在 AngularFire2 的 Firebase 存储中取消上传任务后,快照状态仍为 'running'

firebase - Firebase存储中没有 token 的访问url

android - 扩展 HelloGallery 教程。单击图像并将图像传递给另一个 Activity/页面

可穿戴设备上的 Android Activity 识别

android - 使用 firebase 对类进行 JUnit 测试

firebase - 将相同的 Firebase 应用程序与 Web 和移动应用程序一起使用