How to use AsyncTask on Android?

0

I'm trying to make my application download an XML (RSS Feed) and read its tags to display it on the home screen. However, the application closes after downloading before attempting to start the onPostExecute method of AsyncTask getFeed and AsyncTask readXML of Tags). And if I try to just check the application version, I use AsyncTask to download the file and read its contents, check the version and ask the user if he wants to perform the application update. However, if I have already run AsyncTask UpdateApp , I can not run the low APK without the application closing.

Complete Code: Pastebin

AsyncTask<Void, Void, String> getFeed = new AsyncTask<Void, Void, String>(){
        @Override
        protected String doInBackground(Void... params) {
            String retorno = "não";
            try {
                // Baixar Feed
                URL url = new URL("http://www.ipoema.tumblr.com/rss");
                File file = new File(PATH + "iPoema.xml");
                file.delete();
                URLConnection ucon = url.openConnection();
                InputStream is = ucon.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayBuffer baf = new ByteArrayBuffer(50);
                lenghtOfFile = ucon.getContentLength();
                int current = 0;
                while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
                    progress = current;
                }
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(baf.toByteArray());
                fos.close();
                retorno = "sim";
            } catch (IOException e) {
                showMessage(e.getClass().getName(), "Erro ao tentar realizar o download do arquivo.");
            }
            return retorno;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s.equals("sim")) {
                try {
                    lerXML.execute();
                } catch (Exception e) {
                    showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do arquivo.");
                }
            }
        }
    };

    AsyncTask<Void, Void, String> lerXML = new AsyncTask<Void, Void, String>(){
        @Override
        protected String doInBackground(Void... params) {
            String state = "erro";
            try {
                // Ler XML
                showMessage("iPoema", "Arquivo lido com sucesso");
                File f = new File(PATH + "iPoema.xml");
                SAXBuilder sb = new SAXBuilder();
                Document d = sb.build(f);
                Element mural = d.getRootElement();
                List<Element> elements = mural.getChildren("channel");
                Iterator<Element> i = elements.iterator();
                int x = 0;
                //for (int x = 0; x <= elements.size(); x++) {
                while (i.hasNext()) {
                    //Element node = (Element) elements.get(x);
                    Element node = (Element) i.next();
                    Element item = node.getChild("item");

                    titulo[x] = item.getChildText("title");
                    texto[x] = item.getChildText("description");
                    autor[x] = item.getChildText("category");
                    x++;
                }
                state = "ok";
            } catch (JDOMException e) {
                showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do XML.");
            } catch (IOException e) {
                showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do XML.");
            }
            return state;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s.equals("ok")) {
                try {
                    // Títulos
                    TextView titulo1 = (TextView) findViewById(R.id.titulo1);
                    TextView titulo2 = (TextView) findViewById(R.id.titulo2);
                    TextView titulo3 = (TextView) findViewById(R.id.titulo3);
                    TextView titulo4 = (TextView) findViewById(R.id.titulo4);

                    // Textos
                    TextView texto1 = (TextView) findViewById(R.id.texto1);
                    TextView texto2 = (TextView) findViewById(R.id.texto2);
                    TextView texto3 = (TextView) findViewById(R.id.texto3);
                    TextView texto4 = (TextView) findViewById(R.id.texto4);

                    // SetText
                    titulo1.setText(getTitulo(0));
                    texto1.setText(getTexto(0)+"\n\n#"+getAutor(0)+"\n\n");

                    titulo2.setText(getTitulo(1));
                    texto2.setText(getTexto(1)+"\n\n#"+getAutor(1)+"\n\n");

                    titulo3.setText(getTitulo(2));
                    texto3.setText(getTexto(2)+"\n\n#"+getAutor(2)+"\n\n");

                    titulo4.setText(getTitulo(3));
                    texto4.setText(getTexto(3)+"\n\n#"+getAutor(3)+"\n\n");

                    // Exibe
                    titulo1.setVisibility(TextView.VISIBLE);
                    texto1.setVisibility(TextView.VISIBLE);

                    titulo2.setVisibility(TextView.VISIBLE);
                    texto2.setVisibility(TextView.VISIBLE);

                    titulo3.setVisibility(TextView.VISIBLE);
                    texto3.setVisibility(TextView.VISIBLE);

                    titulo4.setVisibility(TextView.VISIBLE);
                    texto4.setVisibility(TextView.VISIBLE);
                } catch (Exception e) {
                    showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do arquivo.");
                }
            }
        }
    };

    AsyncTask<Void, Void, String> atualizaApp = new AsyncTask<Void, Void, String>(){
        @Override
        protected String doInBackground(Void... params) {
            String versao = "0";
            try {
                // Baixar iPoema.txt
                URL url = new URL("http://www.xadees.xpg.com.br/iPoema.txt");
                File file = new File(PATH + "iPoema.txt");
                file.delete();
                URLConnection ucon = url.openConnection();
                InputStream is = ucon.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayBuffer baf = new ByteArrayBuffer(50);
                lenghtOfFile = ucon.getContentLength();
                int current = 0;
                while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
                    progress = current;
                }
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(baf.toByteArray());
                fos.close();

                // Ler iPoema.txt
                StringBuilder text = new StringBuilder();
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;
                while ((line = br.readLine()) != null) {
                    text.append(line);
                }
                versao = text.toString();
            } catch (IOException e) {
                showMessage(e.getClass().getName(), "Erro ao tentar realizar o download do arquivo.");
            } catch (Exception e) {
                showMessage(e.getClass().getName(), "Erro ao tentar realizar a leitura do arquivo.");
            }

            return versao;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            int vAtual = Pi.versionCode;
            int vAPK = Integer.parseInt(s);

            if (vAtual < vAPK) {
                try {
                    // Baixar
                    URL url = new URL("http://www.xadees.xpg.com.br/iPoema%20for%20Android.apk");
                    File file = new File(PATH + "iPoema.apk");
                    file.delete();
                    URLConnection ucon = url.openConnection();
                    InputStream is = ucon.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    ByteArrayBuffer baf = new ByteArrayBuffer(50);
                    lenghtOfFile = ucon.getContentLength();
                    int current = 0;
                    while ((current = bis.read()) != -1) {
                        baf.append((byte) current);
                        progress = current;
                    }
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(baf.toByteArray());
                    fos.close();

                    // Instalar
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(new File(PATH + "iPoema.apk")), "application/vnd.android.package-archive");
                    //java.lang.Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "adb install -r " + PATH + "iPoema.apk"});
                    //proc.waitFor();
                    startActivityForResult(intent,0);
                } catch (IOException e) {
                    showMessage(e.getClass().getName(), "Erro ao tentar realizar o download do pacote.");
                }
            } else {
                showMessage("iPoema", "iPoema já está atualizado.");
            }
        }
    };
    
