Android-Toast和Notification

来源:互联网 发布:中国网络自由 编辑:程序博客网 时间:2024/06/05 18:41

在Android中Toast和Notification都是用于消息提示。

Toast:


Notification:



下面为实现代码:

分别在布局中设置两个按钮用于实现Toast和Notification

Toast

case R.id.bt_toast:                Toast.makeText(getContext(),"This is a toast demo",Toast.LENGTH_SHORT).show();                break;
Toast实现较简单,调用Toast类的makeText方法,其中LENGTH_SHORT,LENGTH_LONG分别为显示时间长短,大约为3秒和5秒。

在最后一定要调用show()才会显示。


Notification

case R.id.bt_notification:                Notification.Builder builder = new Notification.Builder(getContext());                builder.setContentTitle("Just " + notificationCounter++ + " Notification demo");                builder.setContentText("hello notification");                builder.setSmallIcon(R.mipmap.ic_launcher);                Notification notification = builder.build();                NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);                notificationManager.notify(NOTIFICATION_ID, notification);                break;
创建一个Builder对象来设置Notification的图标,标题,内容摘要,时间等,最后传递给notification,再由notificationManager将notification发出,其中NOTIFICATION_ID表示该通知的ID,便于更改通知的内容等。







0 0
原创粉丝点击