gpt4 book ai didi

java - 如何在启动完成时发送通知?

转载 作者:行者123 更新时间:2023-11-30 10:14:24 25 4
gpt4 key购买 nike

我有以下名为 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);
}
}
}

我还在 list 中添加了以下几行:

    <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>

最佳答案

您缺少通知 channel 的创建。您可以按如下方式创建通知:

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);
}
}
}

关于java - 如何在启动完成时发送通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50901809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com