Hi,
I want to run a script in background when the app is open or closed. This background script sends a request to the local server and then sends a response as a notification to the user. I can communicate the local server and send a notification but I don’t know how running this script in app background. This background script should be running independently of scenes. This background script will be run in android and ios.
Please help me with my this problem.
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using Unity.Notifications.Android;
public class Notification : MonoBehaviour
{
void Start()
{
InvokeRepeating("ErrorUpdate", 0, 0.1f);
}
void ErrorUpdate()
{
StartCoroutine(GetError());
}
IEnumerator GetError()
{
string IpURL = IPClass.url + IPClass.port + "/api/data";
UnityWebRequest _www = UnityWebRequest.Get(IpURL);
yield return _www.SendWebRequest();
if (_www.error == null)
{
ErrorData(_www.downloadHandler.text);
}
}
private void ErrorData(string _url)
{
ErrorListDALClass errorDataJson = JsonUtility.FromJson<ErrorListDALClass>(_url);
foreach (var item in errorDataJson.Value)
{
if (item != null)
{
SendNotification();
break;
}
}
}
public void CreateNotificationChannel()
{
var c = new AndroidNotificationChannel()
{
Id = "channel_id",
Name = "Default Channel",
Importance = Importance.High,
Description = "Generic notifications",
};
AndroidNotificationCenter.RegisterNotificationChannel(c);
}
public void SendNotification()
{
var notification = new AndroidNotification();
notification.Title = "Robot Says";
notification.Text = "System Error";
notification.Color = Color.red;
notification.FireTime = System.DateTime.Now.AddMilliseconds(10);
AndroidNotificationCenter.SendNotification(notification, "channel_id");
}
}