在通知中显示进度 [英] Displaying progress in notification

查看:96
本文介绍了在通知中显示进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将视频上传到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

解决方案

您的线程代码是主要问题.每5秒钟循环一次.因此,您对它再次显示正在进行中的通知"的答案. 从代码中删除线程.例如,开发人员指南

您可以使用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());

希望对您有帮助.

I am uploading a video to firebase and I want to show the status of the progress in both seekbar and in my notification. My seekbar behaves properly, but my notification with progress keeps showing download in progress status

@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 works fine, but notification with progress sometimes shows download complete even though file is not uploaded to firebase and after showing download complete, it agains shows the notification of in progress.What am i doing wrong? Please help. I already refer the following documentation & followed the steps but not able to figure it out why my notification with progress is behaving this way https://developer.android.com/training/notify-user/display-progress.html

解决方案

Your Thread code is the main problem. The loops iterate after every 5 seconds. Hence your answer for "it agains shows the notification of in progress." Remove the Thread from your code. It was just for example in Developer Guide

You can use AsyncTask to do this. Code is as follow:

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

Call your AsyncTask by following code when in need

new YourTaskLoader().execute();

and the code for onProgress() method In that loop

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

After the loop is over Call the following lines so that the progress in the notification bar is removed.
You can add these lines in onSuccess() method.

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

I hope it helps.

这篇关于在通知中显示进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