程序介绍:
调用getSystemService(NOTIFICATION_SERVICE)方法获取系统的NotifacationManager服务
通过构造器创建一个Notification对象
为Notification设置各种属性
通过NotificationManager发送Notification。
pendingIntent是在点击通知的时候所触发的Intent事件
Intent intent = new Intent(MainActivity.this,Hello.class);
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
PendingIntent与Intent的区别: http://blog.csdn.net/stven_king/article/details/38014727
效果图:
初始状态: 点击发送:
查看通知: 点击通知:
主程序:
package com.example.notificationdemo;
import javax.xml.transform.Source;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
static final int NOTIFICATION_ID = 0x123;
NotificationManager nm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
public void send(View source){
Intent intent = new Intent(MainActivity.this,Hello.class);
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
Notification notification = new Notification.Builder(this).setAutoCancel(true).setTicker("有新消息").setSmallIcon(R.drawable.email01)
.setContentTitle("有一条新消息").setContentText("恭喜您,您中奖了,奖金500万!").setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS)
.setWhen(System.currentTimeMillis()).setContentIntent(pi).build();
nm.notify(NOTIFICATION_ID, notification);
}
public void del(View source){
nm.cancel(NOTIFICATION_ID);
}
}