Android IntentService 从未被调用

标签 android android-service

我有一个 IntentService,我想在 onCreate 时启动它。这是一种一劳永逸的方法,它调用一个网站,然后(可能)通过下载管理器开始下载。我不相信我的服务正在启动,因为我没有看到其中的任何日志语句。我的 list 中有该服务,与 main 相同的包。它也没有出现在我的 logcat 中(另一个线程说它应该出现)。

创建时:

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    Intent heartbeat = new Intent(this, Heartbeat.class);
    startService(heartbeat);
}

*我也尝试过 this.startService(heartbeat);而且它也不起作用。

list :

<application
    android:debuggable="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <service android:name=".Heartbeat" android:enabled="true"/>

    <activity
        android:name=".MainActivity"
        android:configChanges="keyboardHidden|orientation|screenSize"
        android:label="@string/title_activity_main" >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

*有或没有 android:enabled 标志没有区别

IntentService 的启动:

public class Heartbeat extends IntentService
{
    public Heartbeat()
    {
        super("Heartbeat");
        Log.v("SUPER", "SUPER");
    }

    @Override
    protected void onHandleIntent(Intent intent)
    {
        Log.v("HERE", "HERE");
        //do other stuff

这些日志语句都不会显示在控制台/logcat 中,并且我的服务从未访问 Web 服务器(此代码之前位于 asynctask 中并且正在运行)。关于我做错了什么有什么想法吗?

编辑 - 我确实在所有消息中看到来自标记 ActivityManager 的警告,指出“无法启动服务 Intent { act=com.example.vs_1.Heartbeat }:未找到”。然而,我在该消息中看到的几乎所有建议都是将 list 放入应用程序标记中,我已经这样做了。

最佳答案

啊,剧情变得更复杂了!

“无法启动服务”是一个错误,即使它被标记为警告。

出现这种情况是因为系统找不到具有所列出名称的类。在这种情况下, 它是 com.example.vs_1.Heartbeat。

为了确保您拥有该类,您需要一个包含的 Hearbeat.java 文件

包 com.example.vs_1;

公共(public)类Heartbeat扩展了IntentService...

在您的 list 中,如果您的元素包含该属性 package="com.example.vs_1",那么你可以说

请注意“Heartbeat”之前的句点(“.”)。

如果您使用“package”的其他值,那么您必须说

/com.example.vs_1.Heartbeat”,其中是“package”的值。

从这里应该可以清楚地看出,您应该为您的类选择一个主包名称,并为“package”值使用相同的名称。

关于Android IntentService 从未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13183922/

相关文章:

java - 无法解析 ondestroy 方法内的方法 'stopService(android.content.Intent)'

java - 在不同的 Activity 中传递来自服务器的不同响应

android - 在 Android 中保留对系统服务的成员引用是否有益?

android - ImageView 在 getView() 时崩溃自定义适配器

android - Xamarin 表格 : iOS Linking

android - 位图内存泄漏 - Android

Android 线程和服务优先级

android - 持久服务

android - 颜色值无效?android :colorControlNormal

android - 无法进行简单的 Android 声音测试