从Unity3D代码启动android服务

时间:2016-07-14 08:07:10

标签: c# android unity3d plugins service

在我的用于android的Unity3D应用程序中,我需要启动一个将在后台运行的服务。我无法弄清楚我该怎么做。必须在活动上调用 startService()方法,但我不知道如何将当前的unity活动从unity脚本传递到我的android插件。我还没有找到任何方法在静态方法中获取活动并在其中运行 startService()

据我了解序列,我需要获得主要的Unity3D活动并从中启动服务。

我的班级应该致电该服务。

public final class StatusCheckStarter {

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

此代码不起作用,因为“无法解析方法startService”,我无法通过参数传递。我需要获得当前的活动。

1 个答案:

答案 0 :(得分:8)

以下是发送Activity实例/引用Java插件的两种方法,使用onCreate函数或从UnityPlayerActivity扩展。

方法1 :发送Activity引用一次,然后将其存储在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引用。

<强>爪哇

public final class StatusCheckStarter {

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

<强> C#

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课程的完整包。