Android 第四十五章 Notification

java 复制代码
public class MainActivity extends AppCompatActivity {

    private Button btn_common;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        initClick();
    }

    private void initView() {
        btn_common = findViewById(R.id.btn_common);
    }

    private void initData() {
    }

    private void initClick() {
        btn_common.setOnClickListener(v -> {
            initNotification();
        });
    }

    private void initNotification() {
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("channel_id", "test_name", NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(channel);
        }
        Notification notification = new NotificationCompat.Builder(this, "channel_id")
                .setSmallIcon(R.mipmap.ic_test)// 设置通知图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_test))
                .setContentTitle("标题")// 设置通知的标题
                .setContentText("内容。。。")// 设置通知的内容
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true)
                .setOngoing(true)
                .setContentIntent(pendingIntent)
                .build();
        manager.notify(1, notification);
    }
}
xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_common"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="发送通知"
        android:textSize="30sp" />


</LinearLayout>
相关推荐
Xempastissimo32 分钟前
Android常见界面控件
android
法欧特斯卡雷特34 分钟前
从 Kotlin 编译器 API 的变化开始: 2.3.20
android·后端·开源
词元Max2 小时前
1.5 Harness 架构深度解析:Claude Code 为什么强?
android·架构
yy55272 小时前
Mysql 主从复制与读写分离
android·数据库·mysql
zhenxin01223 小时前
万字详解 MySQL MGR 高可用集群搭建
android·mysql·adb
做萤石二次开发的哈哈3 小时前
萤石云硬件接入如何完成云对讲套件低代码集成?
android·低代码·rxjava
恋猫de小郭4 小时前
2026 AI 时代下,Flutter 和 Dart 的机遇和未来发展,AI 一体化
android·前端·flutter
缺土的鲨鱼辣椒5 小时前
Android 资源类型概述
android
sp425 小时前
安卓原生 MQTT 通讯 Java 实现
android
PD我是你的真爱粉5 小时前
MySQL 事务与并发控制:从日志底层到 MVCC 哲学
android·mysql·adb