Android为Notification提供了Notification.Builder类,通过该类允许开发者更轻松的创建Notification对象。Notification.Builder提供了如下方法。
- setDefault():设置通知LED灯,音乐,震动。
- setAutoCancel():设置点击通知后,状态栏自动删除通知。
- setContentTitle():设置通知标题。
- setContentText():设置通知内容。
- setSmallIcon():设置通知图标。
- setLargeIcon():设置通知大图标。
- setTick():设置通知在状态栏的提示文本。
- setContentIntent():设置点击通知后要启动的程序组件对应的PendingInent。
发送Notification的步骤:
- 调用getSystemServices(NOTIFICATION_SERVICE)方法获取系统的NotificationManager服务。
- 创建NotificationChannel对象,并在NotificationManager上创建该Channel对象。
- 通过构建器创建一个Notification.Builder对象。
- 为Notification.Builder设置通知的各种属性。
- 创建MessagingStyle和Message,通过Message设置消息内容,为Notification.Builder设置MessagingStyle后创建Notification.
- 通过NotificationManager发送Notification。
package com.example.helloworld;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Person;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
public static final int NOTIFICATION_ID =0x123;
public static final String CHANNEL_ID = "lytcoding";
private NotificationManager nm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取系统的NotificationManager对象
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//设置channel名字
String name = "test channel";
//创建NotificationChannel对象
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,name,NotificationManager.IMPORTANCE_HIGH);
//设置channel的描述信息
channel.setDescription("测试Channel的描述信息");
//设置闪光灯
//channel.enableLights(true);
//channel.setLightColor(Color.RED);
//设置震动
//channel.enableVibration(true);
//channel.setVibrationPattern(new Long[]{0L,50L,100L,150L});
//在NotificationManager上创建该通知channel
nm.createNotificationChannel(channel);
Button sendNotification = (Button) findViewById(R.id.SendNotification);
sendNotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
send();
}
});
}
public void send(){
Person p = new Person.Builder()
.setName("曹操")
.build();
//设置通知的参与者
Notification.MessagingStyle messagingStyle = new Notification.MessagingStyle(p);
//设置标题
messagingStyle.setConversationTitle("一条新的通知");
//创建一条消息
Notification.MessagingStyle.Message message =
new Notification.MessagingStyle.Message("胜利了,大家一起庆祝!!",System.currentTimeMillis(),p);
//添加消息
messagingStyle.addMessage(message);
Notification notify = new Notification.Builder(this,CHANNEL_ID)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setStyle(messagingStyle)
.build();
//发送通知
nm.notify(NOTIFICATION_ID,notify);
}
}
2355



被折叠的 条评论
为什么被折叠?



