#android #unity3d #notifications
#Android #unity3d #уведомления
Вопрос:
Это BroadcastReceiver, расширенное до RebootManager. Проблема в том, что при перезагрузке или перезапуске мобильного устройства уведомления не отображаются. у меня включены все три вызова сброса загрузки в действии фильтра намерений, но я не вижу, что не так. было бы неплохо, если бы кто-нибудь мог помочь с этим кодом. приложение отображает уведомление, если мобильный телефон не перезагружен, но при перезагрузке мобильный телефон теряет данные для уведомления.
import java.util.Iterator;
import android.content.Intent;
import android.content.Context;
import android.content.BroadcastReceiver;
public class RebootManager extends BroadcastReceiver
{
public void onReceive(final Context context, final Intent intent) {
for (final int id : Storage.GetNotificationIds(context)) {
final NotificationParams params = Storage.GetNotification(context, id);
if (params != null) {
Controller.SetNotification(context, params);
}
}
}
}
using System;
using UnityEngine;
namespace Assets.SimpleAndroidNotifications
{
public class NotificationExample : MonoBehaviour
{
public void ScheduleSimple()
{
NotificationManager.Send(TimeSpan.FromSeconds(120), "Simple notification", "Customize icon and color", new Color(1, 0.3f, 0.15f));
}
public void ScheduleNormal()
{
NotificationManager.SendWithAppIcon(TimeSpan.FromSeconds(120), "Notification", "Notification with app icon", new Color(0, 0.6f, 1), NotificationIcon.Message);
}
public void ScheduleNormal2()
{
NotificationManager.SendWithAppIcon(TimeSpan.FromSeconds(120), "Notification", "Notification with app icon", new Color(0, 0.6f, 1), NotificationIcon.Message);
}
public void ScheduleCustom()
{
var notificationParams = new NotificationParams
{
Id = UnityEngine.Random.Range(0, int.MaxValue),
Delay = TimeSpan.FromSeconds(120),
Title = "Custom notification",
Message = "Message",
Ticker = "Ticker",
Sound = true,
Vibrate = true,
Light = true,
SmallIcon = NotificationIcon.Heart,
SmallIconColor = new Color(0, 0.5f, 0),
LargeIcon = "app_icon"
};
NotificationManager.SendCustom(notificationParams);
}
public void CancelAll()
{
NotificationManager.CancelAll();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.hippogames.simpleandroidnotifications"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-sdk android:minSdkVersion="15" />
<application android:largeHeap="true" android:allowBackup="true" android:directBootAware="true"
android:label="@string/app_name"
android:debuggable="true">
<activity android:name="com.unity3d.player.UnityPlayerActivity" android:launchMode="singleTask"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
</activity>
<receiver android:name="com.hippogames.simpleandroidnotifications.Controller" />
<receiver android:name="com.hippogames.simpleandroidnotifications.RebootManager"
android:directBootAware="true"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
using System;
using UnityEngine;
#if UNITY_ANDROID amp;amp; !UNITY_EDITOR
using System.Linq;
#endif
namespace Assets.SimpleAndroidNotifications
{
public static class NotificationManager
{
#if UNITY_ANDROID amp;amp; !UNITY_EDITOR
private const string FullClassName = "com.hippogames.simpleandroidnotifications.Controller";
private const string MainActivityClassName = "com.unity3d.player.UnityPlayerActivity";
#endif
/// <summary>
/// Schedule simple notification without app icon.
/// </summary>
/// <param name="smallIcon">List of build-in small icons: notification_icon_bell (default), notification_icon_clock, notification_icon_heart, notification_icon_message, notification_icon_nut, notification_icon_star, notification_icon_warning.</param>
public static int Send(TimeSpan delay, string title, string message, Color smallIconColor, NotificationIcon smallIcon = 0)
{
return SendCustom(new NotificationParams
{
Id = UnityEngine.Random.Range(0, int.MaxValue),
Delay = delay,
Title = title,
Message = message,
Ticker = message,
Sound = true,
Vibrate = true,
Light = true,
SmallIcon = smallIcon,
SmallIconColor = smallIconColor,
LargeIcon = ""
});
}
/// <summary>
/// Schedule notification with app icon.
/// </summary>
/// <param name="smallIcon">List of build-in small icons: notification_icon_bell (default), notification_icon_clock, notification_icon_heart, notification_icon_message, notification_icon_nut, notification_icon_star, notification_icon_warning.</param>
public static int SendWithAppIcon(TimeSpan delay, string title, string message, Color smallIconColor, NotificationIcon smallIcon = 0)
{
return SendCustom(new NotificationParams
{
Id = UnityEngine.Random.Range(0, int.MaxValue),
Delay = delay,
Title = title,
Message = message,
Ticker = message,
Sound = true,
Vibrate = true,
Light = true,
SmallIcon = smallIcon,
SmallIconColor = smallIconColor,
LargeIcon = "app_icon"
});
}
/// <summary>
/// Schedule customizable notification.
/// </summary>
public static int SendCustom(NotificationParams notificationParams)
{
#if UNITY_ANDROID amp;amp; !UNITY_EDITOR
var p = notificationParams;
var delay = (long) p.Delay.TotalMilliseconds;
new AndroidJavaClass(FullClassName).CallStatic("SetNotification", p.Id, delay, p.Title, p.Message, p.Ticker,
p.Sound ? 1 : 0, p.Vibrate ? 1 : 0, p.Light ? 1 : 0, p.LargeIcon, GetSmallIconName(p.SmallIcon), ColotToInt(p.SmallIconColor), MainActivityClassName);
#else
Debug.LogWarning("Simple Android Notifications are not supported for current platform. Build and play this scene on android device!");
#endif
return notificationParams.Id;
}
/// <summary>
/// Cancel notification by id.
/// </summary>
public static void Cancel(int id)
{
#if UNITY_ANDROID amp;amp; !UNITY_EDITOR
new AndroidJavaClass(FullClassName).CallStatic("CancelScheduledNotification", id);
#endif
}
/// <summary>
/// Cancel all notifications.
/// </summary>
public static void CancelAll()
{
#if UNITY_ANDROID amp;amp; !UNITY_EDITOR
new AndroidJavaClass(FullClassName).CallStatic("CancelAllScheduledNotifications");
#endif
}
private static int ColotToInt(Color color)
{
var smallIconColor = (Color32) color;
return smallIconColor.r * 65536 smallIconColor.g * 256 smallIconColor.b;
}
private static string GetSmallIconName(NotificationIcon icon)
{
return "anp_" icon.ToString().ToLower();
}
}
}
Ответ №1:
RECEIVE_BOOT_COMPLETED
в вашем манифесте отсутствует разрешение, по умолчанию Android удаляет уведомления после загрузки. Это должно дать вам желаемый результат.
Вот документация, как это сделать, если вы используете тот же ресурс:
https://docs.unity3d.com/Packages/com.unity.mobile.notifications@1.3/manual/Settings.html
Комментарии:
1. в строке № 9 вы можете видеть, что я использую
RECEIVE_BOOT_COMPLETED
в своем Manifest.xml досье. есть ли где-нибудь еще, где мне нужно его использовать?