asked by anonymous 25.03.2014 / 02:33

4 answers

2

Looking quickly at your code, I noticed that you initialize all AsyncTasks into a separate Thread .

AsyncTasks are routines that make it easy to use Threads on Android. They execute a code in the background *, in the call doInBackground and are able to make changes in the thread of the UI in the call onPostExecute .

In this way, your code has two problems:

- Create a new thread to call a asyncTask , which is not necessary, and can cause problems. -Modifications made in process doInBackground , when they should be performed only in onPostExecute

Also, keep in mind that Android limits the number of asyncTasks that can run in parallel. Only 1 for android 3.0 on

    
25.03.2014 / 13:32
1

What Felipe wanted to say would be to create an interface and make its Activity implement this interface, and when creating the Asynctask instance pass the reference of its activity to it (its Asynctask class must have a reference to the interface object), so in the onPostExecute method you call the method implemented by your activity passing the parameter (if any). This way you would be making the threads "communicate".

I use it that way and never had a problem.

    
03.02.2015 / 13:14
0

ALWAYS separate the "responsibilities" of each action! Create two distinct classes for AsyncTask.

Remember, AsynkTask is a thread separate from the main Thread.

In order to receive the return of your Async, you can create an interface with the OnResult (Boolean result) method and implement it in the calling activity, so you can make the new call from your other AsyncTask.

    
20.06.2014 / 15:33
0

Well, I did not quite understand what you did, but a possible solution would be the following code:

Create a class to do what you want and extends AsyncTask, since you can only run one at a time.

private class NomeDaClass extends AsyncTask {

    private  int tipoDeFuncao ;

    public NomeDaClasse(int a) {
       this.tipoDeFuncao = a;
    }

    @Override
    protected Object doInBackground(Object... params) {

      if (typeofFunction == 1) {
        atualizaApp();
      } else if (typeofFunction == 2) {
        lerXML();
      } else if (typeofFunction == 3) {
        getFeed();
      }

      return null;
    }

}

So, in your normal class, you create the functions that you want to run in the background, and within them you call the constructor of your class that inherits from AsyncTask:

public void atualizaApp() {    
    new Connection(1).execute();
}

public void lerXML(parameters) {
    new Connection(2).execute();

}

public void getFeed(parameters) {
    new Connection(3).execute();

}

It's not the best, but it's a solution. :)

    
20.06.2014 / 21:23