android - 通知不会出现在前台服务中

标签 android android-service android-notifications

我正在使用以下代码:

private void startForeground(boolean isActive) {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(getString(isActive ? R.string.title_agent_active : R.string.title_agent_inactive))
                .setContentIntent(pendingIntent)
                .build();

        startForeground(1, notification);
    }

 @Override
    protected void onHandleIntent(Intent intent) {
        startForeground(true);
        ...

使用此代码通知不会出现。

但是如果我用 NotificationManager.notify(...) 替换 startForeground(...) — 它会显示通知,所以我认为至少通知构建代码是可以的。

问题出在哪里?

最佳答案

如果您使用的是 IntentService,则服务将在 onHandleIntent() 方法完成执行后立即销毁,然后通知将被删除。

关于android - 通知不会出现在前台服务中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35034037/

相关文章:

android - Latlng Bound 返回 0.0

android - 如何为自定义 Android 通知向 RemoteView 添加垂直线?

android - 应用关闭时未触发通知

Android Wear - 通知标题格式

android - 如果应用程序位于前台,则通知 ParentStack 重新启动父级

java - 通知未显示在锁定屏幕上

android - Bottom Sheet 全屏显示

java - 让事情去中心化 Android

android - 在应用程序类中绑定(bind) Android 服务是个好主意吗?

java - startForeground 错误的错误通知,看不到修复