尝试初始化服务时出错(扩展了IntentService类)

时间:2012-04-09 23:38:15

标签: android service intentservice

我尝试在Android中使用Service,我的应用程序包含一个带按钮的Activity,以便在我按下它时可以执行操作。 核心组件是ExtractingURLService,它扩展了IntentService框架类。 我已经覆盖了onHandleIntent()方法,因此它可以正确处理传递给它的意图。 代码:

public  class ExtractingURLService extends IntentService {

    private static final String TAG = "ExtractingURLService"; 

    public ExtractingURLService(String name) {
        super("ExtractingURLService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // do something here !
        }
    }



}

Android Manifest文件是:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="example.service.urlextraction"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ServiceExample02Activity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".ExtractingURLService" android:enabled="true"></service>

    </application>
</manifest>

在我唯一的Activity类中,我使用:

来调用服务
Intent startServiceIntent =  new Intent(this, ExtractingURLService.class);
startService(startServiceIntent);

这就是我的全部工作,但在部署时,我收到的运行时错误是:

  

04-09 16:24:05.751:ERROR / AndroidRuntime(1078):引起:   java.lang.InstantiationException:   example.service.urlextraction.ExtractingURLService

我该怎么做?

2 个答案:

答案 0 :(得分:1)

添加服务的完整路径

<service android:name="com.foo.services.ExtractingURLService" android:enabled="true"></service>

Intent Service应如下所示:

package com.foo.services;

import android.app.IntentService;
import android.content.Intent;

public class ExtractingURLService extends IntentService {

    private static final String TAG = "ExtractingURLService";

    public ExtractingURLService() {
        super("ExtractingURLService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // do something here !
    }
}

答案 1 :(得分:0)

您可以添加try and catch块以避免崩溃。它对我有用

try {
      Intent intent = new Intent(DashboardActivity.this, MyService.class);
      startService(intent);

     }catch (IllegalStateException e){

    }catch (Exception ee){

   }