首页 > 解决方案 > 如何仅以 10% 的增量调用 NotificationManager

问题描述

我有一个上传照片的服务正在运行。我有一个由 NotificationManager 更新的进度条,但是它被多次调用。

IntentService[n identical 127 lines

我怎样才能让经理只在上传 10% 的增量时通知?

@Override
        public void writeTo(@NonNull BufferedSink sink) throws IOException {
            long fileLength = mFile.length();
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            FileInputStream in = new FileInputStream(mFile);
            long uploaded = 0;
            int read;

            while (is_uploading && (read = in.read(buffer)) != -1) {
                int percent = 10* (int) (10 * uploaded / fileLength);
                mManager.notify(NOTIFICATION_ID, uploadingProgressNotification(String.valueOf(current_image_uploading+1), percent + 10));
                uploaded += read;
                sink.write(buffer, 0, read);
            }



        }

编辑:

@Override
        public void writeTo(@NonNull BufferedSink sink) throws IOException {
            long fileLength = mFile.length();
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            FileInputStream in = new FileInputStream(mFile);
            long uploaded = 0;
            int read;

            while (is_uploading && (read = in.read(buffer)) != -1) {
                int percent = 10* (int) (10 * uploaded / fileLength);
                if(percent % 10 == 0){
                    Log.d(TAG, "writeTo: test");
                    mManager.notify(NOTIFICATION_ID, uploadingProgressNotification(String.valueOf(current_image_uploading+1), percent + 10));
                }
                uploaded += read;
                sink.write(buffer, 0, read);
            }



        }

Log.d(TAG, "writeTo: test");即使它应该只有 10 次,它仍然被调用了很多次。

IntentService[n identical 346 lines

标签: android

解决方案


使用以下代码:

int percent = (int) (100 * uploaded / fileLength);
if(percent % 10 == 0 && lastPercent != percent){
   lastPercent = percent;
   mManager.notify(NOTIFICATION_ID, uploadingProgressNotification(String.valueOf(current_image_uploading+1), percent));
}

还创建全局变量public int lastPercent = 0;


推荐阅读