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>
相关推荐
Dreamboat¿1 小时前
解析PHP安全漏洞:Phar反序列化、Filter链与文件包含的高级利用与防御
android·网络·php
周杰伦的稻香3 小时前
MySQL中常见的慢查询与优化
android·数据库·mysql
他们叫我技术总监4 小时前
Python 列表、集合、字典核心区别
android·java·python
2401_882351528 小时前
Flutter for OpenHarmony 商城App实战 - 地址编辑实现
android·java·flutter
42nf8 小时前
Android 根据platform.pk8和platform.x509.pem生成.jks文件
android·.pk8和.pem生成.jks
摘星编程9 小时前
React Native for OpenHarmony 实战:DisplayInfo 显示信息详解
android·react native·react.js
_李小白9 小时前
【Android 美颜相机】第六天:GPUImageView解析
android·数码相机
Mr_sun.10 小时前
Day04——权限认证-基础
android·服务器·数据库
北辰当尹12 小时前
第27天 安全开发-PHP应用&TP框架&路由访问&对象操作&内置过滤绕过&核心漏洞
android·安全·php