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

首頁 Java java教程 Android 推送通知分步指南

Android 推送通知分步指南

Nov 18, 2024 am 08:46 AM

推送通知在移動應用中的用戶參與度和留存率方面發(fā)揮著重要作用,讓用戶了解最新動態(tài)并營造一種促使購買的緊迫感。在 Android 中,我們獲得了 Firebase Cloud Messaging (FCM) 通知服務的額外好處,該服務充當應用服務器和用戶 Android 設備之間的中間人。即使應用程序未激活或用戶在其設備上使用不同的應用程序,它也有助于發(fā)送推送通知。

Firebase Cloud Messaging (FCM) 憑借其強大的交叉消息系統(tǒng),用于向用戶發(fā)送數據消息和警報。 FCM 支持 iOS、Web 和 Android 平臺??梢允褂?FCM 推送通知發(fā)送數據負載高達 4kb 的消息。

在本文中,我們將探索如何將推送通知逐步集成到 Android 應用程序中,并討論實施的關鍵方面。我們還將推出多種可以簡化和增強用戶參與度的產品和工具。

了解 Android 推送通知

移動推送通知有助于提高應用程序中的用戶參與度、客戶保留率和整體用戶體驗。如果正確使用推送通知,它們可以顯著提高各個業(yè)務領域移動應用程序的效率。

推送通知可用于 Android 應用中的不同用例和目的,包括:

i) 更新用戶的在線預訂或日程安排的狀態(tài)。

ii) 為用戶所下的在線訂單提供說明和更新。

iii) 向用戶建議后端的更改并幫助他們跟蹤包裹。

iv) 圍繞與應用相關的活動進行宣傳,并向用戶介紹新的優(yōu)惠、促銷和機會。

v) 通過預告消息鼓勵用戶嘗試新的應用程序功能,并通知他們服務器更新和其他后端更改。

Android應用中推送通知的實現方法

先決條件

您需要擁有這些工具和服務才能在 Android 應用 FCM 中成功實現推送通知:

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

ii) 基礎知識和理解 –您需要對 Android 項目開發(fā)和結構以及清單文件配置有基本的了解。

iii) Firebase 帳戶 –您應該擁有一個 Firebase 帳戶來創(chuàng)建和管理項目設置。

iv) 互聯(lián)網可用性 – 集成測試和 Firebase 設置需要互聯(lián)網連接。

步驟 1. 設置您的 Firebase 項目

訪問 Firebase 控制臺。

通過命名來創(chuàng)建您的項目,然后單擊“繼續(xù)”。

Android Push Notifications Step by Step Guide

要進行進一步配置,您可以啟用或禁用 Google Analytics 服務來獲取應用程序的數據分析。

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

創(chuàng)建項目后,您需要為推送通知實現進行額外的項目配置。

在項目儀表板中注冊您的應用程序

您需要單擊儀表板中的 Android 圖標來添加 Android 應用程序。接下來,輸入 Android 包名稱。此包名稱必須與您項目中的包名稱相同(即 com.app.demoapp)。

Android Push Notifications Step by Step Guide

您還可以在控制臺中輸入應用的昵稱來識別您的應用。

為您的應用添加 SHA-1 密鑰。您需要使用此命令在終端中生成 SHA-1 密鑰:現在復制 SHA-1 密鑰并將其粘貼到 Firebase 控制臺中。

./gradlew signingReport

最后點擊“注冊應用程序”完成配置。

Android Push Notifications Step by Step Guide

設置谷歌服務

完成應用注冊后,您可以下載 google-services.json 文件并將其保存到您的計算機。

現在您需要將 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 服務類路徑:

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. 配置您的 Android 項目

項目級build.gradle

打開項目級 build.gradle:導航到 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 中進行更改

在項目應用目錄中找到 build.gradle 文件,然后在文件末尾添加 google-services 插件,并在依賴項部分添加 Firebase 和 Firebase Messaging 依賴項。

./gradlew signingReport

完成這些步驟后,您的項目就配置了 Firebase 依賴項,包括用于推送通知的 Firebase Messaging?,F在讓我們繼續(xù)設置 Firebase Messaging 服務并處理您應用中的通知。

步驟 3. 實施 FCM

添加服務來處理 FCM 消息

創(chuàng)建一個名為 MyMessagingService 的新類,該類擴展 FirebaseMessagingService。

當您的應用程序處于前臺狀態(tài)時,您需要重寫 onMessageReceived 方法來處理傳入消息。然后實現邏輯來處理通知并可選擇將其顯示給用戶。

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

在AndroidManifest.xml文件中注冊

打開項目中的 AndroidManifest.xml 文件。

現在您需要在清單中注冊 MyMessagingService 來處理 FCM 消息。

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

步驟 4:獲取 FCM 注冊令牌

