首页 > 解决方案 > APK安装期间的服务注册

问题描述

最近我一直在搞乱Android内部。为了更好地了解 APK 的安装方式,我决定制作一个测试 APK 并在 root ADB shell 的帮助下手动安装:

重新启动设备后,我可以使用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()论点thisIntent但它没有帮助。该服务已在 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.MyServicefor .MyService、删除enabled标志并使用一个行标记(以 结尾/>)而不是<service>...</service>. 这些都没有帮助。

我的问题是:

标签: androidandroid-intentserviceapk

解决方案


没关系,在我问这个问题的第二天,我发现了一个解决方案。

如果您遇到这样的问题,出于某种原因,您需要像这样启动服务:

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 }

如果有人知道这种行为的原因,请与我分享,因为我不知道为什么会发生这种情况。


推荐阅读