创建通知

参考(https://www.jianshu.com/p/6aec3656e274

项目中需要用到通知,因此本次将简单总结一下,如何快速在8.0以上创建通知。

效果图。

创建代码如下:

public class MainActivity extends AppCompatActivity {
   
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
   
        btn=findViewById(R.id.btn_create);
        btn.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "发送通知", Toast.LENGTH_SHORT).show();
                createNotification();
            }
        });

    }

    private void createNotification() {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //通知渠道的ID
        String id = "channel_011";
        CharSequence name = getString(R.string.app_name);
        //用户可看到的通知描述
        String description = getString(R.string.app_name);
        //构建NotificationChannel实例
        NotificationChannel notificationChannel =
                new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
        //配置通知渠道的属性
        notificationChannel.setDescription(description);
        //在notificationManager中创建通知渠道
        manager.createNotificationChannel(notificationChannel);

        Notification notification = new NotificationCompat.Builder(MainActivity.this, id)
                .setContentTitle("今天头条")
                .setContentText("今天深圳大部分地区下特大暴雨,其他地区也行会出现冰雹")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .build();
        manager.notify(1, notification);
    }

默认情况下,通知的文字内容会被截断以放在一行。如果您想要更长的通知,可以使用 setStyle() 添加样式模板来启用可展开的通知

Notification notification = new NotificationCompat.Builder(MainActivity.this, id)
.setContentTitle("今天头条")
.setContentText("今天深圳大部分地区下特大暴雨,其他地区也行会出现冰雹")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)

.setStyle(new NotificationCompat.BigTextStyle()
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.build();

补充:由于通道是8.0以后才引入的,因此8.0以下没有相应的类,因此当使用通道时,需要使用如下判断:

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

..............................

      // 创建通知

扫描二维码关注公众号,回复: 11173292 查看本文章

}

原创文章 29 获赞 1 访问量 9268

猜你喜欢

转载自blog.csdn.net/qinxuexiang_blog/article/details/103437990