本文实例讲述了Android编程实现通知栏进度条效果的方法。分享给大家供大家参考,具体如下:
public class NotificationUtil {
private Context mContext;
// NotificationManager : 是状态栏通知的管理类,负责发通知、清楚通知等。
private NotificationManager manager;
// 定义Map来保存Notification对象
private Map map = null;
public NotificationUtil(Context context) {
this.mContext = context;
// NotificationManager 是一个系统Service,必须通过 getSystemService()方法来获取。
manager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
map = new HashMap();
}
public void showNotification(int notificationId) {
// 判断对应id的Notification是否已经显示, 以免同一个Notification出现多次
if (!map.containsKey(notificationId)) {
// 创建通知对象
Notification notification = new Notification();
// 设置通知栏滚动显示文字
notification.tickerText = "开始下载xx文件";
// 设置显示时间
notification.when = System.currentTimeMillis();
// 设置通知显示的图标
notification.icon = R.drawable.ic_launcher;
// 设置通知的特性: 通知被点击后,自动消失
notification.flags = Notification.FLAG_AUTO_CANCEL;
// 设置点击通知栏操作
Intent in = new Intent(mContext, MainActivity.class);// 点击跳转到指定页面
PendingIntent pIntent = PendingIntent.getActivity(mContext, 0, in,
0);
notification.contentIntent = pIntent;
// 设置通知的显示视图
RemoteViews remoteViews = new RemoteViews(
mContext.getPackageName(),
R.layout.notification_contentview);
// 设置暂停按钮的点击事件
Intent pause = new Intent(mContext, MainActivity.class);// 设置跳转到对应界面
PendingIntent pauseIn = PendingIntent.getActivity(mContext, 0, in,
0);
// 这里可以通过Bundle等传递参数
remoteViews.setonClickPendingIntent(R.id.pause, pauseIn);
// 设置取消按钮的点击事件
Intent stop = new Intent(mContext, MainActivity.class);// 设置跳转到对应界面
PendingIntent stopIn = PendingIntent
.getActivity(mContext, 0, in, 0);
// 这里可以通过Bundle等传递参数
remoteViews.setonClickPendingIntent(R.id.cancel, stopIn);
// 设置通知的显示视图
notification.contentView = remoteViews;
// 发出通知
manager.notify(notificationId, notification);
map.put(notificationId, notification);// 存入Map中
}
}
public void cancel(int notificationId) {
manager.cancel(notificationId);
map.remove(notificationId);
}
public void updateProgress(int notificationId, int progress) {
Notification notify = map.get(notificationId);
if (null != notify) {
// 修改进度条
notify.contentView.setProgressBar(R.id.pBar, 100, progress, false);
manager.notify(notificationId, notify);
}
}
}
布局文件notification_contentview.xml
Activity中简单测试发通知,项目中根据需要使用,比如文件下载中要更新进度,取消时进行对应操作等。
public class MainActivity extends ActionBarActivity {
private NotificationUtil mNotificationUtil;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNotificationUtil = new NotificationUtil(this);
findViewById(R.id.send).setonClickListener(new onClickListener() {
@Override
public void onClick(View v) {
mNotificationUtil.showNotification(100);// 测试发出通知
}
});
}
}
Android通知功能可以参考前面一篇https://www.jb51.net/article/85807.htm
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。



