Android下添加状态栏图标的方法

来源:互联网 发布:怎么申请做淘宝模特 编辑:程序博客网 时间:2024/05/17 08:39
   有时我们听着音乐或者浏览网页什么的,来一条短信或者一封邮件,就会在状态栏显示一个相应的图标,并且在状态窗口添加一条信息。当用户点击这个信息时,android会发送一个intent请求,通常是启动一个已定义的activity。可以添加声音、震动、闪屏给设备来提醒用户。
   通常一个服务后台运行时,如果需要提醒用户一些事件、或者让用户反馈一些信息时,通常用到状态栏提醒。一个后台Service永远不会自己运行一个activity来接收用户交互。一般的,后台服务会添加一个状态栏通知来与用户进行交互。
   因为activity只有在活动状态下才能执行一些命令,所以需要从一个service来建立状态通知。当用户启动了其他程序或者设备已经休眠时,通过这种方式,通知就可以在后台被创建。需要用到的两个类:Notification和NotificationManager。
  Notification类来定义状态通知的属性,比如图标、提示信息,或者提示声音。NotificationManager是一个android系统的服务,用来管理和运行所有的通知,不能被实例化,可以通过getSystemService(Context.NOTIFICATION_SERVICE)方法获得它的句柄。当想通知用户时,调用notify(int,Notification)方法即可;当想取消通知时,调用cancel(int)方法即可。

1.获得NotificationManager的引用
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager =(NotificationManager)getApplicationContext().getSystemService(ns);
2.实例化Notification
int icon = R.drawable.send_sms;
CharSequence tickerText = “sending SMS”;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText,when);
或者
Notification notification = new Notification();
notification .icon = R.drawable.send_sms;
notification.tickerText = “sending SMS”;
notification.defaults = Notification.DEAFULT_SOUND; //默认提示音
这一部分定义的信息都是显示在手机最上面的状态栏里面的。
3.定义Notification,如显示icon、目标intent等信息
Context context = getApplicationContext();
CharSequence contentTitle = “Registered SMS”;
CharSequence contentText = “send the registertion SMS to theCustomer Service”;
Intent notificationIntent = new Intent();
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,notificationIntent, 0);
notification.setLatestEcentInfo(context, contentTitle, contentText,contentIntent);
这一部分定义的信息都是显示在下拉状态栏里面的,即状态窗口里面。
4.传递给NotificationManager
private static final int SALESTRACKER = 100;
notificationManager.notify(SALESTRACKER, notification);
6.取消Notification
notificationManager.cancel(SALESTRACKER);

0 0
原创粉丝点击