Android 之 Notification 通知消息
程序员文章站
2022-05-16 09:05:31
...
NotificationManager是显示在手机状态栏的消息,如短息提醒等,做得大点,可以做消息推送等。下面的实例程序示范了如何通过NotificationManager来发送、取消Notification,本程序的界面很简单,只是包含了两个按钮,分别用于发送Notification和取消Notification,主要的java代码如下:
notification.java:
package com.example.notification; import android.os.Bundle; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity implements OnClickListener{ static final int NOTIFICATION_ID = 0x1123; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button b1=(Button)findViewById(R.id.b1); b1.setOnClickListener((View.OnClickListener) this); Button b2=(Button)findViewById(R.id.b2); b2.setOnClickListener((View.OnClickListener) this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.b1: Intent intent = new Intent(); intent.setClass(MainActivity.this, other.class); PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0); Notification notify = new Notification(); notify.icon = R.drawable.no; notify.tickerText = "自己做的消息呀"; notify.when = System.currentTimeMillis(); notify.defaults = Notification.DEFAULT_ALL; notify.setLatestEventInfo(MainActivity.this, "站内信", "五一放假通知", pi); NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); notificationManager.notify(NOTIFICATION_ID, notify); break; case R.id.b2: NotificationManager notificationmanager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); notificationmanager.cancel(NOTIFICATION_ID); break; } } }
other.java
package com.example.notification; import android.app.Activity; import android.os.Bundle; public class other extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.otherx); } }
运行效果图:
点击开始推送后:
附件是源码,需要的请下载。
推荐阅读
-
Android消息通知栏的实现方法介绍
-
android自定义view之模拟qq消息拖拽删除效果
-
.NET平台下,钉钉微应用开发之:工作消息通知
-
突袭HTML5之Javascript API扩展5—其他扩展(应用缓存/服务端消息/桌面通知)
-
Android开发笔记之:消息循环与Looper的详解
-
Android Handler之消息循环的深入解析
-
Android中通过Notification&NotificationManager实现消息通知
-
Android开发之React Navigation 导航栏样式调整+底部角标消息提示
-
Android编程实现google消息通知功能示例
-
Android系统修改之Notification布局修改(一)