要接收推送通知,您的應用需要獲取 FCM 注冊令牌。此令牌唯一標識設備上的應用程序實例。

獲取設備令牌的代碼示例

您可以在 FirebaseMessagingService 或應用中的任何其他適當位置獲取 FCM 注冊令牌。讓我們看看如何在 FirebaseMessagingService 中執(zhí)行此操作。

更新我的消息服務:

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,并根據需要存儲或使用它。

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 應用程序中獲取 FCM 注冊令牌??梢栽?FirebaseMessagingService 或任何 Activity 或 Fragment 中獲取令牌。此令牌對于向特定設備發(fā)送有針對性的推送通知非常重要。

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

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

您需要獲取服務器密鑰

  • 在Firebase控制臺→項目設置→“項目概述”→“云消息傳遞”中。
  • 在“項目憑據”中,您將找到服務器密鑰。

cURL 請求: 此 cURL 命令將用于發(fā)送通知。替換 使用您的實際服務器密鑰和 與目標設備的 FCM 令牌。

./gradlew signingReport

  • https://fcm.googleapis.com/fcm/send API 端點。
  • H "Authorization: key=":這是帶有您的服務器密鑰的授權標頭。
  • H "Content-Type: application/json": 內容類型標頭。
  • d '{ ... }':這是包含您的通知和數據的 JSON 負載。

高級主題

處理數據消息

數據消息是一種可以攜帶自定義鍵值對的消息,其處理方式與通知消息不同。無論應用是在前臺還是后臺,數據消息都會在 FirebaseMessagingService 的 onMessageReceived 方法中接收。

數據消息處理示例

更新我的消息服務

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

管理通知渠道

從 Android 8.0(API 級別 26)開始,所有通知都必須分配給一個通道。這允許用戶控制每個頻道的通知設置。

創(chuàng)建通知通道示例

創(chuàng)建設置通知渠道的方法:

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

在您的 MainActivity 或應用程序類中調用此方法:

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);在你的應用程序類中,如果你有一個:

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()
    }
}

更新您的通知生成器以使用通道 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'

測試推送通知

當實現推送通知時,我們需要進行測試以確保它們正確實現。

在Android Studio中,可以打開logcat,查看>工具窗口> Logcat。

我們還可以使用 FirebaseMessagingService 類中使用的標簽來過濾 logcat 輸出。應用程序必須在設備上或通過模擬器運行。

收到通知后,我們可以在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>

結論

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

您需要首先設置 Firebase 項目并下載 google-services.json 文件。之后,您需要將此文件放入應用程序的目錄并修改 build.gradle 文件以包含 Firebase 依賴項。

然后,您需要創(chuàng)建一個類來處理傳入消息并在 AndroidManifest.xml 中注冊該服務類。在清單文件中添加服務后,您需要獲取用于唯一標識您的應用程序的 FCM 令牌,以便可以將通知發(fā)送到目標設備。

可以通過從 Firebase 控制臺發(fā)送消息并使用 Android Studio 的 logcat 確認發(fā)送來測試通知。要激活服務器端通知,請使用帶有 Firebase 服務器密鑰和設備的 FCM 令牌的 cURL 請求。

為了保持與更高版本 Android 的兼容性,您需要在“FirebaseMessagingService”中處理數據消息并管理復雜配置的通知通道。

推送通知提供相關更新和定制信息,并且可以提高用戶保留率和轉化率,這對于鼓勵用戶參與至關重要。

閱讀官方 Firebase 和 Android SDK 文檔,了解更多信息和深入指導。這些網站提供了將推送通知合并到您的應用程序中的全面指導和行業(yè)最佳實踐。

以上是Android 推送通知分步指南的詳細內容。更多信息請關注PHP中文網其他相關文章!

本站聲明
本文內容由網友自發(fā)貢獻,版權歸原作者所有,本站不承擔相應法律責任。如您發(fā)現有涉嫌抄襲侵權的內容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅動的應用程序,用于創(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

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

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

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

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

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

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

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

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

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

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

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

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

變量的最終關鍵字是什么? 變量的最終關鍵字是什么? 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)建邏輯,隱藏實現細節(jié),支持多種相關對象的創(chuàng)建。具體描述如下:工廠模式將對象創(chuàng)建交給專門的工廠類或方法處理,避免直接使用newClass();適用于多類型相關對象創(chuàng)建、創(chuàng)建邏輯可能變化、需隱藏實現細節(jié)的場景;例如支付處理器中通過工廠統(tǒng)一創(chuàng)建Stripe、PayPal等實例;其實現包括工廠類根據輸入參數決定返回的對象,所有對象實現共同接口;常見變體有簡單工廠、工廠方法和抽象工廠,分別適用于不同復雜度的需求。

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

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

See all articles