从Android服务中获取Activity.Class服务

问题描述:

我正在编写使用Android本机插件的Unity移动应用程序。这个插件创建后台定位服务,并通知用户,当他接近地图上的特定点(这是建筑古迹顺便说一句)。从Android服务中获取Activity.Class服务

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

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

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

诀窍是,统一的应用程序生命周期中使用一个活动(UnityPlayerActivity)。但我必须建立独立的.jar文件与我的服务不能使用UnityPlayerActivity类,因为它不知道这一点。

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

问题:如何在创建Intent时从Service获得Activity.class

感谢您的回复。

UPD:我不能把我的服务放到Intent的构造函数中。 Intent构造函数中的第二个参数必须是Activity.Class,当用户单击通知时应打开它。如果我把Service.Class放在那里,什么都不会打开。

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

+0

'服务延伸Context'。为什么你需要一个活动? –

+0

所以你有'新的意图(this,this.getClass());' –

+0

@ cricket_007哦,对不起,这是错误的答案。 “Intent”构造函数中的第二个参数必须是“Activity.Class”,当用户单击通知时该参数应该打开。如果我把'Service.Class'放在那里,什么都不会打开。 –

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

,然后得到这个意图在服务的onStartCommand方法:

mNotificationIntent = intent.getParcelableExtra("notificationIntent"); 
+0

你可以显示类定义?什么是'这个'? –

+0

@ cricket_007编辑我的答案 –

+0

我的意思是'公共类'定义 –