通知控件的使用步骤

来源:互联网 发布:wordpress速度优化 编辑:程序博客网 时间:2024/05/17 22:46

创建普通通知的步骤:

1.  定义一个NotificationManager管理器并且实例化

private NotificationManager manager;

manager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

2. 构建通知的Builder(通知的构造器)

NotificationCompat.Builder builder=newNotificationCompat.Builder(this);

3. 设置必要属性

builder.setSmallIcon(R.drawable.ic_launcher);

         builder.setContentTitle("普通的通知");

         builder.setContentText("通知来了");

4.       添加附加属性(可要可不要)

4.1添加声音

                            builder.setSound(Uri.parse("android.resource://"+

                            getPackageName()+

                            "/"+R.raw.a));

           4.2添加滚动

                            builder.setTicker("要滚动的内容");

             4.3点击时跳到另外一个界面

//public static PendingIntent getActivity (Context context, int requestCode, Intent intent, int flags)

//flags有四个取值:

int FLAG_CANCEL_CURRENT:如果该PendingIntent已经存在,则在生成新的之前取消当前的。

int FLAG_NO_CREATE:如果该PendingIntent不存在,直接返回null而不是创建一个PendingIntent.
int FLAG_ONE_SHOT:该PendingIntent只能用一次,在send()方法执行后,自动取消。
int FLAG_UPDATE_CURRENT:如果该PendingIntent已经存在,则用新传入的Intent更新当前的数据。

我们需要把最后一个参数改为PendingIntent.FLAG_UPDATE_CURRENT,这样在启动的Activity里就可以用接收Intent传送数据的方法正常接收。

 

 

                            Intentintent=new Intent(MainActivity.this, Second.class);

                            PendingIntentpIntent=PendingIntent.getActivity(MainActivity.this,100,intent,PendingIntent.FLAG_UPDATE_CURRENT);

                            builder.setContentIntent(pIntent);

5.       Builder创建一个通知对象

Notification notification=builder.build();

6.       发布通知(参数1:通知的id,参数2:通知对象名)

manager.notify(0, notification);


7.取消通知

 mNotifyManager.cancel(0);  

0 0