在我的用于android的Unity3D应用程序中,我需要启动一个将在后台运行的服务。我无法弄清楚我该怎么做。必须在活动上调用 startService()方法,但我不知道如何将当前的unity活动从unity脚本传递到我的android插件。我还没有找到任何方法在静态方法中获取活动并在其中运行 startService()。
据我了解序列,我需要获得主要的Unity3D活动并从中启动服务。
我的班级应该致电该服务。
public final class StatusCheckStarter {
public static void StartCheckerService()
{
startService(new Intent(this, CheckService.class));
}
}
此代码不起作用,因为“无法解析方法startService”,我无法通过此参数传递。我需要获得当前的活动。
答案 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
课程的完整包。