Android下的多线程断点续传下载,其中用到了通知栏Notificaton,这里写一下基本用法。
Notification notification = new Notification();
notification.tickerText = fileInfo.getFileName() + "正在下载...";//滚动显示的文字
notification.when = System.currentTimeMillis();//时间
notification.icon = R.mipmap.ic_launcher;//通知显示的图标
notification.flags = Notification.FLAG_AUTO_CANCEL;//点击后自动消失
这里需要注意的就是当你通知死活显示不出来的时候,请查看有没有设置icon
点击通知栏的操作
//点击通知栏的操作
Intent intent = new Intent(mContext, MainActivity.class);
PendingIntent pintent = PendingIntent.getActivity(mContext, 0, intent, 0);
notification.contentIntent = pintent;
比如上边的操作就是点击通知栏跳到MainActivity
设置显示的视图
//创建RemoteView (通知显示视图)
RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(), R.layout.notification_item);
其中notification_item 就是显示的布局视图
当然如果你的通知栏中有按钮需要点击事件的话可以这么写:
Intent intentStart = new Intent(mContext, DownLoadService.class);
intentStart.setAction(DownLoadService.ACTION_START);
PendingIntent piStart = PendingIntent.getService(mContext, 0, intentStart, 0);
remoteViews.setOnClickPendingIntent(R.id.btn_notification_start, piStart);
大家一定注意到了,如果你的操作是和Activity相关的话,在获取PendingIntent时使用的是getActivity,相应的Service使用的是getService
设置通知栏的标题
remoteViews.setTextViewText(R.id.tv_name, "TITLE");
最后我们需要把remoteViews设置给contentView
notification.contentView = remoteViews;
发送通知
mNotificationManger = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
//发送通知
mNotificationManger.notify(fileInfo.getId(), notification);
到这里我们的通知栏才真正的显示出来了。
取消通知
mNotificationManger = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManger.cancel(id);
其中id是要取消的通知的id
通知栏中的进度设置
如果我们需要在通知栏中显示一些进度怎么办呢?
notification.contentView.setProgressBar(R.id.pb_download_progress, 100, progress, false);//params: 进度条,最大进度,当前进度,是否显示具体进度
mNotificationManger.notify(id, notification);//id是通知的id
好啦,关于通知的基本用法就介绍到这里。有问题欢迎留言。
更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11
本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-05/144070.htm