Notifaction常用的方法
必须要设置前三个,不设置不好用
注意
package com.example.sixnotification; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.NotificationCompat; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { NotificationManager manager; Notification notification; private String channelId = "musichhhh"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获得通知管理器这个对象 manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); //Android8.0以上的适配 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ //创建通知渠道 这三个参数是必须的 现在我们设置这个通知级别是高的 NotificationChannel channel = new NotificationChannel(channelId,"音乐消息",NotificationManager.IMPORTANCE_HIGH); //创建通知渠道的通知管理器 NotificationManager manager1 = getSystemService(NotificationManager.class); //将通知渠道交给管理器 manager1.createNotificationChannel(channel); } //为了setContentIntent这个功能做的activity //PendingIntent是对Intent的封装,但它不是立刻执行某个行为,而是满足某些条件或触发某些事件后才执行指定的行为 Intent intent = new Intent(this, MessageActivity.class); PendingIntent activity = PendingIntent.getActivity(this, 250, intent, 0); //通知管理 notification = new NotificationCompat.Builder(this,channelId) .setContentTitle("官方通知") .setContentText("你的绿钻已到期") .setSmallIcon(R.drawable.ic_audiotrack_black_24dp) .setContentIntent(activity) .build(); } public void sentMessage(View view) { manager.notify(250,notification); } public void cancelSentButton(View view) { manager.cancel(250); //注意昂,这个id要和sentMessage的id一致 } }
<?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" tools:context=".MainActivity"> <Button android:id="@+id/sentButton" android:text="发送通知" android:onClick="sentMessage" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/cancelSentButton" android:text="取消发送" android:onClick="cancelSentButton" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>