Send an Android Notification before an Activity has been launched

怎甘沉沦 提交于 2019-12-11 13:07:43

问题


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 

来源:https://stackoverflow.com/questions/23809158/send-an-android-notification-before-an-activity-has-been-launched

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!