Notification notification = new NotificationCompat.Builder(this, "com.example.myapplication") .setSmallIcon(R.drawable.ic_launcher_background) .setContentTitle("My notification") .setContentText("Hello World!") .addAction(R.drawable.ic_launcher_foreground, "Delete", pendingDeleteIntent) .build(); NotificationManagerCompat.from(this).notify(CHANNEL_CHARGING_NOTIFICATION_ID, notification); No Channel found for pkg=com.example.myapplication
时间: 2024-01-12 09:02:43 浏览: 34
这个错误提示是因为在 Android O 及更高版本中,创建通知时必须指定通知渠道。如果没有为通知指定渠道,则会出现“无法找到渠道”的错误。
您需要在创建通知之前创建一个通知渠道,并将其与通知相关联。以下是一个示例:
```
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel
CharSequence name = "My App Notification Channel";
String description = "My App Notifications";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("com.example.myapplication", name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
// Create the notification and set the channel ID
Notification notification = new NotificationCompat.Builder(this, "com.example.myapplication")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("My notification")
.setContentText("Hello World!")
.addAction(R.drawable.ic_launcher_foreground, "Delete", pendingDeleteIntent)
.build();
// Show the notification
NotificationManagerCompat.from(this).notify(CHANNEL_CHARGING_NOTIFICATION_ID, notification);
```
请注意,这里使用的通知渠道 ID 是 `"com.example.myapplication"`,这是您自己定义的字符串。在创建通知时,需要使用相同的通知渠道 ID。