android 弹出消息框

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

1、布局文件


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">

<Button android:id="@+id/send" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="发送通知"
android:onClick="click"></Button>

<Button android:layout_width="fill_parent" android:id="@+id/cancel"
android:layout_height="wrap_content" android:text="取消通知"
android:onClick="click"></Button>

</LinearLayout>

2、代码


public class MianActivity extends Activity {
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;
     记得加权限:<uses-permission android:name="android.permission.VIBRATE"></uses-permission>
3、闪光灯
n.defaults|=Notification.DEFAULT_LIGHTS;
     n.ledARGB=0x99f0ff00;
n.ledOnMS=300;
     n.ledOffMS=2000;
     n.flags|=Notification.FLAG_SHOW_LIGHTS; 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值