android被设计为运行在便携式设备上,可以被携带到任何地方,在不定时的时候使用。为了让用户更好的使用这个设备,Android提供了一系列通知机制来保证用户可以马上意识到任何事件的发生。
Toast
toast是最基本的通知。它是一个简单的消息,会出现在屏幕一段很短的事件,通常是5到10秒。
Context context = getApplicationContext();
CharSequence text = “Hello toast!”;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Status bar notification
通知托盘是android最主要的通知方式。它由一个图标,标题和消息内容组成,你可以设置以下几个基本元素:
1、显示在状态栏的图标。
2、当通知第一次显示时,在状态栏显示的文字(可选)。
3、显示在通知托盘的标题和文字。(可选)
4、一个当用户点击通知时触发的PendingIntent。
NotificationManager nm = (NotificationManager) p getSystemService(NOTIFICATION_SERVICE);
Context context = getApplicationContext();
CharSequence message = “Hello World!”;
Intent intent = new Intent(this, Example.class);
String title = “Hello World!”;
String message = “This is a message.”;
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,p intent, 0);
notification.setLatestEventInfo(context, title, message,p pendingIntent);
nm.notify(ID, notification);
除了更新状态栏的通知托盘,你还可以在通知到来时发出声音,闪动led,震动手机。Android3.0之后,提供了Notification.Builder类来创建通知。
Dialogs
对话框是出现在屏幕上的一个小窗口,用来实现用户和app的交互。
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.confirm_clear_all_title)
.setMessage(R.string.confirm_clear_all_message)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.create();
}