更新通知区域中的进度条

时间:2010-08-21 13:17:19

标签: android

如何在通知栏中制作自定义布局已有几个主题。问题是我必须遗漏一些简单的东西。

我有一个custom_notification_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="3dip"
              >

    <TextView android:id="@+id/text"
              android:text="Uploading"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textColor="#000"
              />

    <ProgressBar  
            style="?android:attr/progressBarStyleHorizontal" 
            android:layout_height="wrap_content" 
            android:layout_width="fill_parent"
            android:max="0" 
            android:progress="0"   
            android:layout_marginLeft="10dip"  
            android:id="@+id/progressBar" 
            />  
</LinearLayout>

我还有一些创建通知的测试代码,它可以工作并显示进度条。

NotificationManager mManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, title, System.currentTimeMillis());
RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout);
contentView.setProgressBar(R.id.progressBar, 10, 0, false);        
contentView.setTextViewText(R.id.text, text);       
notification.contentView = contentView;

Intent notificationIntent = new Intent(context, NotificationHandler.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.contentIntent = contentIntent;
mManager.notify(APPID, notification);

最后,我尝试更新进度条,但不起作用。

contentView.setProgressBar(R.id.progressBar, 10, 5, false); 

实际更新通知的秘诀是什么?

4 个答案:

答案 0 :(得分:11)

您应该添加以下两行:

// update the notification object
notification.contentView.setProgressBar(R.id.progressBar, 10, 5, false);
// notify the notification manager on the update.
mManager.notify(APPID, notification);

答案 1 :(得分:5)

请记住不要经常通知状态栏。如果您在内部使用该代码(例如,AsyncTask的onProgressUpdate)并且您通知每个进度,您将虚拟地阻止状态栏。仅在有变化时通知。

答案 2 :(得分:1)

在布局文件中,progressbars max设置为0。 如果它最大值为0,则不能高于0.将其设置为100

答案 3 :(得分:0)

我在更新进度条时遇到问题(我使用NotificationCompat.Builder来完成工作)导致通知区域被阻止。我通过跳过更新来解决问题,如果它们发生在最小间隔时间内,如下所示:

private static final long MIN_UPDATE_INTERVAL = 10000000;

private long lastUpdateTime = System.nanoTime();

并在我的更新回调中:

// Don't update too often
if ((System.nanoTime() - lastUpdateTime)< MIN_UPDATE_INTERVAL) return;

builder.setProgress(max, currentValue, false);
notificationManager.notify(notificationID, builder.build());

lastUpdateTime = System.nanoTime();

这可以防止notiicaton区域出现问题,并且还可以顺利更新进度条