以下写法不规范,只是为了能发送通知,把所有东西全部都写再Activity中了:
流程如下:
- 通过getSystemService()获得 Notificationmanager 对象manager。
- 创建NotificationChannel类对象 channel
- 将channel传入manager 的createNotificationChannel 方法中
- 通过new NotificationCompat.Builder().builder() 创建Notification对象 notification。
- 将notification 和通知id传入manager.notify()方法中。
具体代码如下
public class MainActivity extends AppCompatActivity {
private NotificationManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button send = findViewById(R.id.buttonsend);
String channelId = "chat";
String channelName = "聊天消息";
int importance = NotificationManager.IMPORTANCE_HIGH;
manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);//第一步
NotificationChannel channel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {//
channel = new NotificationChannel(channelId,channelName,importance);//第二步
manager.createNotificationChannel(channel);//第三步
} else {
Log.d("MainActivity", "error ");
}
final Notification notification = new NotificationCompat.Builder(this,channelId)//第四步
.setAutoCancel(true).setContentTitle("收到聊天消息")
.setContentText("今天晚上吃什么")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
//设置红色
.setColor(Color.parseColor("#F00606"))
.build();
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("MainActivity", "onClick: ");
manager.notify(1,notification); //第五步
//Toast.makeText(MainActivity.this,"H",Toast.LENGTH_SHORT).show();
}
});
}
}
参考链接
https://blog.youkuaiyun.com/qq_35507234/article/details/90676587
官网的详细介绍
https://developer.android.com/training/notify-user/build-notification.html#java