无法启动服务意图

6

我已经阅读了大约100个关于这个问题的问题和答案,但似乎无法使其正常工作。 我正在尝试从Activity启动Service。 我的清单文件似乎没问题,我启动Service的方式也似乎正确。 在LogCat中显示以下错误:

ActivityManager(1296): Unable to start service Intent
{ cmp=com.exercise.AndroidClient/com.client.Communication }: not found

我正在尝试通过在我的Activity中调用以下内容来启动服务:

startService(new Intent(getApplicationContext(), Communication.class));

Service是以下内容:

public class Communication extends Service {
    public Communication() {
        super();
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("Service", "Created service");
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("Service", "onStartCommand called");
        return START_STICKY;
    }
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

我的清单文件中的条目是:

<?xml version="1.0" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.exercise.AndroidClient" android:versionCode="1"
    android:versionName="1.0">

    <application android:icon="@drawable/sms" android:label="@string/app_name" >

        <activity> ... </activity>

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

    </application>
</manifest>

非常感谢您的建议。


通过将startService(new Intent(getApplicationContext(), Communication.class));更改为startService(new Intent(getApplicationContext(), com.client.Communication.class));并在清单文件中进行相同的更改,解决了此问题。我以为由于所有文件都在同一个包中,所以这样做没问题...看来不是这样。 - Shaun
3个回答

4

通讯类在哪里?

在您的清单文件中,您声明了一个带有android:name=".Communication"的服务,这意味着您的服务类应该位于com.exercise.AndroidClient.Communication中。

请检查包名是否正确。注意,“.”(点)是指您包的根目录(即在清单文件中声明的包)。因此,例如,如果您的包名为com.exercise.AndroidClient,而您的服务类位于com.exercise.AndroidClient.services.Communication下,则需要像这样声明服务:

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

或者指定完整的软件包:

<service android:enabled="true" android:name="com.exercise.AndroidClient.services.Communication" />

谢谢!我在一段时间前已经成功解决了这个问题。但是,我无法在发布后的8小时内回答自己的问题。 - Shaun

0
此外,如果您的服务恰好存在于您正在引用的库项目中,请检查您的project.properties文件。
您需要添加以下行:
manifestmerger.enabled=true

0

我遇到了同样的错误,原因是服务没有在AndroidManifest.xml中定义。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接