简介:
Notification —— 通知,是一种让你的应用程序在不使用Activity的情况下警示用户。它是看不见的程序组件(Broadcast Receiver,Service和不活跃的Activity)警示用户有需要注意的事件发生的最好途径。 Notification 是由NotificationManager(系统服务)统一管理的。
Android中如何发送一个通知?
1>获取系统服务NotificationManager。
2>构建一个Notification对象。Notification.Builder
3>调用manager.notify(Notification)方法发送通知。
package com.example.android_day08_notification;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doClick(View view){
switch (view.getId()) {
case R.id.button1:
clearNotification();
sendNotification();
break;
case R.id.button2:
//清除通知
clearNotification();
break;
}
}
private void clearNotification() {
//1> 获取NotificationManager对象
NotificationManager manager=(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
//2.清除通知
manager.cancel(111);
}
/**
* 发送通知
*/
int number=1;
private void sendNotification() {
//1> 获取NotificationManager对象
NotificationManager manager=(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
//2> 构造Notification对象
Builder builder=new Builder(this);
builder.setContentInfo("ContentInfo....")//内容信息
.setContentText("ContentText..."+number++)//内容文本
.setContentTitle("ContentTitle...") //内容标题
.setLargeIcon(BitmapFactory.decodeResource(
getResources(), R.drawable.ic_launcher))//大图标
.setShowWhen(true)//是否显示时间
.setWhen(System.currentTimeMillis())//时间毫秒值
.setSmallIcon(R.drawable.ic_launcher)//小图标必须设置
.setSubText("subText...")//小文本
.setTicker("这是滚动消息..."); //滚动消息
//添加通知的点击意图
Intent i=new Intent(this, MainActivity.class);
PendingIntent pi=PendingIntent.getActivity(this, 0, i, 0);
builder.setContentIntent(pi);
Notification n=builder.build();
//测试notification的常见属性 常驻通知栏属性
n.flags=Notification.FLAG_NO_CLEAR;
//3> 调用manager.notify
manager.notify(111, n);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
如何使用代码清除通知?
NotificationManager manager=(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(id);
如何使通知常驻通知栏?
notification.flags=Notification.FLAG_NO_CLEAR;
如何更新Notification上面的内容?
1> 重新发送一条新内容的通知即可。
(使用同一个id)
如何点击通知后响应点击意图?
//添加通知的点击意图
Intent i=new Intent(this, MainActivity.class);
//(context,请求码无所谓,intent对象,常量)
PendingIntent pi=PendingIntent.getActivity(this, 0, i, 0);
builder.setContentIntent(pi);