android - APK安装期间的服务注册
问题描述
最近我一直在搞乱Android内部。为了更好地了解 APK 的安装方式,我决定制作一个测试 APK 并在 root ADB shell 的帮助下手动安装:
- 我创建了一个应用程序目录
/data/app/com.example.myapp-y6zjC4JYhJKOph-sl-G5QA==
并将 APK 复制到那里(asbase.apk
)。目录后缀是从另一台设备上的“正确”安装复制的,即使我认为它可能是任何东西,因为它是 base64 编码的随机字符串。 - 我创建目录
/data/data/com.example.myapp
及其子目录cache
和code_cache
- 我修改
packages.xml
并packages.list
在其中添加了一个关于我的应用程序的条目(同样,从另一个“正确”安装复制)。
重新启动设备后,我可以使用adb shell pm list packages | grep myapp
找到我的包来验证应用程序是否已安装。我可以使用adb shell am start -n com.example.myapp/.MainActivity
.
但是,当我想在我的应用程序中实现一项服务(从 自动启动MainActivity.onStart
)时,该服务不会启动并在日志中打印一条错误消息:
ActivityManager: Unable to start service Intent { cmp=com.example.myapp/.MyService } U=0: not found
该服务不显示在dumpsys
任何一个:
# adb shell dumpsys activity service com.example.myapp
No services match: com.example.myapp
我打电话的方式startService
如下:
Log.e("MYAPP", "About to start the service"); // This is printed to the log
Intent intent = new Intent(getApplicationContext(), MyService.class);
startService(intent);
我试图改变getApplicationContext()
论点this
,Intent
但它没有帮助。该服务已在 AndroidManifest.xml 中正确注册:
<application ... >
...
<activity android:name="com.example.myapp.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.myapp.MyService" android:enabled="true"></service>
</application>
同样,我尝试在 Manifest 中更改一些内容:更改com.example.myapp.MyService
for .MyService
、删除enabled
标志并使用一个行标记(以 结尾/>
)而不是<service>...</service>
. 这些都没有帮助。
我的问题是:
- 为什么系统看不到我的服务?
- 在 APK 安装过程中,有没有办法“注册”服务?我需要修改其他一些配置文件吗?
解决方案
没关系,在我问这个问题的第二天,我发现了一个解决方案。
如果您遇到这样的问题,出于某种原因,您需要像这样启动服务:
Intent intent = new Intent(getApplicationContext(), MyService.class);
intent.setClassName("com.example.myapp", "com.example.myapp.MyService"); // add this line
startService(intent);
我不知道为什么会发生这种情况,意图似乎是相同的。当我在调用之前和之后打印intent.toString()
到日志时intent.setClassName
,两行都如下所示:
Intent { cmp=com.example.myapp/.MyService }
如果有人知道这种行为的原因,请与我分享,因为我不知道为什么会发生这种情况。
推荐阅读
- c++ - 如何检查位枚举中是否存在值?
- javascript - 如何在 D3 饼图中动态放置标签
- visual-c++ - msft c 未解决的外部绑定以在 win32 控制台应用程序中使用 dll 函数
- xamarin.forms - 如何在默认选择的母版页中显示侧边菜单而不点击 xamarin 表单中的母版页项目?
- c# - 当我们通过 id 获取记录时使用 Linq 查询如何将该值分配给另一列?
- php - 如何在不硬编码我的 mysqli 查询的情况下更新我的表单
- javascript - classList.add() 不会在单击事件中立即激活
- git - GIT 存储库迁移冲突(重命名/重命名)
- javascript - free-jqgrid 方法和参数列表?
- python - 为什么appium在新浪新闻文本框中输入中文会乱码