在学习《第一行》代码的时候,学到使用通知章节时书上的代码不能在手机上显示通知。
原因:NotificationCompat.Builder()
过时
解决办法:android 8.0 在NotificationCompat.Builder()
中添加一个chanlId
参数,在写的时候添加上。
在每次使用通知时对系统版本进行判断(否则会报错)8.0及以上需要设好“channelId”(唯一与后面的NotificationCompat.Builder()
相同)、“channelName”(用户看得到的信息)、“importance”(重要等级)这三个重要参数,然后创建到NotificationManager
//MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendNotice =(Button) findViewById(R.id.send_notic);
sendNotice.setOnClickListener(this);
}
@Override
public void onClick(View v){
switch (v.getId()){
case R.id.send_notic:
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//需添加的代码
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
String channelId = "default";
String channelName = "默认通知";
manager.createNotificationChannel(new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH));
}
//
Notification notification =new NotificationCompat.Builder(this,"default")
.setContentTitle("This is content title")
.setContentText("this is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.build();
manager.notify(1,notification);
break;
default:
break;
}
}
}