Android8.0以后带通道的通知创建流程

以下写法不规范,只是为了能发送通知,把所有东西全部都写再Activity中了:

流程如下:

  1. 通过getSystemService()获得 Notificationmanager 对象manager。
  2. 创建NotificationChannel类对象 channel
  3. 将channel传入manager 的createNotificationChannel 方法中
  4. 通过new NotificationCompat.Builder().builder() 创建Notification对象 notification。
  5. 将notification 和通知id传入manager.notify()方法中。

具体代码如下

public class MainActivity extends AppCompatActivity {

    private NotificationManager manager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button send = findViewById(R.id.buttonsend);
        String channelId = "chat";
        String channelName = "聊天消息";
        int importance = NotificationManager.IMPORTANCE_HIGH;

        manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);//第一步
        NotificationChannel channel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {//
            channel = new NotificationChannel(channelId,channelName,importance);//第二步
            manager.createNotificationChannel(channel);//第三步
        } else {
            Log.d("MainActivity", "error ");
        }
        final Notification notification = new NotificationCompat.Builder(this,channelId)//第四步
                .setAutoCancel(true).setContentTitle("收到聊天消息")
                .setContentText("今天晚上吃什么")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                //设置红色
                .setColor(Color.parseColor("#F00606"))
                .build();
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("MainActivity", "onClick: ");
                manager.notify(1,notification);         //第五步
                //Toast.makeText(MainActivity.this,"H",Toast.LENGTH_SHORT).show();
            }
        });
    }
}

参考链接
https://blog.youkuaiyun.com/qq_35507234/article/details/90676587

官网的详细介绍
https://developer.android.com/training/notify-user/build-notification.html#java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值