android - 如何从另一个 Android 应用程序启动 android 服务

标签 android android-intent

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

# 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

所以,当我在代码中执行相同操作时,看起来我没有遗漏任何 Intent :

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

我得到的是(当时服务没有运行):

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

我在服务上没有 Intent 过滤器,我不想设置一个,我真的想了解我做错了什么,通过它的组件名称启动它,或者可能是什么这是不可能的。

最佳答案

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

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

如果您指定特定组件,则无需设置 ACTION 或 CATEGORY。确保您的服务在 list 中正确定义。

关于android - 如何从另一个 Android 应用程序启动 android 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17316232/

相关文章:

android - 无法使用 adb 从 Bluestacks 应用程序播放器中提取 .apk 文件

Android Intent 启动失败

java - 将文件上传到保管箱(通过同步)

android - 是否有相当于 "Android Localization Files Editor"的 android-studio?

Android 获取非 Play Store 应用列表

android - 在android中创建渐变边框?

android - 如何使用 dip 在 webview css 中指定图像大小?

android - 如何切换到其他正在运行的应用程序

Android 多重通知避免更新时闪烁

java - Android-如何以编程方式检查 Intent 过滤器的类型?