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>
相关推荐
Geeker555 小时前
如何在忘记密码的情况下解锁Android手机?
android·网络·macos·华为·智能手机·电脑·手机
wxx21506 小时前
【android】【adb shell】写一个shell脚本,监听进程pid变化
android·adb
心死翼未伤7 小时前
【MySQL基础篇】多表查询
android·数据结构·数据库·mysql·算法
喂_balabala7 小时前
Android手机拍照或从本地相册选取图片设置头像-高版本适配
android·开发语言
_小马快跑_9 小时前
Android | StandardCharsets.UTF_8.toString() 遇到的兼容问题记录
android
wxx215010 小时前
【Android】【多屏】多屏异显异触调试技巧总结
android
人民的石头12 小时前
Android增量更新----java版
android
Geeker5513 小时前
如何在忘记密码的情况下删除华为ID激活锁
android·运维·服务器·网络·macos·华为·智能手机
XD74297163615 小时前
【Android】ADB 使用指南
android·adb
骨子里的偏爱15 小时前
uniapp/Android App上架三星市场需要下载所需要的SDK
android·uni-app