在启动时启动Android通知

时间:2012-10-16 20:59:17

标签: 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

有关于此的任何想法吗?

要点: 服务或广播接收器更好(在这种情况下)? 如何在我的代码中解决这些错误(当你悬停时他们说它们是未定义的)?

1 个答案:

答案 0 :(得分:3)

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

与活动和服务不同,BroadcastReciever不实现上下文。您遇到错误的所有方法都需要上下文实例