国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 Java java教程 Android 推播通知逐步指南

Android 推播通知逐步指南

Nov 18, 2024 am 08:46 AM

推播通知在行動應(yīng)用程式中的用戶參與度和留存率方面發(fā)揮著重要作用,讓用戶了解最新動態(tài)並營造一種促使購買的緊迫感。在 Android 中,我們獲得了 Firebase Cloud Messaging (FCM) 通知服務(wù)的額外好處,該服務(wù)充當(dāng)應(yīng)用程式伺服器和用戶 Android 裝置之間的中間人。即使應(yīng)用程式未啟動或用戶在其裝置上使用不同的應(yīng)用程序,它也有助於發(fā)送推播通知。

Firebase Cloud Messaging (FCM) 憑藉其強大的交叉訊息系統(tǒng),用於向使用者發(fā)送資料訊息和警報。 FCM 支援 iOS、Web 和 Android 平臺??梢允褂?FCM 推播通知發(fā)送資料負載高達 4kb 的訊息。

在本文中,我們將探索如何將推播通知逐步整合到 Android 應(yīng)用程式中,並討論實施的關(guān)鍵方面。我們還將推出多種可以簡化和增強用戶參與度的產(chǎn)品和工具。

了解 Android 推播通知

行動推播通知有助於提高應(yīng)用程式中的用戶參與度、客戶保留率和整體用戶體驗。如果正確使用推播通知,它們可以顯著提高各個業(yè)務(wù)領(lǐng)域行動應(yīng)用程式的效率。

推播通知可用於 Android 應(yīng)用中的不同用例和目的,包括:

i) 更新使用者的線上預(yù)訂或日程安排的狀態(tài)。

ii) 為使用者所下的線上訂單提供說明和更新。

iii) 向使用者建議後端的變更並幫助他們追蹤包裹。

iv) 圍繞與應(yīng)用程式相關(guān)的活動進行宣傳,並向用戶介紹新的優(yōu)惠、促銷和機會。

v) 透過預(yù)告訊息鼓勵使用者嘗試新的應(yīng)用程式功能,並通知他們伺服器更新和其他後端變更。

Android應(yīng)用程式中推播通知的實作方法

先決條件

您需要擁有這些工具和服務(wù)才能在 Android 應(yīng)用程式 FCM 中成功實現(xiàn)推播通知:

i) Android Studio –這是用於 Android 開發(fā)的 IDE。

ii) 基礎(chǔ)知識與理解 –您需要對 Android 專案開發(fā)與架構(gòu)以及清單檔案配置有基本的了解。

iii) Firebase 帳戶 –您應(yīng)該擁有一個 Firebase 帳戶來建立和管理專案設(shè)定。

iv) 網(wǎng)路可用性 – 整合測試和 Firebase 設(shè)定需要網(wǎng)路連線。

步驟 1. 設(shè)定您的 Firebase 項目

造訪 Firebase 控制臺。

透過命名來建立您的項目,然後按一下「繼續(xù)」。

Android Push Notifications Step by Step Guide

要進行進一步配置,您可以啟用或停用 Google Analytics 服務(wù)來取得應(yīng)用程式的資料分析。

要完成設(shè)置,您需要檢查項目設(shè)定;然後你就可以創(chuàng)建你的項目了。

建立專案後,您需要為推播通知實作進行額外的專案配置。

在專案儀表板中註冊您的應(yīng)用程式

您需要點擊儀表板中的 Android 圖示來新增 Android 應(yīng)用程式。接下來,輸入 Android 套件名稱。此套件名稱必須與您專案中的套件名稱相同(即 com.app.demoapp)。

Android Push Notifications Step by Step Guide

您也可以在控制臺中輸入應(yīng)用程式的暱稱來識別您的應(yīng)用程式。

為您的應(yīng)用程式新增 SHA-1 金鑰。您需要使用此命令在終端機中產(chǎn)生 SHA-1 金鑰:現(xiàn)在複製 SHA-1 金鑰並將其貼上到 Firebase 控制臺中。

./gradlew signingReport

最後點選「註冊應(yīng)用程式」完成設(shè)定。

Android Push Notifications Step by Step Guide

設(shè)定Google服務(wù)

完成應(yīng)用程式註冊後,您可以下載 google-services.json 檔案並將其儲存到您的電腦。

現(xiàn)在您需要將 google-services.json 新增到您的 Android 專案中,並將檔案新增至 Android 專案的 app 目錄。

MyApp/
├── app/
│ ├── src/
│ ├── build.gradle
│ ├── google-services.json
├── build.gradle
├── settings.gradle

添加 Firebase SDK

接下來,將 Firebase SDK 新增至您的項目,在 build.gradle 中新增 Google 服務(wù)類路徑:

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:4.3.10'
    }
}

