Start Android service with Unity3D code

In my Unity3D Android app, I need to run a service that will run in the background. I can’t figure out how to do this. The startService () method should be called into action, but I don’t know how to transfer the current unity activity from the script unit to my Android plugin. And I did not find a way to get activity in the static method and run startService () .

As far as I understand the sequence, I need to get the main Unity3D activity and start the service from it.

My class that should call the service.

public final class StatusCheckStarter {

    public static void StartCheckerService()
    {
        startService(new Intent(this, CheckService.class));
    }
}

This code does not work because "Cannot resolve the startService method" and I have nothing to pass in the this argument . I need to get current activity.

+4
source share
1 answer

Below are two ways to send an instance Activityinstance / link to a Java plugin that does not use a function onCreateor extends from UnityPlayerActivity.

Method 1 : send the Activitylink once , then save it in a static variable in Java for reuse:

Java

public final class StatusCheckStarter {

    static Activity myActivity;

    // Called From C# to get the Activity Instance
    public static void receiveActivityInstance(Activity tempActivity) {
        myActivity = tempActivity;
    }

    public static void StartCheckerService() {
        myActivity.startService(new Intent(myActivity, CheckService.class));
    }
}

C # :

AndroidJavaClass unityClass;
AndroidJavaObject unityActivity;
AndroidJavaClass customClass;

void Start()
{
    //Replace with your full package name
    sendActivityReference("com.example.StatusCheckStarter");

   //Now, start service
   startService();
}

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");
}

2: Activity .

Java

public final class StatusCheckStarter {

    public static void StartCheckerService(Activity tempActivity) {
        tempActivity.startService(new Intent(tempActivity, CheckService.class));
    }
}

#:

void Start()
{
    //Replace with your full package name
    startService("com.example.StatusCheckStarter");
}

void startService(string packageName)
{
    AndroidJavaClass unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject unityActivity = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
    AndroidJavaClass customClass = new AndroidJavaClass(packageName);
    customClass.CallStatic("StartCheckerService", unityActivity);
}

. com.example.StatusCheckStarter StatusCheckStarter.

+5

All Articles