1. 程式人生 > 其它 >9.基本控制元件 Notification

9.基本控制元件 Notification

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>