[Android]Notification | 建立一個Notification | 01

首先先引用Android Developers上的通知(Notification)介紹:
A notification is a message that Android displays outside your app's UI to provide the user with reminders, communication from other people, or other timely information from your app. Users can tap the notification to open your app or take an action directly from the notification.
 大概的意思是說 notification 是在App以外的地方顯示訊息來提供使用者提醒、App的即時訊息blahblah...之類的,使用者也可以點擊notification來開啟你的App或直接透過notification做一些動作。

這篇文章將會透過一個包含一個Button的Activity來說明如何建立notification,並點擊Button後將會顯示通知。



要使用notification
需先在build.gradle中加入dependencies:
 dependencies {
     implementation "com.android.support:support-compat:28.0.0"
 }

接著在Layout中拉一個Button
提供一下我的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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/baisc_notif_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.02"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

</android.support.constraint.ConstraintLayout>


接下來就是建立一個notification
我就直接複製Android Developers上的範例來改一改:

    private NotificationCompat.Builder builder = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(android.R.drawable.ic_dialog_email)
                .setContentTitle("I'm title")
                .setContentText("content text")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);
    }

簡單介紹一下NotificationCompat.Builder這個物件的一些較常用的方法:


  • setSmallIcon(int icon)//設定icon

  • setContentTitle(CharSequence title)//設定標題

  • setContentText(CharSequence text)//設定內容文字

比較要注意的方法:
setPriority(int pri)
對於API 26+(也就是Android 8.0以上)必須改成設定channel importance
所以我們新增一個方法檢查版本,如果>=Android 8.0,則向系統註冊channel
以下為Android Developers上的範例再附上英翻中:
private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library

    // 建立一個NotificationChannel,但是只能在 API 26+ 因為 NotificationChannel
    // 這個class 是新的且沒有在support library 裡面

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);

        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this

        // 向系統註冊channel;註冊完後你不能改變 importance 或 其他的通知行為

        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

最後把notification顯示出來:
 NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

 // notificationId is a unique int for each notification that you must define
 // 你必須自己定義一個對所有notification唯一的整數 notificationId
 notificationManager.notify(notificationId, builder.build());

附上完整程式碼:
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private final String CHANNEL_ID = "TEST";
    private final int notificationId = 1111;
    private Button basic_notif_btn;
    private NotificationManagerCompat notificationManager;
    private NotificationCompat.Builder builder = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(android.R.drawable.ic_dialog_email)
                .setContentTitle("I'm title")
                .setContentText("content text")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        notificationManager = NotificationManagerCompat.from(this);

        createNotificationChannel();

        basic_notif_btn = findViewById(R.id.baisc_notif_btn);
        basic_notif_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // notificationId is a unique int for each notification that you must define
                notificationManager.notify(notificationId, builder.build());
            }
        });
    }

    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "test";
            String description = "just a test channel";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}

然後是執行畫面:

補充:  根據文件裡面說道,預設內容文字至多只會有一行,所以超出的文字將會被截斷,可以使用 setStyle() 來設定template,會在另外一篇文章多做說明


以上為個人淺見,還請各位大大指教


下篇將說明如何點擊notification後開啟activity & setStyle() 函式來建立更多類型的notification


參考資料:https://developer.android.com/training/notify-user/build-notification?hl=zh-tw#

留言

這個網誌中的熱門文章

[android]QR code掃描