本文共 2729 字,大约阅读时间需要 9 分钟。
在 Android 开发中,Notification 是一种强大的 UI 组件,能够将应用的状态信息反馈给用户。通过发送 Notification,可以在系统的通知栏中显示图标提示,用户可以通过拉下来信息查看详情。
要创建一个基本的 Notification,主要需要设置以下属性:
setSmallIcon()
方法设置。setContentTitle()
方法设置。setContentText()
方法设置。宏观来看,这三个属性是核心配置,缺一不可。此外,为了让 Notification 与用户交互,可以通过设置 Action 来实现跳转指定页面、启动服务或发送广播。可以通过 setContentIntent()
方法设置 Pending Intent,用来指定点击后要执行的操作。
此外,Notification
对象可以通过 setDefaults()
方法设置一些默认属性,如震动、响铃等效果。但需要注意,一旦设置默认属性,自定义效果将失效。
在 Notification 中,大图标可以通过 setLargeIcon()
方法设置。如果同时设置小图标和大图标,小图标会显示在右侧,largeIcon 则会放在左侧。
以下是代码示例:
Resources res = getResources();NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.small_icon) .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable_large_icon)) .setContentTitle("标题") .setContentText("内容");Notification notification = builder.build();mNotificationManager.notify(TAG, 0, notification);
为了使 Notification具备交互能力,需要设置相应的 Pending Intent。例如,要启动 MainActivity,可以这样做:
PendingIntent mainPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);Notification notification = ... .setContentIntent(mainPendingIntent);
clicking the notification 将会以 mainPendingIntent
为目标执行。
如果需要让 Notification 有一些特殊效果,可以设置以下 Flags:
此外,想让 Notification 有震动或响铃效果,可以通过 setVibrate()
或 setDefaultSound()
等方法设置。
严重的是,设置默认效果时(如 Notification.DEFAULT_VIBRATE
或 Notification.DEFAULT_SOUND
),自定义设置将失效。
如果需要在 Notification 中显示进度条,可以这样做:
private void showProgressBarNotification() { count++; NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("带进度条的通知") .setContentText("进度: " + count + "/" + 100) .setProgress(100, count, false); mNotification = builder.build(); mNotificationManager.notify(TAG, 0, mNotification);}
与此同时,可以使用 Handler 定时更新进度条:
final Runnable updateProgress = new Runnable() { @Override public void run() { showProgressBarNotification(); if (count < 100) { postDelayed(updateProgress, 200); } }};
最终,可以通过点击动画效果取自应用自身资源。
此外,需要注意的是,通知栏的清除按钮可以清除任何可清除 notifications。如果要自定义清除行为,可以设置 setAutoCancel(true)
,然后单击通知即可清除。
通过以上方法,可以非常方便地创建和定制 Notification。无论是单纯的信息通知,还是带有进度条/图片或与用户交互的通知,都可以通过 NotificationCompat.Builder readily配置。当然,在实际开发中,还需要考虑权限申请(如震动权限)以及兼容不同的安卓版本的问题。
转载地址:http://zgauk.baihongyu.com/