温馨提示×

android notification怎么使用

小亿
106
2023-08-24 01:54:25
栏目: 编程语言

要使用Android通知,您可以按照以下步骤操作:

  1. 创建一个NotificationCompat.Builder对象:使用NotificationCompat.Builder类创建通知对象,并设置一些基本属性,比如标题、内容、图标等。
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My Notification")
.setContentText("This is a notification message");
  1. 设置通知行为:您可以设置通知的行为,比如点击通知后打开一个Activity、发送广播等。
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
  1. 显示通知:使用NotificationManager类将通知显示出来。
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, builder.build());

以上代码中,notificationId是一个用于区分不同通知的整数值。

此外,您还可以设置其他属性,比如声音、震动、大文本样式、进度等。

希望这可以帮助到您。

0