在活动发布之前发送Android通知

时间:2014-05-22 14:06:05

标签: android notifications android-service android-notifications

编辑:下面的问题消失了,代码没有变化。通知在以后重新启动时开始正常显示。这至多是一个间歇性问题。

我有一个应用程序在手机启动时启动后台服务。在检测到某个事件后,我想向用户发送通知,允许用户选择在用户点击通知时启动我的MainActivity。

问题是,如果尚未启动任何活动,Android似乎不允许发送通知。下面的代码位于自定义android.app.Application类中,仅在已启动“活动”时才有效。

在推出活动之前有没有办法发送通知?

NotificationCompat.Builder builder =
        new NotificationCompat.Builder(this)
                .setContentTitle("Event Detected")
                .setContentText("Tap to launch MainActivity")
                .setSmallIcon(R.drawable.ic_launcher);

TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
PendingIntent resultPendingIntent =
        stackBuilder.getPendingIntent(
                0,
                PendingIntent.FLAG_UPDATE_CURRENT
        );
builder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
        (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());

这是错误:

05-20 09:09:42.084: W/ContextImpl(801): Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:1505 com.android.server.StatusBarManagerService.sendNotification:981 com.android.server.StatusBarManagerService.addNotification:670 com.android.server.NotificationManagerService$7.run:2142 android.os.Handler.handleCallback:733 

0 个答案:

没有答案