Android(安卓)通知Notification
16lz
2021-01-26
在通知栏弹出发出的消息;类似于接受信息等等的一些小demo;
需要的activity_main.xml
[html] view plain copy
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
- <Button
- android:id="@+id/send"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="发送通知"/>
- <Button
- android:id="@+id/clear"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="清除通知"/>
一个小demo。点击 发送通知 按钮,则发送通知到设备的通知栏。点击 清除通知 则清除通知栏上的消息通知。
[java] view plain copy
- packagezhangphil.notification;
- importandroid.os.Bundle;
- importandroid.view.View;
- importandroid.widget.Button;
- importandroid.app.Activity;
- importandroid.app.Notification;
- importandroid.app.NotificationManager;
- importandroid.support.v4.app.NotificationCompat;
- publicclassMainActivityextendsActivity{
- privatefinalintNOTIFICATION_ID=105;
- @Override
- protectedvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Buttonsend=(Button)findViewById(R.id.send);
- send.setOnClickListener(newView.OnClickListener(){
- @Override
- publicvoidonClick(Viewv){
- sendNotification();
- }
- });
- Buttonclear=(Button)findViewById(R.id.clear);
- clear.setOnClickListener(newView.OnClickListener(){
- @Override
- publicvoidonClick(Viewv){
- clearNotification();
- }
- });
- }
- privatevoidsendNotification(){
- NotificationManagernotificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
- NotificationCompat.BuildermBuilder=newNotificationCompat.Builder(
- this);
- mBuilder.setSmallIcon(R.drawable.ic_launcher);
- mBuilder.setContentTitle("通知的标题");
- mBuilder.setContentText("通知的内容");
- Notificationnotification=mBuilder.build();
- //缺省设置为当发送通知到通知栏时候:提示声音+手机震动
- notification.defaults=Notification.DEFAULT_SOUND
- |Notification.DEFAULT_VIBRATE;
- //通知的时间
- notification.when=System.currentTimeMillis();
- //发送到手机的通知栏
- notificationManager.notify(NOTIFICATION_ID,notification);
- }
- privatevoidclearNotification(){
- NotificationManagernotificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
- notificationManager.cancel(NOTIFICATION_ID);
- }
- }
更多相关文章
- Android(安卓)使用Socket实现服务器与手机客户端的长连接一:一对
- Android设置中清除应用数据源码分析
- Android(安卓)IQ包 发送 基于XMPP
- Android(安卓)Handler(四)
- Android(安卓)USB Host与HID通讯(二)
- SpringBoot webSocket 发送广播、点对点消息,Android接收
- Android定义定时器实现定时任务(亲测可用)
- android常用的API接口调用
- Android(安卓)Handler机制5--消息发送