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>
相关推荐
NoSi EFUL7 小时前
MySQL中ON DUPLICATE KEY UPDATE的介绍与使用、批量更新、存在即更新不存在则插入
android·数据库·mysql
安小牛9 小时前
Android 开发汉字转带声调的拼音
android·java·学习·android studio
聚美智数9 小时前
企业实际控制人查询-公司实控人查询
android·java·javascript
JMchen12310 小时前
第 3 篇|Android 项目结构解析与第一个界面 —— Hello, CSDN!
android·android studio·android 零基础·android 项目结构·android 界面开发
众少成多积小致巨13 小时前
Soong构建入门
android·go·编译器
笔夏13 小时前
【安卓学习之混淆】记录一些混淆导致闪退
android·学习
阿巴斯甜14 小时前
Kotlin高阶函数和Java 8 lambda的区别:
android
张小潇14 小时前
AOSP15 WMS/AMS系统开发 - WindowManagerService relayout调用流程详解
android
阿巴斯甜14 小时前
Kotlin 高阶函数:
android
之歆14 小时前
Day03_HTML 列表、表格、表单完整指南(下)
android·javascript·html