Advertisement
Guest User

ServiceMessageReceiver.java

a guest
Nov 8th, 2024
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. package com.your.example;
  2.  
  3. import android.content.BroadcastReceiver;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.util.Log;
  7. import com.unity3d.player.UnityPlayer;
  8.  
  9. public class ServiceMessageReceiver extends BroadcastReceiver {
  10. @Override
  11. public void onReceive(Context context, Intent intent) {
  12. // Check if the received intent matches your action
  13. if ("com.your.example.MESSAGE".equals(intent.getAction())) {
  14. // Extract the number sent from the service
  15. int number = intent.getIntExtra(Intent.EXTRA_TEXT, -1);
  16. Log.d("ServiceMessageReceiver", "Received number: " + number);
  17. sendMessageToUnity(number);
  18. }
  19. }
  20.  
  21. private void sendMessageToUnity(int number) {
  22. // Run on Unity's main thread to send message to a GameObject in Unity
  23. UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
  24. @Override
  25. public void run() {
  26. try {
  27. // Replace "GameObjectName" with the name of the GameObject in Unity
  28. // Replace "OnServiceMessageReceived" with the Unity method name
  29. UnityPlayer.UnitySendMessage("GameObjectName", "OnServiceMessageReceived", String.valueOf(number));
  30. } catch (Exception e) {
  31. Log.e("ServiceMessageReceiver", "Error sending message to Unity: ", e);
  32. }
  33. }
  34. });
  35. }
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement