Notification基本通知的两种写法

本文详细介绍了如何在Android应用中创建并发送通知,包括构建通知Builder对象、设置通知参数、创建意图对象、添加到任务堆栈、设置内容意图以及发送通知的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private void newNotify() {
        // 1.创建通知的Builder对象
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this);

        //2.设置参数   对象链式操作
        mBuilder.setSmallIcon(R.drawable.ic_launcher); //设置小图标
        mBuilder.setContentTitle("hello title"); //设置标题
        mBuilder.setContentText("Hello content");//设置内容

        //3.创建一个意图对象
        Intent resultIntent = new Intent(this, OtherActivity.class);

        //4.创建TaskStackBuilder对象
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        //5.添加到stackBuilder对象中
        stackBuilder.addParentStack(OtherActivity.class);

        //6.添加到顶端
        stackBuilder.addNextIntent(resultIntent);


        //7.意图对象
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
        //8.设置意图对象
        mBuilder.setContentIntent(resultPendingIntent);

        // 9.获取NotificationManager对象
       NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        //10.发送通知
       mNotificationManager.notify(mId, mBuilder.build());
    }


    private void oldNotify() {
        // 1.获取NotificationManager对象
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 2.定义通知
        Notification notification = new Notification();
        // 3.设置参数
        notification.icon = R.drawable.ic_launcher; // 设置图标
        notification.when = System.currentTimeMillis(); // 发送通知的时间
        // 定义意图
        Intent intent = new Intent(this, OtherActivity.class);
        // 意图 :跨进程的意图
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

        // 设置通知的最新事件消息
        notification.setLatestEventInfo(this, "hello title", "hello content",
                pendingIntent);
        // 3.发通知
        manager.notify(1, notification);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值