2016-03-07 67 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