从Android中的服务获取Activity.Class

时间:2017-02-28 21:32:10

标签: java android android-activity unity3d android-service

我正在编写使用Android原生插件的Unity移动应用程序。此插件创建后台位置服务,并在他接近地图上的特定点(这是建筑纪念碑btw)时通知用户。

因此,服务会发送推送通知,当用户点击此通知时,该应用应该从之前暂停的位置打开。

要创建此通知,我编写了下一个代码:

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课程。

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

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

感谢您的回复。

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

所以我需要将第二个参数UnityPlayerActivity实例放在运行时,但不知道如何将其导入服务。

1 个答案:

答案 0 :(得分:0)

我使用intent 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上课:

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

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

mNotificationIntent = intent.getParcelableExtra("notificationIntent");