我有以下叫做AlarmNotificationReceiver的类。 想法是在设备关闭时发送通知。似乎有些事情是错误的,因为这并没有发生。有什么想法吗?
public class AlarmNotificationReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentTitle("HEY I WAS INITIALIZED!");
builder.setContentText("Good luck");
builder.setSmallIcon(R.drawable.alert_icon);
builder.setAutoCancel(true);
builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.notif_red));
//notification manager
Notification notification = builder.build();
NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
manager.notify(1234, notification);
}
}
}
我还在清单中添加了以下行:
<receiver android:name=".AlarmNotificationReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
答案 0 :(得分:1)
您缺少通知渠道的创建。您可以按如下方式创建通知:
public class AlarmNotificationReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
...
createNotificationChannel(context);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,1000);
...
}
}
private void createNotificationChannel(final Context context) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "ChannelName";
String description = "Channel description";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(1000, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}