在 app/build.gradle 中加入以下依賴項:-

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    // ...
}

dependencies {
    // Add these lines
    implementation platform('com.google.firebase:firebase-bom:29.0.4')
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-messaging'
}

完成這些步驟後,您可以在 Android Studio 中點擊“立即同步”,將您的專案與 Firebase 同步。

步驟 2. 設(shè)定您的 Android 項目

專案級build.gradle

開啟專案級 build.gradle:導(dǎo)覽至 Android 專案的根目錄並找到 build.gradle 檔案。

確保 google() 和 mavenCentral() 儲存庫包含在儲存庫部分中。

buildscript {
    repositories {
        // Check that you have these lines
        google()
        mavenCentral()
    }
    dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:4.3.10'
    }
}

allprojects {
    repositories {
        // Check that you have these lines
        google()
        mavenCentral()
    }
}

在 build.gradle 中進行更改

在專案應(yīng)用程式目錄中找到 build.gradle 文件,然後在文件末尾添加 google-services 插件,並在依賴項部分中新增 Firebase 和 Firebase Messaging 依賴項。

./gradlew signingReport

完成這些步驟後,您的專案就配置了 Firebase 依賴項,包括用於推播通知的 Firebase Messaging?,F(xiàn)在讓我們繼續(xù)設(shè)定 Firebase Messaging 服務(wù)並處理您應(yīng)用程式中的通知。

步驟 3. 實施 FCM

新增服務(wù)來處理 FCM 訊息

建立一個名為 MyMessagingService 的新類,該類別擴展 FirebaseMessagingService。

當(dāng)您的應(yīng)用程式處於前臺狀態(tài)時,您需要重寫 onMessageReceived 方法來處理傳入訊息。然後實作邏輯來處理通知並可選擇將其顯示給使用者。

MyApp/
├── app/
│ ├── src/
│ ├── build.gradle
│ ├── google-services.json
├── build.gradle
├── settings.gradle

在AndroidManifest.xml檔案中註冊

開啟專案中的 AndroidManifest.xml 檔案。

現(xiàn)在您需要在清單中註冊 MyMessagingService 來處理 FCM 訊息。

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:4.3.10'
    }
}

步驟 4:取得 FCM 註冊令牌

要接收推播通知,您的應(yīng)用程式需要取得 FCM 註冊令牌。此令牌唯一標識設(shè)備上的應(yīng)用程式實例。

取得設(shè)備令牌的程式碼範(fàn)例

您可以在 FirebaseMessagingService 或應(yīng)用程式中的任何其他適當(dāng)位置取得 FCM 註冊令牌。讓我們看看如何在 FirebaseMessagingService 中執(zhí)行此操作。

更新我的訊息服務(wù):

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    // ...
}

dependencies {
    // Add these lines
    implementation platform('com.google.firebase:firebase-bom:29.0.4')
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-messaging'
}

您可以在 Activity 或 Fragment 中取得 token,並根據(jù)需要儲存或使用它。

buildscript {
    repositories {
        // Check that you have these lines
        google()
        mavenCentral()
    }
    dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:4.3.10'
    }
}

allprojects {
    repositories {
        // Check that you have these lines
        google()
        mavenCentral()
    }
}

使用這些方法,您可以在 Android 應(yīng)用程式中取得 FCM 註冊令牌??梢栽?FirebaseMessagingService 或任何 Activity 或 Fragment 中取得令牌。此令牌對於向特定裝置發(fā)送有針對性的推播通知非常重要。

第 5 步:發(fā)送推播通知

如果您想從伺服器發(fā)送通知,您需要向 FCM API 發(fā)出 POST 請求。

您需要取得伺服器金鑰

  • 在Firebase控制臺→專案設(shè)定→「專案概述」→「雲(yún)端訊息傳遞」中。
  • 在「專案憑證」中,您將找到伺服器金鑰。

cURL 請求: 此 cURL 指令將用於發(fā)送通知。取代 使用您的實際伺服器金鑰和 與目標裝置的 FCM 令牌。

./gradlew signingReport

  • https://fcm.googleapis.com/fcm/send API 端點。
  • H "Authorization: key=":這是帶有您的伺服器金鑰的授權(quán)標頭。
  • H "Content-Type: application/json": 內(nèi)容類型標頭。
  • d '{ ... }':這是包含您的通知和資料的 JSON 負載。

高級主題

處理資料訊息

資料訊息是一種可以攜帶自訂鍵值對的訊息,其處理方式與通知訊息不同。無論應(yīng)用程式是在前臺還是後臺,資料訊息都會在 FirebaseMessagingService 的 onMessageReceived 方法中接收。

資料訊息處理範(fàn)例

更新我的訊息服務(wù)

MyApp/
├── app/
│ ├── src/
│ ├── build.gradle
│ ├── google-services.json
├── build.gradle
├── settings.gradle

