修改没有自定义布局的Notification.Builder进度条

时间:2012-07-17 15:38:03

标签: android notifications

有人知道如何使用Notification.builder然后更新进度条吗?目前它似乎受限制。我知道我可以访问notification.contentView但是从这里更新progressView需要视图ID,它是android内部类的一部分(我没有访问范围)。当然,如果通知构建器允许您显示进度条,那么应该有更新它的方法吗?

我应该补充一点,我希望在不重复调用'getNotification'的情况下这样做,因为这看起来非常低效。

1 个答案:

答案 0 :(得分:1)

您可以使用新线程以脏的方式执行此操作。但是,通过这种方式,您的通知将不会结束,直到它自身结束。 这是代码。

public void showJobFinishNotification() {
    final String ns = Context.NOTIFICATION_SERVICE;
    final NotificationManager notificationManager = (NotificationManager) getSystemService(ns);
    final Intent notificationIntent = new Intent(this, WillingActivity.class);
    final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    final int JOBFINISH_ID = 1;

    new Thread(new Runnable() {
        public void run() {
            for(int progress = 0; progress <= 29; progress++) {
                Notification jobFinishNotification = new NotificationCompat.Builder(getApplication())
                    .setSmallIcon(R.drawable.ic_launcher) //must have small icon, but the large icon is not a must
                    .setContentTitle("Job is finished")
                    .setContentText("Press here to finish your job.")
                    .setProgress(29, progress, false) 
                    .setDefaults(Notification.DEFAULT_SOUND)
                    .setContentIntent(contentIntent)
                    .setAutoCancel(false)
                    .build();
                notificationManager.notify(JOBFINISH_ID, jobFinishNotification);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            notificationManager.cancel(JOBFINISH_ID); //if you want the user to handle the notification.
            //comment the line above. and use setAutoCancel(true) in the above code.
        }
    }).start();
}