android Notification

来源:互联网 发布:cellsens成像软件 编辑:程序博客网 时间:2024/05/21 09:50

android Notification 的使用:

Broadcast Receiver 组件并没有提供可视化的UI来显示信息, 我们可以使用 Notification 和NotificationManage 来实现可视化的信息通知, 通过使用Notification 可以实现显示广播信息的内容 图标 和振动 等信息.

使用Notification 比较简单,一般获得系统级的服务NotificationManage , 然后 实例化 Notification ,设置其属性 ,通过NotificationManage 发出通知就可以了. 

下面来看具体实现的 小例子 :

package com.app;import android.app.Activity;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.app.Service;import android.content.Context;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button;public class NotificationActivity extends Activity { Button button1,button2 ; NotificationManager nm; Notification notification; private final static int ID =1;    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        button1  = (Button) findViewById(R.id.button1);        button2  = (Button) findViewById(R.id.button2);        String service = Context.NOTIFICATION_SERVICE;        nm =(NotificationManager) getSystemService(service);    button1.setText("发出通知");    button2.setText("取消通知");        button1.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {noti(); }});        button2.setOnClickListener(new View.OnClickListener() {                public void onClick(View v) {        nm.cancel(ID);        }        });    }        private void noti() {    notification = new Notification();    notification.icon=R.drawable.ic_launcher;    notification.tickerText="收到新短信";    notification.when=System.currentTimeMillis();    //notification.defaults |= Notification.DEFAULT_LIGHTS;//闪光灯    notification.defaults |= Notification.DEFAULT_SOUND;//系统默认提示音   // notification.defaults |= Notification.DEFAULT_VIBRATE;//震动    //震动/*    long[] vibrate = {0,100,200,300};    notification.vibrate = vibrate;*/    //闪光灯    /*notification.ledARGB = 0xff00ff00;    notification.ledOnMS = 300;    notification.ledOffMS = 1000;    notification.flags |= Notification.FLAG_SHOW_LIGHTS;*/        PendingIntent contentIntent =   PendingIntent.getActivity(this,     0, new Intent(), 0);    notification.setLatestEventInfo(this, "短信标题", "短信内容---", contentIntent);    nm.notify(ID,notification);}}