2016-03-07 49 views
1

我需要從android小部件開始使用android> 5.0的服務,但是此服務已實現到另一個項目中。Android 5.0(Lollipop)startService無需導入類

如果我使用的設備,採用Android < 4.4此代碼的工作:

Intent intent = new Intent("com.service.example"); 
startService(intent); 

我看到這篇文章: Service Must be explicit: Intent

和解決方案,應該是:

Intent serviceIntent = new Intent(context,MyService.class); 
context.startService(serviceIntent); 

那麼,如何在不導入服務類的情況下啓動服務(使用intent)呢?

+0

https://stackoverflow.com/questions/35827703/how-to-make-an-implicit-intent-explicit/35827786#35827786 – CommonsWare

+0

可能的重複的[在另一個包中沒有意圖過濾器啓動服務](http:///stackoverflow.com/questions/18603381/start-service-in-another-package-without-intent-filter) – Master

+0

類似但不重複 – Simo

回答

3

實際上你需要setComponent到另一個應用程序啓動服務。例如,

活動在com.xyz.app1:

Intent mServiceIntent = new Intent(); 
String pkg = "com.xyz.app2"; 
String cls = "com.xyz.app2.MyService"; 
mServiceIntent.setComponent(new ComponentName(pkg, cls)); 
startService(mServiceIntent); 

你並不需要設置操作或類別,如果你指定一個特定組成部分。確保您的服務在清單中正確定義。

+0

我會嘗試這種方法 – Simo

+0

好吧,讓我知道它是否適合你。 –

+0

謝謝你的解決方案!沒關係! – Simo

0

您可以使用該組件名稱:

Intent intent = new Intent(YOUR_ACTION_HERE); 
intent.setComponent(new ComponentName("your.package.name", 
       "your.package.name.YourService")); 
statService(intent); 
+0

該解決方案與前一個類似。謝謝! @francesc – Simo

相關問題