vendredi 21 août 2015

AsyncTask invoke method error Can't create handler inside thread that has not called Looper.prepare

I try to invoke a method and get response in doInBackground (AsyncTask), but always get error (at line (**) below):

 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

This is example code:

private class DoWorkflowOperation extends AsyncTask<Void, Void, byte[]> {

    final File _optimizedDexOutputPath = this.getDir("outdex", Context.MODE_PRIVATE);
    String _apkfilePath = "/data/data/com.example/files/exam.apk";
    String _className = "com.example.test.ConvertBytes";
    String _methodToInvoke = "convertByteToByte";       

    @Override
    protected byte[] doInBackground(Void... voids) {

        DexClassLoader dLoader = new DexClassLoader(_apkfilePath,
                    _optimizedDexOutputPath.getAbsolutePath(),
                    null, ClassLoader.getSystemClassLoader().getParent());

        try {
            Class<?> loadedClass = dLoader.loadClass(_className);
            Object obj = (Object) loadedClass.newInstance();
            Method m = loadedClass.getDeclaredMethod(_methodToInvoke, byte[].class);
            m.setAccessible(true);

            byte[] send2AppBytes = readFileToByte();                
            byte[] responseBytes = (byte[]) m.invoke(obj,send2AppBytes);   // (**)

            return responseBytes;

        } catch (IllegalAccessException e) {
            e.getCause().printStackTrace();
        } catch (InvocationTargetException e) {
            e.getCause().printStackTrace();
        }catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(byte[] wr) {
        //

    }
}

I tried with Thread, Runnable but could not make it work. If I paste the code invoke method into main thread that all work fine but UI must wait for response because of that i want to run on independent thread.





Aucun commentaire:

Enregistrer un commentaire