andoid中的通知

来源:互联网 发布:iphone视频截图软件 编辑:程序博客网 时间:2024/06/06 17:12

1.Toast通知  

  • 创建通知

Toast.makeText(Context context, CharSequence text, int duration)

Toast.makeText(Context context, int resId, int duration)

  • 发送通知

show()


2. 状态栏通知

直接代码说明,这里先介绍一下Notification的flag与pendingIntent

Notification的flag

FLAG_AUTO_CANCEL: 通知点击后会被自动取消掉

FLAG_FOREGROUND_SERVICE :通知代表当前运行的一个服务

FLAG_HIGH_PRIORITY: 通知高优先级

FLAG_INSISTENT :主要设置音频,音频将被重复,直到通知取消或通知窗口打开

FLAG_NO_CLEAR : 通知点击后不会被清掉

FLAG_ONGOING_EVENT :代表一个正在运行的事件

FLAG_ONLY_ALERT_ONCE :通知来时震动和声音提醒只有一次,

FLAG_SHOW_LIGHTS 三色灯提醒


PendingIntent是一个Intent的描述、包装,给予了这个PendingIntent 的组件在指定的事件发生或指定的时间到达时启动Activty、Service或者Broadcast。

FLAG_CANCEL_CURRENT :  如果指定的PendingIntent已经存在,则取消掉当前的重新建一个

FLAG_NO_CREATE:如果指定的PendingIntent不存在,就返回空

FLAG_ONE_SHOT: 指定的PendingIntent只会被用一次

FLAG_UPDATE_CURREN: 重用当前的pendingIntent,并更新数据


例:

    //旧方法发送通知

    public void sendNotification1(View v) {

  Notification notification = new Notification(R.drawable.ic_launcher, //通知的图片资源ID

    "HelloWord", //状态栏中显示的消息内容

    System.currentTimeMillis());

  Intent intent = new Intent(this, SecondActivity.class); //要启动的控件意图

  PendingIntent pendingIntent = PendingIntent.getActivity(this, //当前上下文

    100, //请求码

    intent, //点击时要发送的意图

    PendingIntent.FLAG_ONE_SHOT  //类型

    ); //

  notification.setLatestEventInfo(this,

    "下载完成2", "HelloWord2", pendingIntent); //设置提醒的内容

  notification.flags = Notification.FLAG_AUTO_CANCEL;

  NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

  manager.notify(0, notification);

 }

 

//新方法:使用 NotificationCompat.Builder

 public void sendNotification2(View v) {

  NotificationCompat.Builder mBuild =

    new NotificationCompat.Builder(this);

  mBuild.setSmallIcon(R.drawable.ic_launcher)

   .setTicker("notificationName") //状态栏中显示的消息内容

   .setContentTitle("HelloWordTitle") //设置提醒标题

   .setContentText("HelloWorld") //设置提醒内容

   .setContentInfo("Hellworld1");  //设置提醒信息

 

  Intent intent = new Intent(this, SecondActivity.class); //要启动的控件意图

  TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

  stackBuilder.addNextIntent(intent);

  PendingIntent pendingIntent = stackBuilder.getPendingIntent(100, PendingIntent.FLAG_ONE_SHOT);

  mBuild.setContentIntent(pendingIntent);

  NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

  Notification notification = mBuild.build();

  notification.flags = Notification.FLAG_ONLY_ALERT_ONCE ; //点击后通知不会被请掉

  manager.notify(0, notification);

 }




0 0
原创粉丝点击