管理通知管道

從 Android 8.0(API 等級 26)開始,所有通知都必須指派給一個頻道。這允許用戶控制每個頻道的通知設(shè)定。

建立通知通道範(fàn)例

建立設(shè)定通知管道的方法:

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:4.3.10'
    }
}

在您的 MainActivity 或應(yīng)用程式類別中呼叫此方法:

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    // ...
}

dependencies {
    // Add these lines
    implementation platform('com.google.firebase:firebase-bom:29.0.4')
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-messaging'
}

或者,您可以呼叫NotificationUtils.createNotificationChannel(this);在你的應(yīng)用程式類別中,如果你有一個:

buildscript {
    repositories {
        // Check that you have these lines
        google()
        mavenCentral()
    }
    dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:4.3.10'
    }
}

allprojects {
    repositories {
        // Check that you have these lines
        google()
        mavenCentral()
    }
}

更新您的通知產(chǎn)生器以使用通道 ID:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 33
    defaultConfig {
        applicationId "com.example.myandroidapp"
        minSdkVersion 21
        targetSdkVersion 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.8.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'

    // Add Firebase BOM
    implementation platform('com.google.firebase:firebase-bom:29.0.4')
    // Add Firebase Messaging dependency
    implementation 'com.google.firebase:firebase-messaging'
}

// Add this line at the bottom of the file
apply plugin: 'com.google.gms.google-services'

測試推播通知

當(dāng)實作推播通知時,我們需要進行測試以確保它們正確實現(xiàn)。

在Android Studio中,可以開啟logcat,檢視>工具視窗> Logcat。

我們也可以使用 FirebaseMessagingService 類別中使用的標籤來過濾 logcat 輸出。應(yīng)用程式必須在設(shè)備上或透過模擬器運行。

收到通知後,我們可以在logcat中看到這樣的資料:

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // Handle the received message
        if (remoteMessage.getNotification() != null) {
            // Get the message body
            String messageBody = remoteMessage.getNotification().getBody();
            // Send a notification
            sendNotification(messageBody);
        }
    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        String channelId = getString(R.string.default_notification_channel_id);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0, notificationBuilder.build());
    }
}

訊息資料可以這樣看:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myandroidapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!-- Add this service -->
        <service
            android:name=".MyMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <!-- Other activities and services -->
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

結(jié)論

在本文中,我們了解了推播通知以及逐步實施方法。我們了解如何在 Firebase 控制臺中設(shè)定專案以及如何在 Firebase 專案設(shè)定中完成所需的配置,以便您可以開始向 Android 用戶發(fā)送 Android 通知。

您需要先設(shè)定 Firebase 專案並下載 google-services.json 檔案。之後,您需要將此檔案放入應(yīng)用程式的目錄並修改 build.gradle 檔案以包含 Firebase 依賴項。

然後,您需要建立一個類別來處理傳入訊息並在 AndroidManifest.xml 中註冊該服務(wù)類別。在清單檔案中新增服務(wù)後,您需要取得用於唯一標識您的應(yīng)用程式的 FCM 令牌,以便可以將通知傳送至目標裝置。

可以透過從 Firebase 控制臺發(fā)送訊息並使用 Android Studio 的 logcat 確認發(fā)送來測試通知。若要啟動伺服器端通知,請使用帶有 Firebase 伺服器金鑰和裝置的 FCM 令牌的 cURL 請求。

為了保持與更高版本 Android 的兼容性,您需要在「FirebaseMessagingService」中處理資料訊息並管理複雜配置的通知通道。

推播通知提供相關(guān)更新和客製化訊息,並且可以提高用戶保留率和轉(zhuǎn)換率,這對於鼓勵用戶參與至關(guān)重要。

閱讀官方 Firebase 和 Android SDK 文檔,以了解更多資訊和深入指導(dǎo)。這些網(wǎng)站提供了將推播通知合併到您的應(yīng)用程式中的全面指導(dǎo)和行業(yè)最佳實踐。

以上是Android 推播通知逐步指南的詳細內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

hashmap和hashtable之間的區(qū)別? hashmap和hashtable之間的區(qū)別? Jun 24, 2025 pm 09:41 PM

HashMap與Hashtable的區(qū)別主要體現(xiàn)在線程安全、null值支持及性能方面。 1.線程安全方面,Hashtable是線程安全的,其方法大多為同步方法,而HashMap不做同步處理,非線程安全;2.null值支持上,HashMap允許一個null鍵和多個null值,Hashtable則不允許null鍵或值,否則拋出NullPointerException;3.性能方面,HashMap因無同步機制效率更高,Hashtable因每次操作加鎖性能較低,推薦使用ConcurrentHashMap替

為什麼我們需要包裝紙課? 為什麼我們需要包裝紙課? Jun 28, 2025 am 01:01 AM

