Android 學習之《第一行代碼》第二版 筆記(十七)使用通知

一、通知

應用程序發出一條通知後,手機最上方的狀態欄中會顯示一個通知圖標,下拉狀態欄後可以看到通知的詳細信息。

二、用法

1. 可以在活動、廣播接收器以及服務裏面創建。

2. 創建通知的詳細步驟:

A.)使用NotificationManager對通知進行管理:

 NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

B.)使用Builder構造器創建Notification對象(Android的很多版本對通知這部分都有或多或少的修改,爲了兼容SdkVersion25及以下,使用NotificationCompat類的構造器來創建Notification對象)

//使用Builder構造器來創建Notification對象
//使用NotificationCompat來解決兼容性問題
//Notification notification = new NotificationCompat.Builder(this).build(); 已過時
//Notification notification = new NotificationCompat.Builder(this,channelId:String類型)
//channelId的實際作用是將notification進行分類,如設置不同優先級等。
Notification notification = new NotificationCompat.Builder(this,"1")
	.setContentTitle("聖旨") //設置通知標題
    .setContentText("聖旨內容嘛,好好學Android日後封你做Android程序員")//設置通知內容
    .setWhen(System.currentTimeMillis())//設置通知被創建時間,以毫秒爲單位
    .setSmallIcon(R.mipmap.ic_launcher) //設置通知小圖標,只能使用純alpha圖層的圖片
    .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))//設置通知大圖標
    .setContentIntent(pi) //構建出一個延遲執行的“意圖”,處理用戶點擊邏輯
    .setAutoCancel(true) //在點擊後取消該通知
    //設置通知發出時播放一段音頻,接收一個Uri參數
    .setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luna.ogg")))
    //設置手機靜止和振動的時長,以毫秒爲時長,奇數下標表示振動時長,偶數下標表示靜止時長
    //控制手機振動需要聲明權限
    .setVibrate(new long[]{0,1000,1000,1000})
    //控制手機呼吸燈 參數一:顏色;參數二:亮起時長,毫秒爲單位;參數三:暗去時長
    .setLights(Color.GREEN,1000,1000)
    //可以直接使用通知的默認效果,系統會根據當前手機環境決定播放什麼鈴聲以及如何振動
     // .setDefaults(NotificationCompat.DEFAULT_ALL)
     .build();
manager.notify(2,notification);//調用該方法讓通知顯示出來,參數爲id和Notification對象

對於Android 8.0 奧利奧 來說使用通知還需要配置相關的NotificationChannel

//兼容Android 8.0 需要對NotificationChannel進行相應配置
//ChannelId爲"1",ChannelName爲"Channel1"
NotificationChannel channel = new NotificationChannel("1","Channel1", NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true); //是否在桌面icon右上角展示小紅點,僅在安裝後第一次顯示出小紅點
channel.setLightColor(Color.GREEN); //小紅點顏色 依舊是紅色
channel.setShowBadge(true); //是否在久按桌面圖標時顯示此渠道的通知
channel.enableVibration(true); //是否開啓通知振動
manager.createNotificationChannel(channel);

以上步驟,下拉系統狀態欄可以看到通知的詳細信息,但是點擊無效果
C.)設置點擊效果

  • Intent 立即執行某個動作
    PendingIntent 在某個合適的時機去執行某個動作,延遲執行的Intent
    二者都可以指明某一個“意圖”,都可以用於啓動活動、啓動服務以及發送廣播等。
  • PendingIntent 的獲取方法:
    getActivity();getBroadcast();getService()
    這三個方法所接收的參數都相同:
    第一個參數:Context
    第二個參數:一般用不到,通常傳入0
    第三個參數:一個Intent對象,用於構建出PendingIntent的“意圖”
    第四個參數:用於確定PendingIntent的行爲,四種值可選:
    FLAG_ONE_SHOT、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT和FLAG_UPDATE_CURRENT,通常傳入0
  • NotificationCompat.Builder構造器可連綴一個setContentIntent()方法,接收一個PendingIntent對象
Intent intent = new Intent(this,NotificationActivity.class);
//參數一:Context;參數二:一般用不到,傳入0即可;參數三:Intent對象;參數四:用於確定PendingIntent的行爲
//參數四有四個值可選:FLAG_ONE_SHOT、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT和FLAG_UPDATE_CURRENT
PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);

