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

int*_*_32 2 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);
    }
Run Code Online (Sandbox Code Playgroud)

和

 @Override
    protected void onHandleIntent(Intent intent) {
        startForeground(true);
        ...
Run Code Online (Sandbox Code Playgroud)

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

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

哪里可能是问题?

kle*_*erg 5

如果您正在使用IntentService该服务,则一旦onHandleIntent()方法完成执行就会销毁该服务,然后通知将被删除.