Send an Android Notification before an Activity ha

2019-08-14 19:47发布

问题:

EDIT: The problem below disappeared with no changes in code. The notifications started appearing properly upon later reboots. This is at most an intermittent issue.

I have an application that starts up a background service when the phone boots. After a certain event is detected, I would like to send a notification to the user, allowing the user to elect to start my MainActivity if the user taps on the notification.

The problem is that Android seems to disallow sending notifications if no Activity has yet been launched. The code below is in a custom android.app.Application class, and works only if the Activity has already been launched.

Is there any way to send a Notification before an Activity has been launched?

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

Here is the error:

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