三、Demo示例

1. 效果圖

進去app後的界面
單擊通知按鈕
提示
通知內容展示
單擊通知後出現的頁面

2. 代碼

A.)activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.thinkpad.notificationtest.MainActivity">

    <Button
        android:id="@+id/send_notice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="頒佈詔令"/>

</android.support.constraint.ConstraintLayout>

B.)activity_notification.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.thinkpad.notificationtest.NotificationActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="24sp"
        android:text="皇上下令讓我來的"/>
</android.support.constraint.ConstraintLayout>

C.)MainActivity.java

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.io.File;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendNotice = (Button)findViewById(R.id.send_notice);
        sendNotice.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.send_notice:
                Intent intent = new Intent(this,NotificationActivity.class);
                //參數一:Context;參數二:一般用不到,傳入0即可;參數三:Intent對象;參數四:用於確定PendingIntent的行爲
                //參數四有四個值可選:FLAG_ONE_SHOT、FLAG_NO_CREATE、FLAG_CANCEL_CURRENT和FLAG_UPDATE_CURRENT
                PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
                //需要使用NotificationManager類來對通知進行管理
                //通過調用getSystemService(一個字符串參數)獲得 Context.NOTIFICATION_SERVICE
                NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                //兼容Android 8.0 需要對NotificationChannel進行相應配置
                //ChannelId爲"1",ChannelName爲"Channel1"
                NotificationChannel channel = new NotificationChannel("1",
                        "Channel1", NotificationManager.IMPORTANCE_DEFAULT);
                channel.enableLights(true); //是否在桌面icon右上角展示小紅點,僅在安裝後第一次顯示出小紅點
                channel.setLightColor(Color.GREEN); //小紅點顏色 依舊是紅色
                channel.setShowBadge(true); //是否在久按桌面圖標時顯示此渠道的通知
                channel.enableVibration(true); //是否開啓通知振動
                manager.createNotificationChannel(channel);

                //使用Builder構造器來創建Notification對象
                //使用NotificationCompat來解決兼容性問題
                //Notification notification = new NotificationCompat.Builder(this).build(); 已過時
                //Notification notification = new NotificationCompat.Builder(this,channelId:String類型)
                //channelId的實際作用是將notification進行分類,如設置不同優先級等。
                Notification notification = new NotificationCompat.Builder(this,"1")
                        .setContentTitle("聖旨") //設置通知標題
                        .setContentText("聖旨內容嘛,好好學Android日後封你做Android程序員")//設置通知內容
                        .setWhen(System.currentTimeMillis())//設置通知被創建時間,以毫秒爲單位
                        .setSmallIcon(R.mipmap.ic_launcher) //設置通知小圖標,只能使用純alpha圖層的圖片
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))//設置通知大圖標
                        .setContentIntent(pi) //構建出一個延遲執行的“意圖”,處理用戶點擊邏輯
                        .setAutoCancel(true) //在點擊後取消該通知
                        //設置通知發出時播放一段音頻,接收一個Uri參數
                        .setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luna.ogg")))
                        //設置手機靜止和振動的時長,以毫秒爲時長,奇數下標表示振動時長,偶數下標表示靜止時長
                        //控制手機振動需要聲明權限
                        .setVibrate(new long[]{0,1000,1000,1000})
                        //控制手機呼吸燈 參數一:顏色;參數二:亮起時長,毫秒爲單位;參數三:暗去時長
                        .setLights(Color.GREEN,1000,1000)
                        //可以直接使用通知的默認效果,系統會根據當前手機環境決定播放什麼鈴聲以及如何振動
                       // .setDefaults(NotificationCompat.DEFAULT_ALL)
                        .build();
                manager.notify(2,notification);//調用該方法讓通知顯示出來,參數爲id和Notification對象
                break;
            default:
                break;
        }
    }

}

D.)NotificationActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class NotificationActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);
    }
}

E.)AndroidManifest.xml
添加

<uses-permission android:name="android.permission.VIBRATE" />

F.)build.gradle
修改SDK版本


整理學習自郭霖大佬的《第一行代碼》
目前小白一名,持續學習Android中,如有錯誤請批評指正!

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