Advertisement
Guest User

PluginWrapper.cs

a guest
Nov 8th, 2024
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class PluginWrapper : MonoBehaviour
  6. {
  7. AndroidJavaClass unityClass;
  8. AndroidJavaObject unityActivity;
  9. AndroidJavaClass customClass;
  10. AndroidJavaObject receiver; // Receiver reference
  11.  
  12. void Start()
  13. {
  14. sendActivityReference("com.your.example.StatusCheckStarter");
  15. customClass.CallStatic("createInstance");
  16. startService();
  17. customClass.CallStatic("makeToast");
  18.  
  19. RegisterReceiver(); // Register the receiver
  20. }
  21.  
  22. public void decreaseCount()
  23. {
  24. stopService();
  25. UnregisterReceiver(); // Unregister when stopping the service
  26. }
  27.  
  28. void RegisterReceiver()
  29. {
  30. receiver = new AndroidJavaObject("com.your.example.ServiceMessageReceiver"); // Create an instance of your receiver
  31. AndroidJavaObject intentFilter = new AndroidJavaObject("android.content.IntentFilter");
  32. intentFilter.Call("addAction", "com.your.example.MESSAGE"); // Action to listen for
  33.  
  34. // Register the receiver with the activity context
  35. unityActivity.Call("registerReceiver", receiver, intentFilter);
  36. }
  37.  
  38. void UnregisterReceiver()
  39. {
  40. if (receiver != null)
  41. {
  42. unityActivity.Call("unregisterReceiver", receiver); // Unregister the receiver
  43. receiver = null; // Clear the reference
  44. }
  45. }
  46.  
  47. void sendActivityReference(string packageName)
  48. {
  49. unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
  50. unityActivity = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
  51. customClass = new AndroidJavaClass(packageName);
  52. customClass.CallStatic("receiveActivityInstance", unityActivity);
  53. }
  54.  
  55. void startService()
  56. {
  57. customClass.CallStatic("StartCheckerService");
  58. }
  59.  
  60. void stopService()
  61. {
  62. customClass.CallStatic("StopCheckerService");
  63. }
  64.  
  65. // This method will be called from the BroadcastReceiver
  66. public void OnServiceMessageReceived(int number)
  67. {
  68. Debug.Log("Received number from service: " + number);
  69. // Add your logic here to handle the received number
  70. }
  71.  
  72. private void OnDestroy()
  73. {
  74. UnregisterReceiver(); // Ensure the receiver is unregistered when the object is destroyed
  75. }
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement