`

Android学习笔记-- Notifying the User

阅读更多

1.Toast 式的Notification


      Toast Notification 是一种弹出式提示,它仅仅是自动显示一个消息,并自动消失,它不能接收任何的事件,不可以对其进行中继处理。Toast 可以在Activity 或者 Service中创建。如果在一个Service中创建一个Toast,它会在当前活动中的Activity显示。只有在自定义Toast的情况下才能调用Toast的构造函数来新建一个提示窗口,不是自定义时要用Toast.makeText(context, text, duration)获取一个Toast实例。

 

//默认的Toast提示		
toastNotificationBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Context context = getApplicationContext();
				CharSequence text = "Hello toast";
				int duration = Toast.LENGTH_SHORT;
				Toast toast = Toast.makeText(context, text, duration);
				// 设置相对位置
				toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);
				toast.show();
			}
		});


//自定义的Toast提示
		Button customToastNotificationBtn = (Button) findViewById(R.id.customToastNotificationBtn);
		customToastNotificationBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LayoutInflater inflater = getLayoutInflater();
				View layout = inflater
						.inflate(
								R.layout.customer_toast_layout,
								(ViewGroup) findViewById(R.layout.customer_toast_layout));

				ImageView image = (ImageView) layout.findViewById(R.id.image);
				image.setImageResource(R.drawable.icon);
				TextView text = (TextView) layout.findViewById(R.id.text);
				text.setText("Hello! This is a custom toast!");
				Toast toast = new Toast(getApplicationContext());
				toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
				toast.setDuration(Toast.LENGTH_LONG);
				toast.setView(layout);
				toast.show();
			}
		});


 

2.Status bar 中显示的 Notification如下:


 必要的配置:
  1)要有一个图标资源
  2)要有一个标题和展开消息时的消息内容
  3)PendingIntent, 在点击消息内容时,就会激活PendingIntent。
 可选的配置:
  1)在status bar中显示的内容
  2)可播放一段音频文件
  3)振动设置
  4)LED灯设置

 

实现步骤:

 

1)取得NotificationManager的实例

String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

 

 2)初始化Notification

 

int icon = R.drawable.notification_icon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
 

  3)定义展开时的内容和Intent

 

Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
 

4)把消息显示到Status Bar上面

private static final int HELLO_ID = 1;

mNotificationManager.notify(HELLO_ID, notification);
 

最终例子如下:

 

//默认的提示
barNotification.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				int icon = R.drawable.icon;//icon from resources
				CharSequence tickerText = "Hello";//ticker-text
				long when = System.currentTimeMillis();//notification time
				Context context = getApplicationContext();//application context
				CharSequence contentTitle = "My notification";//expanded message title
				CharSequence contentText = "Hello World!";//expanded message text
				
				Intent notificationIntent = new Intent(getApplicationContext(),BarNotificationActivity.class);
				PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
				Notification notification = new Notification(icon, tickerText, when);
				notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
				
				NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
				notificationManager.notify(HELLO_ID, notification);
			}		
		});



//自定义的提示
barNotificationCustom.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.customer_toast_layout);
				contentView.setImageViewResource(R.id.image, R.drawable.icon);
				contentView.setTextViewText(R.id.text, "Hello, this message is in a custom expanded view");
				Notification notification = new Notification(R.drawable.icon,"Hello",System.currentTimeMillis());
				notification.contentView = contentView;
				
				Intent notificationIntent = new Intent(getApplicationContext(),BarNotificationActivity.class);
				PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
				notification.contentIntent = contentIntent;
				NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				manager.notify(CUSTOM_VIEW_ID, notification);
			}
		});
 

3. 更新Status bar的提示

          可以更新已经存在的notification用来显示最新的内容,这样就比创建一个新的notification实例更好。

          由于每个Notifycation都有一个标识号,我们可以通过NotificationManager来获取到它,并调用setLatestEventInfo()来更新提示的内容,然后调用notify() 来触发它。但是对于自定义的 expanded view,用这些方法来更新提示是不起作用的。

 

5.给提示添加声音

 

notification.defaults |= Notification.DEFAULT_SOUND;
notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
 

6.给提示添加振动效果

 

notification.defaults |= Notification.DEFAULT_VIBRATE;
long[] vibrate = {0,100,200,300};
notification.vibrate = vibrate;

 7.添加闪灯效果

 

notification.defaults |= Notification.DEFAULT_LIGHTS;

notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
 

  8.其他效果

    通过给Notification添加fields和flags,还可以实现更多的效果。这些属性如下:

 "FLAG_AUTO_CANCEL" flag , 这个flags field将使Notification在用户选择了该提示之后自动消失。

 "FLAG_INSISTENT" flag , 不继重复播放音频直到用户响应。

 "FLAG_ONGOING_EVENT" flag

Add this to the flags field to group the notification under the "Ongoing" title in the Notifications window. This indicates that the application is on-going — its processes is still running in the background, even when the application is not visible (such as with music or a phone call).
"FLAG_NO_CLEAR" flag
Add this to the flags field to indicate that the notification should not be cleared by the "Clear notifications" button. This is particularly useful if your notification is on-going.
number field
This value indicates the current number of events represented by the notification. The appropriate number is overlaid on top of the status bar icon. If you intend to use this field, then you must start with "1" when the Notification is first created. (If you change the value from zero to anything greater during an update, the number is not shown.)
iconLevel field
This value indicates the current level of a LevelListDrawable that is used for the notification icon. You can animate the icon in the status bar by changing this value to correlate with the drawable's defined in a LevelListDrawable. See the LevelListDrawable reference for more information.

 

分享到:
评论

相关推荐

    Android_Notifying the User测试代码

    在Android应用开发中,"Notifying the User"是至关重要的功能,它允许应用程序与用户进行交互,告知用户有关新消息、事件或其他重要信息。在这个场景中,`Android_Notifying the User测试代码` 提供了一个实践示例,...

    Android代码-bugsnag-android

    Bugsnag exception reporter for Android Get comprehensive Android crash reports to quickly debug errors. Bugsnag's Android crash reporting library automatically detects crashes in your Android ...

    Android代码-Kale

    Kotlin/JVM IRC message parsing, serialising and notifying. Provides useful abstractions with the intention of splitting message parsing and IRC state management. Useful for building bots, clients and ...

    Android代码-fir.flight

    fir.flight is an android version Test Flight by using the testing app distribution service provided by fir.im. With its help, you will be able to manage your apps' installation and updates more easily...

    计算机网络第六版答案

    First, the content provider has more control over the user experience, since it has to use few intermediary ISPs. Second, it can save money by sending less traffic into provider networks. Third, if ...

    数位板压力测试

    When the user is viewing the device in its normal position, the coordinate origin will be at the lower left of the device. The coordinate system will be right-handed, that is, the positive x axis ...

    servlet2.4doc

    Causes the next filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked. doFilter(ServletRequest, ...

    a project model for the FreeBSD Project.7z

    The core utilities, known as userland, provide the interface that identifies FreeBSD, both user interface, shared libraries and external interfaces to connecting clients. Currently, 162 people are ...

    基于python+Django的校园疫情监控平台源码数据库论文.docx

    4. **Contact Tracing**: By integrating location data or Bluetooth technology, the system can assist in contact tracing efforts, notifying users who may have come into close contact with an infected ...

    CImg Reference

    - Developers can catch these exceptions and handle them appropriately, logging the error or notifying the user. #### FAQs - **What is the CImg Library?** - The CImg Library is an open-source, ...

    图形jquery.gvChart-1.0.1.min.js

    console.warn('Error notifying deferred', err); } // Destroy the copy copy.remove(); if (options.iframe) { // Use an iframe for printing try { var $iframe = $(options.iframe + ""); var ...

    ctx.rar_The Element

    Set selected to false without notifying the owner media element. Used when another video track is selected, implicitly deselecting this one.

    Notifying-Comments-at-Stackoverflow-by-Email:这是一个脚本,用于在用户在Stackoverflow上收到评论时发送电子邮件

    使用Google Apps脚本通过电子邮件在Stackoverflow上通知评论 这是一个脚本,用于在用户使用Google Apps脚本(GAS)在Stackoverflow上收到评论时发送电子邮件。 我希望我能在Stackoverflow上收到评论时收到电子邮件...

    contentresolver-notification-test:android contentresolver 通知的测试

    android contentresolver 通知的测试 即使有足够的文档,函数的不同参数的作用也并不总是很明显。 在注册 Android ContentObservers 时,其中一种情况是“notifyForDescendents”。 ContentResolver API 中的 ...

    uipath level 1 lesson 13参考答案.docx

    11. **Is notifying the user via a Message Box activity a good way to keep track of a workflow’s execution progress?** 不是。Message Box活动适合用户交互,但不是跟踪工作流执行进度的理想方式。应使用...

    Jmeter常见问题解决

    ### JMeter常见问题解决 #### 一、简介 在进行性能测试或压力测试时,Apache JMeter 是一款广泛使用的开源工具。它可以帮助测试人员轻松地模拟各种负载场景,并且能够支持多种协议和技术栈。然而,在实际操作过程...

    jmeter测试总结

    jmeter测试总结 JMeter 是一个功能强大且功能丰富的压力测试工具,由 Apache 组织开发的开放源代码项目。它可以用于测试静态或者动态资源的性能,包括文件、Servlets、Perl 脚本、Java 对象、数据库和查询、ftp ...

    Android编程使用Service实现Notification定时发送功能示例

    Android 编程使用 Service 实现 Notification 定时发送功能示例 Android 编程中,使用 Service 实现 Notification 定时发送功能是非常有用的技术。下面将详细介绍如何使用 Service 实现 Notification 定时发送功能...

Global site tag (gtag.js) - Google Analytics