Запустите Sqlite Code при получении уведомления Xamarin Forms - PullRequest
0 голосов
/ 05 марта 2020

Я пытаюсь запустить код SQLite, когда приложение получило уведомление от firebase в приложении Xamarin Forms. Сначала я устанавливаю этот плагин Plugin.FirebasePushNotification, а также добавляю это разрешение:

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

, затем добавляю этот класс в mu android project

    [Application]
public class MainApplication : Application
{
    public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
    {
    }

    public override void OnCreate()
    {
        base.OnCreate();

        //Set the default notification channel for your app when running Android Oreo
        if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
        {
            //Change for your default notification channel id here
            FirebasePushNotificationManager.DefaultNotificationChannelId = "FirebasePushNotificationChannel";

            //Change for your default notification channel name here
            FirebasePushNotificationManager.DefaultNotificationChannelName = "General";
        }


        //If debug you should reset the token each time.
        FirebasePushNotificationManager.Initialize(this, true);
        //Handle notification when app is closed here
        CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
        {

        };
    }
}

и в своем главном классе активности после загрузки приложения я добавляю эту строку

FirebasePushNotificationManager.ProcessIntent(this, Intent);

и в своем app.cs я обрабатываю событие OnReceived, как это

        protected override void OnStart()
    {
        CrossFirebasePushNotification.Current.Subscribe("general");
        CrossFirebasePushNotification.Current.OnNotificationReceived += Current_OnNotificationReceived;
    }

    private void Current_OnNotificationReceived(object source, FirebasePushNotificationDataEventArgs e)
    {
        var notification = new AJNotification {Id = "1"};
        if (e.Data.ContainsKey("body"))
        {
            notification.Body = $"{e.Data["body"]}";                    
        }
        if (e.Data.ContainsKey("title"))
        {
            notification.Title = e.Data["title"].ToString();
        }
        if (e.Data.ContainsKey("silent"))
        {
            notification.Silent = e.Data["silent"].ToString();
        }
        _sqliteService.SaveItem(notification);
    }

затем я отправляю уведомление со свойством silent, равным true, например, когда приложение уже «уничтожено», затем я повторно запускаю приложение из Visual Studio и отслеживаю код, чтобы увидеть, сохранены ли данные в SQLite, но я не получил данные

1 Ответ

1 голос
/ 06 марта 2020

Пожалуйста, отредактируйте AndroidManifest. xml и вставьте в раздел следующие элементы:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" package="com.crossgeeks.firebasepushnotificationsample" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="22" android:targetSdkVersion="28" />
<application android:label="FirebasePushSample.Android" android:icon="@drawable/icon">
<receiver
android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver"
android:exported="false" />  
</application>
<receiver
  android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
  android:exported="true"
  android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
  <action android:name="com.google.android.c2dm.intent.RECEIVE" />
  <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
  <category android:name="${applicationId}" />
</intent-filter>
</receiver>
</manifest>

Затем повторите попытку.

Это пример, который вы можете посмотреть:

https://github.com/CrossGeeks/FirebasePushNotificationPlugin

Но вам все равно нужно добавить приведенный выше код в AndroidManifest. xml и запустить этот пример, вы получите успешно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...