android通知栏消息
16lz
2021-12-10
android 在通知栏弹出消息, 看了很多博客,方到代码里都略有问题,最后只能去官方文档找示例。
官方文档
这个通知栏既可以通过service触发,也可以通过activity触发。
public class Notify { private NotificationManager manager; private Notification.Builder builder; private Context context; private Notification notification; private String TAG = "notify"; public Notify(Context context){ this.context = context; } @TargetApi(26) public void setNotification(String title, String desc){ manager = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE); // set channel chanenel的创建 String CHANNEL_ONE_ID = "com.zhangshiling.app"; String CHANNEL_ONE_NAME = "Channel One"; NotificationChannel notificationChannel; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { notificationChannel = new NotificationChannel(CHANNEL_ONE_ID, CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH); /*notificationChannel.enableLights(true); notificationChannel.setLightColor(Color.RED); notificationChannel.setShowBadge(true); notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);*/ NotificationManager nm = context.getSystemService(NotificationManager.class); nm.createNotificationChannel(notificationChannel); } Intent intent = new Intent(context, message_list.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); builder = new Notification.Builder(context).setContentTitle(title) .setChannelId(CHANNEL_ONE_ID) .setContentText(desc) .setContentIntent(pendingIntent) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setVibrate(new long[]{0, 1000, 1000, 1000}) //通知栏消息震动 .setLights(Color.GREEN, 1000, 2000) //通知栏消息闪灯(亮一秒间隔两秒再亮) .setDefaults(NotificationCompat.DEFAULT_ALL) .setSmallIcon(R.drawable.small_icon); Log.i(TAG,"after build a builder"); //manager.notify(1, builder.getNotification()); NotificationManagerCompat new_nm = NotificationManagerCompat.from(context); new_nm.notify(1, builder.build()); // 第一个参数1具体实现时 需要修改 用于显示不同消息。 //return builder.getNotification(); } }
在service中
Notify nm = new Notify(this); nm.setNotification(rsp.title, rsp.content);
更多相关文章
- Android(安卓)事件触发机制
- 友盟推送android 8.0系统不显示推送消息问题
- Android(安卓)获取屏幕高宽度,密度,通知栏高度,截图等常用方法
- Android(安卓)按钮点击两次触发不同的事件
- 解析Android消息处理机制:Handler/Thread/Looper & MessageQueue
- Android消息机制不完全解析(上)
- Android(安卓)View类属性及方法
- android 中文 API (41) —— RatingBar.OnRatingBarChangeListen
- 基于MQTT实现Android消息推送(Push)