如何从另一个Android应用程序启动Android服务 [英] How to start android service from another Android app

查看:340
本文介绍了如何从另一个Android应用程序启动Android服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从另一个Android应用程序(API 17)启动服务时遇到问题. 但是,如果我确实从shell运行'am',则该服务会正常启动.

I'm having a problem starting a service from another Android app (API 17). However, if I do run 'am' from the shell, the service starts fine.

# am startservice com.xxx.yyy/.SyncService
Starting service: Intent { act=android.intent.action.MAIN cat=
[android.intent.category.LAUNCHER] cmp=com.xxx.yyy/.SyncService }
(service starts fine at this point)
# am to-intent-uri com.xxx.yyy/.SyncService
intent:#Intent;action=android.intent.action.MAIN;
category=android.intent.category.LAUNCHER;
component=com.xxx.yyy/.SyncService;end

因此,当我在代码中执行相同的操作时,似乎并没有遗漏任何意图:

So, it doesn't look like I'm missing anything from the intent when I do the same in the code:

Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.setComponent(new ComponentName("com.xxx.yyy", ".SyncService"));
ComponentName c = ctx.startService(i);
if (c == null) { Log.e(TAG, "failed to start with "+i); }

我得到的是(该服务当时未运行):

What I get is (the service is not running at that time):

E/tag( 4026): failed to start with Intent { 
act=android.intent.action.MAIN 
cat=[android.intent.category.LAUNCHER] 
cmp=com.xxx.yyy/.SyncService }

我没有针对该服务的意图过滤器,并且我不想设置它,我实际上是想了解通过其组件名称启动它在做错什么,或者可能是什么原因造成的不可能这样做.

I don't have an intent filter on the service, and I don't want to set one up, I'm really trying to understand what am I doing wrong starting it through its component name, or what may be making it impossible to do so.

推荐答案

您应该能够像这样启动服务:

You should be able to start your service like this:

Intent i = new Intent();
i.setComponent(new ComponentName("com.xxx.yyy", "com.xxx.yyy.SyncService"));
ComponentName c = ctx.startService(i);

如果要指定特定组件,则无需设置ACTION或CATEGORY.确保清单中正确定义了您的服务.

You don't need to set ACTION or CATEGORY if you are specifying a specific component. Make sure that your service is properly defined in the manifest.

这篇关于如何从另一个Android应用程序启动Android服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