Notification的主要方法的使用和解释见代码:
public class NotificationActivity extends Activity implements View.OnClickListener{
private Button send,cancel;
private NotificationManager nm;
// 定义一个Notification的标识ID
private final int NOTIFICATION_ID = 0x111;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
send = (Button) findViewById(R.id.send);
cancel = (Button) findViewById(R.id.cancel);
// 获得通知管理器,用于后面发送通知
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
send.setOnClickListener(this);
cancel.setOnClickListener(this);
}
public void send(){
Intent intent = new Intent(NotificationActivity.this,SearchViewActivity.class);
PendingIntent pi = PendingIntent.getActivity(NotificationActivity.this,0,intent,0);
Notification notify = new Notification.Builder(NotificationActivity.this)
// 设置通知点击后自动消失
.setAutoCancel(true)
// 设置通知状态栏提示信息
.setTicker("新消息")
// 设置通知的图标
.setSmallIcon(R.mipmap.ic_launcher)
// 设置通知内容的标题
.setContentTitle("一条新的通知")
// 设置通知的内容
.setContentText("恭喜你被BAT争相聘用!!")
// 设置通知来时的提示声音
.setDefaults(Notification.DEFAULT_SOUND)
// 设置点击通知要启动的程序
.setContentIntent(pi)
// 创建此Notification
.build();
// 发送通知
nm.notify(NOTIFICATION_ID,notify);
}
public void cancel(){
nm.cancel(NOTIFICATION_ID);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.send:
send();
break;
case R.id.cancel:
cancel();
break;
}
}
}
界面布局就两个Button,一个用于发送通知,一个取消通知