java - 在启动时启动 Android 通知

标签 java android broadcastreceiver android-service android-notifications

这个问题基于我之前的问题: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/

相关文章:

java - Android 的最佳 OpenGL ES 语法

android - 关闭 fragment 时如何使用导航体系结构组件隐藏键盘

android - 如何知道从 Android BroadcastReceiver 发送/传递了哪些 Sms?

android - 如何监控android中的浏览内容?

java - Android Studio - 权限拒绝,需要 android.permission.RECEIVE_SMS 错误

java - Android 通知监听器服务自行启动

java - 为什么复制对象不会影响第一个对象?

java - 静态与非静态误差

android - 使用 Android NDK 时,Eclipse 编辑器将无法识别 C++ 模板类型

android - 如何检查 Intent ( Activity )的包名称(Espresso)中是否包含字符串?