gpt4 book ai didi

java - 在启动时启动 Android 通知

转载 作者:行者123 更新时间:2023-12-01 18:59:07 26 4
gpt4 key购买 nike

这个问题基于我之前的问题:Android - Set notification to never go away

我现在意识到我需要在启动时触发一些东西来触发通知。

从我之前的问题来看,我可以采取两条路线。启动服务或使用 BroadcastReceiver。我认为启动服务有点矫枉过正(但我知道什么)。我在使用 BroadcastReceiver 路线时陷入困境。它通常可以工作,但是当我将代码用于通知时,我收到了一堆错误。

这是我的代码:

NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);
//Intent.putExtra("My Notification");
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(i, mBuilder.build());

我的错误: enter image description here

对此有什么想法吗?

摘要:服务或广播接收器哪个更好(在这种情况下)?如何解决代码中的这些错误(当您将鼠标悬停时,它们说它们未定义)?

最佳答案

将错误行上的所有 this 实例替换为 context

BroadcastReciever 不像 Activity 和 Service 那样实现上下文。所有出错的方法都需要上下文实例

关于java - 在启动时启动 Android 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12923311/

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