通知可以在活动,内容提供器,服务,广播接收器里创建。
1、调用 Context的getSystemService(Context.NOTIFICATION_SERVICE)方NotificationManager 来对通知进行管理
2、创建Notification对象,存储通知的各种信息
3、Intent:倾向立即执行某个动作
PendingIntent :倾向某个时机去执行某个动作,延时执行
静态方法获取不同类型的请求:getActivity(),getBroadcast(),getService()
4、设定通知的布局,调用
Notification 的 setLatestEventInfo()方法
5、调用 NotificationManager 的 notify()方法显示通知
NotificationActivity
public class NotificationActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification_layout);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(1);//取消通知
}
}
public class MainActivity extends Activity implements OnClickListener {
private Button sendNotice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendNotice = (Button) findViewById(R.id.send_notice);
sendNotice.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.send_notice:
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(
R.drawable.ic_launcher, "This is ticker text",
System.currentTimeMillis());
//Uri soundUri = Uri.fromFile(new File("/system/media/audio/ringtones/Basic_tone.ogg"));
//notification.sound = soundUri;
//long[] vibrates = {0, 1000, 1000, 1000};
//notification.vibrate = vibrates;//震动
//notification.ledARGB = Color.GREEN;//led灯
//notification.ledOnMS = 1000;
//notification.ledOffMS = 1000;
//notification.flags = Notification.FLAG_SHOW_LIGHTS;
notification.defaults = Notification.DEFAULT_ALL;
//想要启动NotificationActivity
Intent intent = new Intent(this, NotificationActivity.class);
//将构建好的 Intent 对象传入到 PendingIntent 的 getActivity()方法里
PendingIntent pi = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
//布局
notification.setLatestEventInfo(this, "This is content title",
"This is content text", pi);
//显示通知
manager.notify(1, notification);
break;
default:
break;
}
}
}
结果: