《第一行代码》学习笔记31-多媒体(1)

1.通知Notification:当某个应用程序希望向用户发出一些提示信息,而该应用程序又不在前台运行时,可以借助通知实现。发出
一条通知后,手机最上方的状态栏中会显示一个通知图标,下拉状态栏后可以看到通知的详细内容。

2.通知可在活动里创建,可在广播接收器里创建,亦可在服务里创建。

3.创建通知的详细步骤:(源于本书,不过这块已过时
(1)需要NotificationManager对通知管理,调用Context的getSystemService()方法获取到,获取NotificationManager的实例:

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

(2)创建Notification对象,用于存储通知所需的各种信息,使用它的有参构造函数创建。其接收三个参数:第一个用于指定
通知的图标;第二个指定通知的ticker内容,当通知刚被创建的时候,会在系统的状态栏一闪而过,是一种瞬时的提示信息;
第三个指定通知被创建的时间,以毫秒为单位,当下拉系统状态栏时,指定的时间会显示在相应通知上。创建一个Notification对象:

Notification notification = new Notification(R.mipmap.icon, "This is ticker text", System.currentTimeMillis());

(3)创建Notification对象后,对通知的布局进行设定,只需要调用Notification的setLatestEventInfo()方法给通知设置一
个标准的布局。其接收四个参数,第一个是Context;第二个用于指定通知的标题内容,下拉系统状态栏可以看到这部分内容;
第三个用于指定通知的正文内容,同样下拉系统状态栏可以看到这部分内容;第四个暂时用不到,传入null。对通知布局的设定:

notification.setLatestEventInfo(context, "This is content title", "This is content text", null);

(4)以上工作都完成后,调用NotificationManager的notify()方法让通知显示出来。notify()方法接收两个参数,第一个是id,
要注意保证为每个通知所设定的id是不同的;第二个Notification对象,直接传入即可。显示一个通知:

manager.notify(1, notification);

4.Android Studio显示setLatestEventInfo这种方式被废弃!
核心代码:

Notification notification = new Notification(R.mipmap.ic_launcher,
                        "This is ticker text", System.currentTimeMillis());
                notification.setLatestEventInfo(this, "This is content title",
                        "This is content text", null);
                manager.notify(1, notification);

更换成:

Notification.Builder builder = new Notification.Builder(MainActivity.this);
                builder.setSmallIcon(R.mipmap.ic_launcher);
                builder.setTicker("This is ticker text");
                builder.setWhen(System.currentTimeMillis());
                builder.setAutoCancel(true);
                builder.setContentTitle("This is content title");
                builder.setContentText("This is content text");
                Notification n = builder.build();
                manager.notify(1,n);
原文地址:https://www.cnblogs.com/Iamasoldier6/p/5037609.html