Java使用包裝類是因為基本數(shù)據(jù)類型無法直接參與面向?qū)ο癫僮?,而實際需求中常需對象形式;1.集合類只能存儲對象,如List利用自動裝箱存儲數(shù)值;2.泛型不支持基本類型,必須使用包裝類作為類型參數(shù);3.包裝類可表示null值,用於區(qū)分未設(shè)置或缺失的數(shù)據(jù);4.包裝類提供字符串轉(zhuǎn)換等實用方法,便於數(shù)據(jù)解析與處理,因此在需要這些特性的場景下,包裝類不可或缺。

JIT編譯器如何優(yōu)化代碼? JIT編譯器如何優(yōu)化代碼? Jun 24, 2025 pm 10:45 PM

JIT編譯器通過方法內(nèi)聯(lián)、熱點檢測與編譯、類型推測與去虛擬化、冗餘操作消除四種方式優(yōu)化代碼。 1.方法內(nèi)聯(lián)減少調(diào)用開銷,將頻繁調(diào)用的小方法直接插入調(diào)用處;2.熱點檢測識別高頻執(zhí)行代碼並集中優(yōu)化,節(jié)省資源;3.類型推測收集運行時類型信息實現(xiàn)去虛擬化調(diào)用,提升效率;4.冗餘操作消除根據(jù)運行數(shù)據(jù)刪除無用計算和檢查,增強性能。

什麼是接口中的靜態(tài)方法? 什麼是接口中的靜態(tài)方法? Jun 24, 2025 pm 10:57 PM

StaticmethodsininterfaceswereintroducedinJava8toallowutilityfunctionswithintheinterfaceitself.BeforeJava8,suchfunctionsrequiredseparatehelperclasses,leadingtodisorganizedcode.Now,staticmethodsprovidethreekeybenefits:1)theyenableutilitymethodsdirectly

什麼是實例初始器塊? 什麼是實例初始器塊? Jun 25, 2025 pm 12:21 PM

實例初始化塊在Java中用於在創(chuàng)建對象時運行初始化邏輯,其執(zhí)行先於構(gòu)造函數(shù)。它適用於多個構(gòu)造函數(shù)共享初始化代碼、複雜字段初始化或匿名類初始化場景,與靜態(tài)初始化塊不同的是它每次實例化時都會執(zhí)行,而靜態(tài)初始化塊僅在類加載時運行一次。

變量的最終關(guān)鍵字是什麼? 變量的最終關(guān)鍵字是什麼? Jun 24, 2025 pm 07:29 PM

InJava,thefinalkeywordpreventsavariable’svaluefrombeingchangedafterassignment,butitsbehaviordiffersforprimitivesandobjectreferences.Forprimitivevariables,finalmakesthevalueconstant,asinfinalintMAX_SPEED=100;wherereassignmentcausesanerror.Forobjectref

什麼是工廠模式? 什麼是工廠模式? Jun 24, 2025 pm 11:29 PM

工廠模式用於封裝對象創(chuàng)建邏輯,使代碼更靈活、易維護、松耦合。其核心答案是:通過集中管理對象創(chuàng)建邏輯,隱藏實現(xiàn)細節(jié),支持多種相關(guān)對象的創(chuàng)建。具體描述如下:工廠模式將對象創(chuàng)建交給專門的工廠類或方法處理,避免直接使用newClass();適用於多類型相關(guān)對象創(chuàng)建、創(chuàng)建邏輯可能變化、需隱藏實現(xiàn)細節(jié)的場景;例如支付處理器中通過工廠統(tǒng)一創(chuàng)建Stripe、PayPal等實例;其實現(xiàn)包括工廠類根據(jù)輸入?yún)?shù)決定返回的對象,所有對象實現(xiàn)共同接口;常見變體有簡單工廠、工廠方法和抽象工廠,分別適用於不同複雜度的需求。

什麼是類型鑄造? 什麼是類型鑄造? Jun 24, 2025 pm 11:09 PM

類型轉(zhuǎn)換有兩種:隱式和顯式。 1.隱式轉(zhuǎn)換自動發(fā)生,如將int轉(zhuǎn)為double;2.顯式轉(zhuǎn)換需手動操作,如使用(int)myDouble。需要類型轉(zhuǎn)換的情況包括處理用戶輸入、數(shù)學(xué)運算或函數(shù)間傳遞不同類型的值時。需要注意的問題有:浮點數(shù)轉(zhuǎn)整數(shù)會截斷小數(shù)部分、大類型轉(zhuǎn)小類型可能導(dǎo)致數(shù)據(jù)丟失、某些語言不允許直接轉(zhuǎn)換特定類型。正確理解語言的轉(zhuǎn)換規(guī)則有助於避免錯誤。

See all articles