Android开发通知栏的那些事开发通知栏的那些事
对于通知栏的使用,Android各个版本其实都有比较大的调整。例如老版本的不兼容,大小图标问题以及自定义通知栏适配问
题,这些都是比较头大的事,当然弄懂了就清楚了,本篇就处理下这些疑惑。
通知栏的使用通知栏的使用
显示一个普通的通知栏显示一个普通的通知栏
public static void showNotification(Context context) {
Notification notification = new NotificationCompat.Builder(context)
/**设置通知左边的大图标**/
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
/**设置通知右边的小图标**/
.setSmallIcon(R.mipmap.ic_launcher)
/**通知首次出现在通知栏,带上升动画效果的**/
.setTicker("通知来了")
/**设置通知的标题**/
.setContentTitle("这是一个通知的标题")
/**设置通知的内容**/
.setContentText("这是一个通知的内容这是一个通知的内容")
/**通知产生的时间,会在通知信息里显示**/
.setWhen(System.currentTimeMillis())
/**设置该通知优先级**/
.setPriority(Notification.PRIORITY_DEFAULT)
/**设置这个标志当用户单击面板就可以让通知将自动取消**/
.setAutoCancel(true)
/**设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同
步操作,主动网络连接)**/
.setOngoing(false)
/**向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合:**/
.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
.setContentIntent(PendingIntent.getActivity(context, 1, new Intent(context, MainActivity.class), PendingIntent.FLAG_CANCEL_CURRENT))
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
/**发起通知**/
notificationManager.notify(0, notification);
}
显示一个下载带进度条的通知显示一个下载带进度条的通知
public static void showNotificationProgress(Context context) {
//进度条通知
final NotificationCompat.Builder builderProgress = new NotificationCompat.Builder(context);
builderProgress.setContentTitle("下载中");
builderProgress.setSmallIcon(R.mipmap.ic_launcher);
builderProgress.setTicker("进度条通知");
builderProgress.setProgress(100, 0, false);
final Notification notification = builderProgress.build();
final NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
//发送一个通知
notificationManager.notify(2, notification);
/**创建一个计时器,模拟下载进度**/
Timer timer = new Timer();
timer.schedule(new TimerTask() {
int progress = 0;
@Override
public void run() {
Log.i("progress", progress + "");
while (progress <= 100) {
progress++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//更新进度条
builderProgress.setProgress(100, progress, false);
//再次通知
notificationManager.notify(2, builderProgress.build());
}
//计时器退出
this.cancel();
//进度条退出
notificationManager.cancel(2);
return;//结束方法