NotificationManager manager =(NotificationManager)まずは、ノーティフィケーション全体を管理するNotificationManagerを取得します。これは、Activityの「getSystemService」メソッドで行います。引数に、NOTIFICATION_SERVICEを指定することでNotificationManagerが得られます。
getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.icon;ノーティフィケーション作成に必要な情報を用意します。まず、表示するアイコンのリソース。ここでは、とりあえずR.drawable.iconでアプリのデフォルトアイコンを使っています。そして、情報バーに表示するメッセージと、現在のタイムスタンプの値です。
CharSequence msg = "情報バーに表示する!";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, msg, when);ノーティフィケーションを作成します。これは、new Nofiricationで作ることができます。引数には、先ほどのアイコン、メッセージ、現在のタイムスタンプの値を渡します。
notification.flags = Notification.FLAG_AUTO_CANCEL;作成したNotificationの挙動を設定します。ここではflagsにFLAG_AUTO_CANCELを設定しています。これで、ノーティフィケーションをタップしたら、自動的にキャンセルされ、一覧から消えるようになります。
Intent nIntent = new Intent(this, SampleApp.class);;PendingIntentを作成します。これは、PendingIntent.getActivityメソッドで用意します。引数には、Content、リクエストコード番号、インテント、フラグといったものが渡されます。リクエストコードとフラグはいずれもゼロでOKです。またContextはthisでよいでしょう。
PendingIntent pIntent = PendingIntent.getActivity(this, 0, nIntent, 0)
Context context = getApplicationContext();ノーティフィケーションとして引き出しに表示される内容として必要な値を用意しておきます。Context、タイトルのテキスト、本文のメッセージテキストなどです。
CharSequence title = "sample Notify!";
CharSequence content = "これがノーティフィケーションだ!";
notification.setLatestEventInfo(context, title, content, pIntent);「setLatestEventInfo」で、Notificationにイベント情報を設定します。用意しておいた値をそれぞれ引数に渡しておきます。
manager.notify(1, notification);これで準備完了です。後は、「notify」を呼び出して、ノーティフィケーションを表示させるだけです。引数には、ID番号とPendingIntentを渡します。これでPendingIntentの設定内容に従ってノーティフィケーションのためのインテントが起動され、情報バーにメッセージが表示されます。
※リストが表示されない場合
AddBlockなどの広告ブロックツールがONになっているとリストなどが表示されない場合があります。これらのツールをOFFにしてみてください。
package jp.tuyano; import android.app.*; import android.content.*; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class SampleApp extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btn = (Button)this.findViewById(R.id.btn); btn.setOnClickListener(this); } @Override public void onClick(View v) { NotificationManager manager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); int icon = R.drawable.icon; CharSequence msg = "情報バーに表示する!"; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, msg, when); notification.flags = Notification.FLAG_AUTO_CANCEL; Intent nIntent = new Intent(this, SampleApp.class); PendingIntent pIntent = PendingIntent.getActivity(this, 0, nIntent, 0); Context context = getApplicationContext(); CharSequence title = "sample Notify!"; CharSequence content = "これがノーティフィケーションだ!"; notification.setLatestEventInfo(context, title, content, pIntent); manager.notify(1, notification); } }
<< 前へ |