2017-02-28 99 views
1

我正在編寫使用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'放在那裏,什麼都不會打開。 –

回答

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

,然後得到這個意圖在服務的onStartCommand方法:

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

你可以顯示類定義?什麼是'這個'? –

+0

@ cricket_007編輯我的答案 –

+0

我的意思是'公共類'定義 –