Android Notificationを使ってステータス通知する方法

参考コード:

package com.ljq.activity;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
clearNotification();
}

@Override
protected void onStop() {
showNotification();
super.onStop();
}

@Override
protected void onStart() {
clearNotification();
super.onStart();
}

/**
* ステータスバーに通知が表示される
*/
private void showNotification(){
// NotificationManager参照を作成
NotificationManager notificationManager = (NotificationManager)
this.getSystemService(android.content.Context.NOTIFICATION_SERVICE);

// Notificationの属性を定義
Notification notification =new Notification(R.drawable.icon,

notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_NO_CLEAR;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults = Notification.DEFAULT_LIGHTS;
//重畳効果定数
//notification.defaults=Notification.DEFAULT_LIGHTS|Notification.DEFAULT_SOUND;
notification.ledARGB = Color.BLUE;
notification.ledOnMS =5000;

//設定された通知イベントメッセージ
CharSequence contentTitle ="通知タイトル";
CharSequence contentText ="通知コンテンツ";
Intent notificationIntent =new Intent(MainActivity.this, MainActivity.class);y
PendingIntent contentItent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, contentTitle, contentText, contentItent);

// NotificationをNotificationManagerに渡す
notificationManager.notify(0, notification);
}
?
//通知を削除
private void clearNotification(){
// 起動した後に通知を削除
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(0);

}
}

 

Source

Posted by arkgame