《第一行代码》第8章 --通知的使用修正

cyang Lv6

《第一行代码》第8章的中涉及的通知的基本用法处,由于Notificition已被弃用,所以代码出错。需要更新写法。下面列出的是可用的修正写法。同时,第九章P365页处用到的通知,也需要重新写。

##1、P300 页源码及修正
这里写图片描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Override
private void onClick(View v){
switch (v.getId()){
case R.id.send_notice:
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.s3,"this is ticker text",
System.currentTimeMillis());
notification.setLatestEventInfo(this,"this is title","this is text",null);
manager.notify(1,notification);
break;
default:
break;
}
}

更新为
这里写图片描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.send_notice:
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.s3);
builder.setTicker("just watch me");
builder.setWhen(System.currentTimeMillis());
builder.setContentTitle("look at that");
builder.setContentText("you can do it!");
Intent intent = new Intent(this,NotificationActivity.class);
PendingIntent pi = PendingIntent.getActivity(this,0,intent,
PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(pi);

//Uri soundUri = Uri.fromFile(new File("/system/media/audio/ringtones/Basic_tone.ogg"));
//builder.setSound(soundUri);

//long[] vibrates = {0,1000,1000,1000};
//builder.setVibrate(vibrates);

//builder.setLights(Color.GREEN,1000,1000);
builder.setDefaults(Notification.DEFAULT_ALL);
manager.notify(1, builder.build());
break;
default:
break;

##2、P365 页源码及修正
这里写图片描述

1
2
3
4
5
6
7
Notification notification = new Notification(R.drawable.a10,"Notification comes",
System.currentTimeMillis());
Intent notificationIntent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
notification.setLatestEventInfo(this,"this is title","this is content",pendingIntent);
startForeground(1,notification);
Log.d("MyService","onCreate executed");

更新为:
这里写图片描述

1
2
3
4
5
6
7
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setTicker("just watch me");
builder.setWhen(System.currentTimeMillis());
builder.setContentTitle("look at that");
builder.setContentText("you can do it!");
startForeground(1,builder.build());

原文链接:本人CSDN博客

  • 标题: 《第一行代码》第8章 --通知的使用修正
  • 作者: cyang
  • 创建于 : 2016-06-05 21:24:12
  • 更新于 : 2020-02-19 21:33:54
  • 链接: https://blog.cyang.tech/2016/06/05/《第一行代码》第8章 --通知的使用修正/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
此页目录
《第一行代码》第8章 --通知的使用修正