ClassCastException在服务中启动AsyncTask

时间:2013-09-04 10:37:07

标签: android android-asynctask

我在启动启动AsyncTask的服务时遇到此错误 - 但我有另一个类似的服务和AsyncTask工作正常。两个服务都在清单中声明。 如果有人可以提出可能存在的问题,我会很感激。经过大量阅读后,我认为它与AsyncTask的结构/参数有关,所以我尝试了一些没有快乐的变化 - 但我不确定我是否朝着正确的方向前进。 我没有明确地在任何地方扩展应用程序。

09-04 09:13:46.444: E/AndroidRuntime(1190): FATAL EXCEPTION: main
09-04 09:13:46.444: E/AndroidRuntime(1190): java.lang.RuntimeException: Unable to start service couk.jit.currencycheck1.ServiceClassXML@4602fc20 with Intent { flg=0x4 cmp=couk.jit.currencycheck1/.ServiceClassXML (has extras) }: java.lang.ClassCastException: android.app.Application
09-04 09:13:46.444: E/AndroidRuntime(1190):     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3063)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at android.app.ActivityThread.access$3600(ActivityThread.java:125)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2096)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at android.os.Looper.loop(Looper.java:123)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at android.app.ActivityThread.main(ActivityThread.java:4627)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at java.lang.reflect.Method.invokeNative(Native Method)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at java.lang.reflect.Method.invoke(Method.java:521)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at dalvik.system.NativeStart.main(Native Method)
09-04 09:13:46.444: E/AndroidRuntime(1190): Caused by: java.lang.ClassCastException: android.app.Application
09-04 09:13:46.444: E/AndroidRuntime(1190):     at couk.jit.currencycheck1.GetXMLTask.<init>(GetXMLTask.java:52)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at couk.jit.currencycheck1.ServiceClassXML.onStartCommand(ServiceClassXML.java:24)
09-04 09:13:46.444: E/AndroidRuntime(1190):     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3053)
09-04 09:13:46.444: E/AndroidRuntime(1190):     ... 10 more

此服务可以在其下运行AsyncTask。

public class ServiceClass extends Service {
SharedPreferences prefs = null;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplication().getApplicationContext());
    boolean run = prefs.getBoolean("running", false);
    if (!run)
        stopSelf();
    else {
        new AsyncNetworkConnection(this.getApplication().getApplicationContext(), true).execute("");
    }
    return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}
}

AsyncTask有效。

public class AsyncNetworkConnection extends AsyncTask<String, String, String> {

public AsyncNetworkConnection(Context ct, boolean asService) {
...
}

@Override
protected void onPostExecute(String result) {
...
}

protected String doInBackground(String... arg0) {
String result = null;
...
results = fetchHTML(arg0[0]);
return results;
}

private String fetchHTML(String urlStr) throws URISyntaxException,
        ClientProtocolException, IOException, Exception {
String result = null;
...
return result;
}

}

这是提供错误的服务。如果我注释掉'newGetXMLTask'行,我就不会收到错误。如果我用其他AsyncTask替换它我没有得到错误(但当然后续错误)。日志消息显示在logcat中。

public class ServiceClassXML extends Service {

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("DBG", "ServiceClassXML started");
    prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplication().getApplicationContext());
    boolean run = prefs.getBoolean("running", false);
    if (!run)
        stopSelf();
    else {
        new GetXMLTask(this.getApplication().getApplicationContext(), true).execute("abc");
//          new AsyncNetworkConnection(this.getApplication().getApplicationContext(), true).execute("");
    }
    return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}
}

提供错误的AsyncTask的基础知识。

public class GetXMLTask extends AsyncTask<String, Void, List<RateData>> {

public GetXMLTask(Context ct, boolean asService) {
    this.context = (Activity) ct;   //as context can be cast to activity
    prefs = PreferenceManager.getDefaultSharedPreferences(context);
    dataSource = prefs.getInt("srcs", 0);
    runAsService = asService;
    restoredTextFrom = prefs.getString("fromCurr", null);
    restoredTextTo = prefs.getString("toCurr", null);
}

@Override
protected void onPostExecute(List<RateData> rates) {
...
}

@Override
protected List<RateData> doInBackground(String... urls) {
xml = getXmlFromUrl(url);
...
}

private String getXmlFromUrl(String urlString) {
...
return output.toString();
}
}

清单包括:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="couk.jit.currencycheck1.MainMenu"
        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="couk.jit.currencycheck1.ServiceClass"
        android:enabled="true" />
    <service
        android:name="couk.jit.currencycheck1.ServiceClassXML"
        android:enabled="true" />
...
</application>

2 个答案:

答案 0 :(得分:3)

您正在

中传递应用程序上下文
new GetXMLTask(this.getApplication().getApplicationContext(), true).execute("abc");

并且将其强制转换为活动上下文,例如this.context = (Activity) ct;

这给你例外

Caused by: java.lang.ClassCastException: android.app.Application

答案 1 :(得分:0)

你应该为Context创建变量。

 Context ctx = getApplicationContext();

并在

中使用此ctx
 new GetXMLTask(ctx, true).execute("abc");