Android 中状态栏(屏幕顶部)消息的显示 Notification

在系统停留在其他页面时,如果发来一条短信会看到如图的情况:

那么这种效果是如何实现的呢,其实很简单,这用到了系统中的两个类:Notification和NotificationManager

一个简单例子:

1、布局文件

android:orientation="vertical" android:layout_width="fill_parent"

android:layout_height="fill_parent">

2、代码

public class MianActivity extends Activity {

/** Called when the activity is first created. */

NotificationManager nm = null;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

public void click(View v) {

switch (v.getId()) {

case R.id.send:

String service = Context.NOTIFICATION_SERVICE;         

nm = (NotificationManager) getSystemService(service);          //获得系统级服务,用于管理消息

Notification n = new Notification();                                        //定义一个消息类

n.icon = R.drawable.icon;                                                //设置图标

n.tickerText = "Notification Test!!";                                        // 设置消息

n.when = System.currentTimeMillis();                             //设置时间

// Notification n1 =new Notification(icon,tickerText,when);    //也可以用这个构造创建

Intent intent = new Intent(MianActivity.this, MianActivity.class);       

PendingIntent pi = PendingIntent.getActivity(MianActivity.this, 0,intent, 0);       //消息触发后调用

n.setLatestEventInfo(MianActivity.this, "my title", "my content",pi); //设置事件信息就是拉下标题后显示的内容

nm.notify(1, n);      //发送通知

break;

case R.id.cancel:

nm.cancel(1);           //关闭通知

}

}

}

运行效果如下:

正如上边截图那样,可以为Notification对象设置图标、显示文字等信息,除了这些还有很多属性可以用来提醒。如:声音、震动、闪光灯等。设置方式如下:

1、播放音乐

     n.defaults |= Notification.DEFAULT_SOUND;

     n.sound=Uri.parse("file:///sdcard/sound.mp3");

     n.sound=Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");

2、振动

     n.defaults|=Notification.DEFAULT_VIBRATE;

     long[] vib={0,50,100,150,200};

     n.vibrate=vib;

     记得加权限:

3、闪光灯

n.defaults|=Notification.DEFAULT_LIGHTS;

     n.ledARGB=0x99f0ff00;

n.ledOnMS=300;

     n.ledOffMS=2000;

     n.flags|=Notification.FLAG_SHOW_LIGHTS;

你可能感兴趣的:(android,相关知识)