【问题标题】:ExceptionInInitializerError when instanciating AsyncTask inside Plugin.execute()在 Plugin.execute() 中实例化 AsyncTask 时出现 ExceptionInInitializerError
【发布时间】:2013-01-08 17:32:55
【问题描述】:

我正在开发一个应用程序,在其中我使用cordova Api 在Sencha 代码和*Android native Code* 之间进行通信。

在我的插件的 execute 方法中,我正在启动一个 AsyncTask( 用于设备注册),但我在 第 36 行 (实例化) 中得到了 ExceptionInInitializerError TaskDeviceRegistration)。

RegistrationDevicePlugin

public class DeviceRegistrationPlugin extends Plugin {

    public static final String TAG = "DeviceRegistrationPlugin";
    public static final String ACTION_REGISTER_DEVICE = "registerDeviceAction";

    protected String callBackMethod;

    @Override
    public PluginResult execute(String action, JSONArray args, String callBackId) {

        String token;
        if(action.equals(ACTION_REGISTER_DEVICE)) {
            try {
                token = args.getString(0);
                if(token != null) {
                    // launch the task to register device
                    SharedPreferences prefs = cordova.getActivity().getSharedPreferences(WebServiceRequest.PREFS_IDENTIFICATION, Context.MODE_PRIVATE);
                    prefs.edit().putString(WebServiceRequest.PREF_TOKEN_PARAM, token).commit();
                    TaskRegisterDevice task = new TaskRegisterDevice(cordova.getActivity());// this is the line 36
                    task.execute();

                    // tell the plugin that the callBack will be executed after the task
                    // has finished his work.
                    this.callBackMethod = callBackId;
                    PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
                    pluginResult.setKeepCallback(true);
                    return pluginResult;
                }
                else {
                    return new PluginResult(Status.ERROR, "token required");
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
            }
        }
        else {
            // invalid action sended to the plugin
            return new PluginResult(PluginResult.Status.INVALID_ACTION);
        }
    }


    /**
     * asynctask to register the device
     * @author houcine
     * 
     */
    class TaskRegisterDevice extends AsyncTask<Void, Void, Boolean> {

        protected Context context;

        public TaskRegisterDevice(Context context) {
            this.context = context;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                return WebServiceRequest.RegisterDevice(context);
            } catch (JSONException e) {
                e.printStackTrace();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return true;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            // return new plugin result when synchronization done
            Log.d(TAG, "resultat DeviceRegistration : "+result + " , \ncallBackMethod : "+callBackMethod);
            PluginResult pluginResult = new PluginResult(
                    PluginResult.Status.OK, result);
            pluginResult.setKeepCallback(false);
            success(pluginResult, callBackMethod);
        }

    }

}

清单文件:

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

     <supports-screens
     android:largeScreens="true"
     android:normalScreens="true"
     android:smallScreens="true"
     android:resizeable="true"
     android:anyDensity="true"
     />

     <uses-sdk android:minSdkVersion="5" android:targetSdkVersion="16"/>
     //other stuff : declaration of <application> tag , activities , services...etc
>

和 logCat:

01-01 06:54:26.251: E/AndroidRuntime(6189): FATAL EXCEPTION: Thread-31
01-01 06:54:26.251: E/AndroidRuntime(6189): java.lang.ExceptionInInitializerError
01-01 06:54:26.251: E/AndroidRuntime(6189):     at com.myapp.plugins.DeviceRegistrationPlugin.execute(DeviceRegistrationPlugin.java:36)
01-01 06:54:26.251: E/AndroidRuntime(6189):     at org.apache.cordova.api.PluginManager$1.run(PluginManager.java:192)
01-01 06:54:26.251: E/AndroidRuntime(6189):     at java.lang.Thread.run(Thread.java:1096)
01-01 06:54:26.251: E/AndroidRuntime(6189): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
01-01 06:54:26.251: E/AndroidRuntime(6189):     at android.os.Handler.<init>(Handler.java:121)
01-01 06:54:26.251: E/AndroidRuntime(6189):     at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
01-01 06:54:26.251: E/AndroidRuntime(6189):     at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
01-01 06:54:26.251: E/AndroidRuntime(6189):     at android.os.AsyncTask.<clinit>(AsyncTask.java:152)
01-01 06:54:26.251: E/AndroidRuntime(6189):     ... 3 more

注意:该应用程序在 HTC ONE S、HTC ONE X、SAMSUNG GALAXY S II、SAMSUNG GALAXY SIII 上运行良好,android sdk 版本:4.0 或更高,但不适用于 android 设备版本如:2.2.2、2.3.5、2.3.3

【问题讨论】:

    标签: android plugins android-asynctask cordova-2.0.0


    【解决方案1】:

    AsyncTask 应该在 UI 线程上创建和执行。看起来 DeviceRegistrationPlugin.execute() 方法是在主线程之外调用的,这就是您收到错误的原因。

    您可以尝试这样修复它:

    cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            TaskRegisterDevice task = new TaskRegisterDevice(cordova.getActivity());
            task.execute();
        }
    });
    

    【讨论】:

    • 感谢您的回复,但如何解释代码在 android 4.0 或更高版本上 100% 正常工作,但对于 android 2.3.3 、 2.2.2 、 2.3.5 、 2.3.6 是不是吗?
    • 根据AsyncTask 文档The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN。我想这就是解释。
    • 我知道,但我已经在 ICS 上对其进行了测试,它也可以工作。好的,我将对逻辑进行一些更改并强制它在 UIThread 上运行以避免此问题。谢谢:)
    猜你喜欢
    • 2016-02-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多