Android Notification 通知的使用以及自定義通知

如何發送一個通知?

Android 8版本之前:

第一步:獲取NotificationManager

mNotificationManager = (NotificationManager)activity.getSystemService(NOTIFICATION_SERVICE);

第二步:構建一個Notification的builder用於構建Notification

Notification.Builder builder=new Notification.Builder(activity);
builder.setContentTitle("測試  "+mNotificationId) //必須提供
                        .setContentText("測試內容") //必須提供
                        .setTicker("測試通知到達")
                        .setWhen(System.currentTimeMillis())
                        .setPriority(Notification.PRIORITY_DEFAULT)//設置該通知優先級
                        .setSmallIcon(R.mipmap.ic_launcher_round) //必須提供
                        .setOngoing(true)           //  設置常駐用戶無法清除
                        .setContentIntent(intent);   //用於點擊通知跳轉界面

第三步:調用NotificationManager的notify函數,傳入一個int類型id(用於標識通知)和一個Notification對象

mNotificationManager.notify(mNotificationId++, builder.build());

Android 8版本之後:

大體步驟沒什麼區別,多了個Channel通道

mNotificationManager = (NotificationManager) activity.getSystemService(NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,"my_channel",NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true); //是否在桌面icon右上角展示小紅點
channel.setLightColor(Color.GREEN); //小紅點顏色
channel.setShowBadge(true); //是否在久按桌面圖標時顯示此渠道的通知
mNotificationManager.createNotificationChannel(channel);//創建Channel

builder需要設置Channel

 builder.setContentTitle("測試  "+mNotificationId) //必須提供
                        .setContentText("測試內容") //必須提供
                        .setTicker("測試通知到達")
                        .setWhen(System.currentTimeMillis())
                        .setPriority(Notification.PRIORITY_DEFAULT)//設置該通知優先級
                        .setSmallIcon(R.mipmap.ic_launcher_round) //必須提供
                        .setOngoing(true)           //  設置常駐用戶無法清除
                        .setContentIntent(intent)   //用於點擊通知跳轉界面
                        .setChannelId(CHANNEL_ID); //Android O以上版本必須提供

同樣是調用notify開啓一個通知

mNotificationManager.notify(mNotificationId++, builder.build());

添加點擊通知跳轉Activity:

創建一個Intent

mIntent=new Intent();
mIntent.setClass(activity,SecondActivity.class);

創建一個PendingIntent:

PendingIntent intent=PendingIntent.getActivity(activity,0,mIntent,0);

在builder中setContentIntent

builder.setContentTitle("測試  "+mNotificationId) //必須提供
                        .setContentText("測試內容") //必須提供
                        .setTicker("測試通知到達")
                        .setWhen(System.currentTimeMillis())
                        .setPriority(Notification.PRIORITY_DEFAULT)//設置該通知優先級
                        .setSmallIcon(R.mipmap.ic_launcher_round) //必須提供
                        .setOngoing(true)           //  設置常駐用戶無法清除
                        .setContentIntent(intent)   //用於點擊通知跳轉界面
                        .setChannelId(CHANNEL_ID); //Android O以上版本必須提供

清除一個消息:傳給NotificationManager一個啓動時的ID即可刪除

mNotificationManager.cancel(mNotificationId-1);

清除所有消息:

mNotificationManager.cancelAll();

演示效果:

 

擴展:自定義Notification的View視圖實現QQ音樂播放功能

第一步:準備我們的佈局文件,這個佈局文件有特殊要求:
僅支持FrameLayout、LinearLayout、RelativeLayout三種佈局控件
AnalogClock、Chronometer、Button、ImageButton、ImageView、ProgressBar、TextView、ViewFlipper、ListView、GridView、StackView和AdapterViewFlipper這些顯示控件
使用其他View會引起ClassNotFoundException異常。

仿QQ音樂Notification佈局如下

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    >
    <ImageView
        android:id="@+id/title_icon"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:src="@drawable/title_icon"
        android:layout_marginStart="16dp" />
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_toRightOf="@+id/title_icon"
        android:layout_marginRight="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="16dp"
        android:layout_toEndOf="@+id/title_icon">
        <TextView
            android:id="@+id/song_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="七里香"
            android:textSize="20sp"
            android:textStyle="bold"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginStart="16dp" />
        <TextView
            android:id="@+id/singer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="周杰倫"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="4dp"
            android:layout_below="@+id/song_title"
            android:layout_marginStart="16dp" />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/singer"
            android:weightSum="5"
            android:orientation="horizontal"
            >
            <Button
                android:id="@+id/love"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/song_like"
                android:textColor="@android:color/holo_red_light"
                android:background="@android:color/transparent"
                />
            <Button
                android:id="@+id/song_back"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/song_back"
                android:textSize="16sp"
                android:textColor="@android:color/black"
                android:background="@android:color/transparent"
                />
            <Button
                android:id="@+id/song_start"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="||"
                android:textColor="@android:color/black"
                android:background="@android:color/transparent"
                />
            <Button
                android:id="@+id/song_front"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text=">"
                android:textSize="16sp"
                android:textColor="@android:color/black"
                android:background="@android:color/transparent"
            />
            <Button
                android:id="@+id/song_font"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="詞"
                android:textColor="@android:color/darker_gray"
                android:background="@android:color/transparent"
                />
        </LinearLayout>
        <TextView
            android:id="@+id/btn_item_close"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignParentEnd="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:gravity="center"
            android:text="X"
            android:textStyle="bold"
            />

    </RelativeLayout>

</RelativeLayout>

效果如下:

第二步:

添加通知View,添加點擊事件,添加一個Notification

Notification.Builder builder=new Notification.Builder(activity);
                Intent in=new Intent("close");
                in.setPackage(activity.getPackageName());
                PendingIntent intent=PendingIntent.getBroadcast(activity,0
                        ,in,PendingIntent.FLAG_UPDATE_CURRENT);

                MyNotificationView myNotificationView=new MyNotificationView(activity.getPackageName()
                        ,R.layout.notification_item
                        ,activity);
                myNotificationView.setOnClickPendingIntent(R.id.btn_item_close,intent);

                builder.setSmallIcon(R.mipmap.ic_launcher)
                        .setOngoing(false)
                        .setAutoCancel(true)
                        .setCustomContentView(myNotificationView)
                        .setChannelId(CHANNEL_ID)
                        .setWhen(SystemClock.currentThreadTimeMillis())
                        .setContentIntent(intent);
                mNotificationManager.notify(mNotificationId++, builder.build());

第三步,寫一個廣播接受者,接受發出的廣播事件

public class MusicReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action=intent.getAction();
        if (action != null && action.equals("close")) {
            if(MainActivity.myHandler!=null){
                MainActivity.myHandler.sendEmptyMessage(MainActivity.MESSAGE_CLOSE);
            }
        }
    }
}

項目效果:

點擊Toast

 

項目git地址:https://github.com/1104219446/NitificationTest.git

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章