从 Android 中的服务获取 Activity.Class

Get Activity.Class from service in Android

我正在编写使用 Android 本机插件的 Unity 移动应用程序。该插件创建后台定位服务,并在用户接近地图上的特定点(顺便说一句,这是建筑纪念碑)时通知用户。

所以服务发送推送通知,当用户点击这个通知时,应用程序应该从之前暂停的地方打开。

为了创建这个通知,我写了下一个代码:

Intent intent = new Intent(this, UnityPlayerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

Notification n = new Notification.Builder(this)
        .setContentTitle(title)
        .setContentText(text)
        .setSmallIcon(R.drawable.app_icon)
        .setDefaults(Notification.DEFAULT_ALL)
        .setPriority(Notification.PRIORITY_HIGH)
        .setContentIntent(pIntent)
        .setAutoCancel(true).build();

mNotificationManager.notify(notificationID, n);

诀窍是 Unity 在应用程序生命周期中使用一个 Activity (UnityPlayerActivity)。但是我必须用我的服务构建独立的 .jar 文件,它不能使用 UnityPlayerActivity class 因为它不知道。

我只能在运行时获取当前 Activity 实例并在启动服务时使用它。

问题:如何在创建Intent时从服务获取Activity.class

感谢您的回复。

UPD: 我无法将我的服务放入 Intent 构造函数中。 Intent 构造函数中的第二个参数必须是 Activity.Class 当用户点击通知时应该打开。如果我把 Service.Class 放在那里,什么也不会打开。

所以我需要将 UnityPlayerActivity 实例作为第二个参数,我只能在运行时获取它,但不知道如何将其导入服务。

我使用意图 putExtra 方法实现了这样的事情。

统一方:

public class GPSServiceAndroidTest : MonoBehaviour {

    private AndroidJavaObject activity = null;
    private AndroidJavaObject launcher = null;

    void Start () {

        using(AndroidJavaClass activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")){
            activity = activityClass.GetStatic<AndroidJavaObject>("currentActivity");
        }

        using(AndroidJavaClass pluginClass = new AndroidJavaClass("com.softserve.gpstest.Launcher")){
            if(pluginClass!=null){
                launcher = pluginClass.CallStatic<AndroidJavaObject>("instance");
                launcher.Call("startTustanService", activity);
            }
        }
    }
}

Launcher class:

public class Launcher {

    private static Launcher instance;

    private Launcher() {
        Launcher.instance = this;
    }

    public static Launcher instance() {
        if(instance == null) {
            instance = new Launcher();
        }
        return instance;
    }

    public void startTustanService(Activity currentActivity){
        Intent notificationIntent = new Intent(currentActivity, currentActivity.getClass());
        startServiceIntent.putExtra("notificationIntent", notificationIntent);

        currentActivity.startService(new Intent(currentActivity, TestService.class));
    }
}

然后在服务的 onStartCommand 方法中获取此意图:

mNotificationIntent = intent.getParcelableExtra("notificationIntent");