Android 上未显示通知

Notification not being shown on Android

我正在构建一个简单的应用程序,其目的是在应用程序启动后立即显示通知。

按照 Android 文档中描述的步骤,我编写了一个名为 createNotification 的方法来设置通知,并将对该方法的调用插入 onCreate方法,我想在应用程序启动后不久就会被调用。

然而,应用程序启动时没有显示任何通知。我想知道代码有什么问题。

public class MainActivity extends ActionBarActivity {
    // ...

    protected void onCreate(Bundle savedInstanceState) {
        // ...

        createNotification();
    }

    private void createNotification() {

        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setAutoCancel(true)
        .setWhen(System.currentTimeMillis())
        .setVisibility(Notification.VISIBILITY_PUBLIC); 

        Intent resultIntent = new Intent(this, MainActivity.class);

        PendingIntent resultPendingIntent = 
                PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentIntent(resultPendingIntent);

        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(1, builder.build());

    }

}

the docs

Required notification contents

A Notification object must contain the following:

  • A small icon, set by setSmallIcon()
  • A title, set by setContentTitle()
  • Detail text, set by setContentText()

如果你添加一个 smallIcon,例如 android.R.drawable.ic_dialog_alert 它会起作用(我刚刚测试过)。您当然也可以添加自己的图标,但我使用它是因为它是内置的,对于示例来说非常容易。

像这样

NotificationCompat.Builder builder =
        new NotificationCompat.Builder(this)
                .setContentTitle("My notification")
                .setContentText("Hello World!")
                .setAutoCancel(true)
                .setSmallIcon(android.R.drawable.ic_dialog_alert) // Add this line
                .setWhen(System.currentTimeMillis())
                .setVisibility(Notification.VISIBILITY_PUBLIC);

我必须说,我觉得很奇怪,当你不添加 smallIcon 时它不显示错误或任何东西。