android 弹出消息框

xiaoxiao2021-02-28  30

那么这种效果是如何实现的呢,其实很简单,这用到了系统中的两个类: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;
转载请注明原文地址: https://www.6miu.com/read-600183.html

最新回复(0)