Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class PluginWrapper : MonoBehaviour
- {
- AndroidJavaClass unityClass;
- AndroidJavaObject unityActivity;
- AndroidJavaClass customClass;
- AndroidJavaObject receiver; // Receiver reference
- void Start()
- {
- sendActivityReference("com.your.example.StatusCheckStarter");
- customClass.CallStatic("createInstance");
- startService();
- customClass.CallStatic("makeToast");
- RegisterReceiver(); // Register the receiver
- }
- public void decreaseCount()
- {
- stopService();
- UnregisterReceiver(); // Unregister when stopping the service
- }
- void RegisterReceiver()
- {
- receiver = new AndroidJavaObject("com.your.example.ServiceMessageReceiver"); // Create an instance of your receiver
- AndroidJavaObject intentFilter = new AndroidJavaObject("android.content.IntentFilter");
- intentFilter.Call("addAction", "com.your.example.MESSAGE"); // Action to listen for
- // Register the receiver with the activity context
- unityActivity.Call("registerReceiver", receiver, intentFilter);
- }
- void UnregisterReceiver()
- {
- if (receiver != null)
- {
- unityActivity.Call("unregisterReceiver", receiver); // Unregister the receiver
- receiver = null; // Clear the reference
- }
- }
- void sendActivityReference(string packageName)
- {
- unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
- unityActivity = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
- customClass = new AndroidJavaClass(packageName);
- customClass.CallStatic("receiveActivityInstance", unityActivity);
- }
- void startService()
- {
- customClass.CallStatic("StartCheckerService");
- }
- void stopService()
- {
- customClass.CallStatic("StopCheckerService");
- }
- // This method will be called from the BroadcastReceiver
- public void OnServiceMessageReceived(int number)
- {
- Debug.Log("Received number from service: " + number);
- // Add your logic here to handle the received number
- }
- private void OnDestroy()
- {
- UnregisterReceiver(); // Ensure the receiver is unregistered when the object is destroyed
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement