通知領域に通知メッセージを表示する - Android

Android端末の通知領域に通知メッセージを表示するコードを紹介します。
Androidアプリケーションプロジェクトを新規作成します。

プロジェクトの設定

  • Project name: SimpleNotification
  • Build Target: Android 2.3.3
  • Application name: SimpleNotification
  • Package name: iPentec.SimpleApp.SimpleNotification
  • Activity: SimpleNotificationActivity

UI

下図のUIを準備します。

コード

SimpleNotificationActivity.java

package iPentec.SimpleApp.SimpleNotification;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.*;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;


public class SimpleNotificationActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }
    
  public void button1_click(View view){
    String url = "http://www.ipentec.com/document/document.aspx?page=index";
    Uri uri = Uri.parse(url);

    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
    	
    NotificationManager manager 
      = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification();
    	
    notification.flags = Notification.FLAG_AUTO_CANCEL;
    notification.icon = R.drawable.ic_launcher;
    notification.tickerText = "通知メッセージ";
    notification.setLatestEventInfo(
      getApplicationContext(), "通知タイトル", "通知のメッセージ本文", pendingIntent);
    	
    manager.notify(1,notification);
  }
}

解説

String url = "http://www.ipentec.com/document/document.aspx?page=index";
Uri uri = Uri.parse(url);
通知領域のメッセージをクリックした際に表示するURLページのUriクラスのインスタンスを作成します。URLの文字列からUri.parseメソッドを用いて作成します。

Intent intent = new Intent(Intent.ACTION_VIEW, uri);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
通知領域をクリックした際のインテントとペンディングインテントを作成します。

NotificationManager manager 
  = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification();
通知領域のメッセージ管理クラス(NotificationManager)を取得します。また、通知メッセージクラス(Notification)クラスを作成します。

notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.icon = R.drawable.ic_launcher;
notification.tickerText = "通知メッセージ";
notification.setLatestEventInfo(
  getApplicationContext(), "通知タイトル", "通知のメッセージ本文", pendingIntent);
通知領域メッセージの各種オプションを設定します。

manager.notify(1,notification);
通知メッセージ管理クラス(NotificationManager)のnotify()メソッドを呼び出し、通知メッセージクラス(Notification)を引数に与えることで、通知領域にメッセージを表示します。

実行結果

アプリケーションを実行します。下図の画面が表示されます。画面のボタンをタップします。


ボタンがタップされると上部のバー部分に通知メッセージが表示されます。


バー部分を下に向けてフリックすると通知領域が表示され通知メッセージの一覧を確認できます。


通知メッセージをクリックすると指定されたURLをWebブラウザで表示します。

著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2024-01-04
作成日: 2012-02-08
iPentec all rights reserverd.