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>
相关推荐
青莲84327 分钟前
深拷贝 vs 浅拷贝
android
一枚小小程序员哈40 分钟前
基于Android的音乐播放器/基于android studio的音乐系统/音乐管理系统
android·ide·android studio
叽哥1 小时前
flutter学习第 13 节:本地存储
android·flutter·ios
whysqwhw5 小时前
安卓上WebRtc
android
青莲8435 小时前
内联函数 inline noinline crossinline reified
android
wayne2145 小时前
从 MVC 到 MVI:Android 架构演进全景剖析与示例代码
android
我又来搬代码了7 小时前
【Android】【bug】Json解析错误Expected BEGIN_OBJECT but was STRING...
android·json·bug
CANI_PLUS17 小时前
ESP32将DHT11温湿度传感器采集的数据上传到XAMPP的MySQL数据库
android·数据库·mysql
来来走走18 小时前
Flutter SharedPreferences存储数据基本使用
android·flutter
安卓开发者19 小时前
Android模块化架构深度解析:从设计到实践
android·架构