Notification が通知されない

知り合いがハマってたので書いておきます。

問題

Notification が表示されない。文法的には正しいし、エラーを吐いているようでもないんだけど…。

解決策

Notification.Builder#setSmallIcon() を呼びましょう。
Android で Notification を利用する際は、 SmallIcon を設定しないと通知がされないです。「通知は文字列だけでいいんだけど」という場面もありそうな気はしますけどね。

API ドキュメントには特に記載がありませんが、 Building a Notification | Android Developers の方に書いてあります。
このドキュメントを読むと、以下の 3 つが必須だということがわかりますね。

  • setSmallIcon()
  • setContentTitle()
  • setContentText()

サンプル

package foo.bar;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class MainActivity extends Activity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button buttonNotify = (Button) findViewById(R.id.button_notify);
        buttonNotify.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Intent intent = new Intent(this, NextActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        Notification notification = new Notification.Builder(this)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setTicker("ティッカーだよ。")
                .setContentText("コンテントテキストだよ。")
                .setContentInfo("コンテントインフォだよ。")
                .setContentTitle("コンテントタイトルだよ。")
                .setWhen(System.currentTimeMillis())
//                .setSmallIcon(R.drawable.my_icon)   // SmallIcon を設定しないと通知されない(例外も発生しない)
                .build();

        notificationManager.notify(0, notification);
    }
}