How to solve the problem of Android Not Responsive (ANR)?

0

When something runs on the main thread and it takes more than 5 seconds, the "app is not responding?" dialog box is something that a mobile programmer quickly learns.

In a synchronization routine, the user accesses an API, the json obtained and the process of writing in SQLite all takes about 3 minutes, it is a process triggered by the user and he knows he has to wait ...

I'm using Volley for the network (although I have loopj http client in this project as well) and a progressDialog for the user to realize that something is being processed plus the Android message can cause it to stop everything.

I understand that after the request is made what happens inside the onResponse (JSONObject response) is in the Therad UI, I then "solved" the problem by putting everything inside an AsyncTask, "I solved it" because I noticed that nothing has changed. / p>

Follow the code below, how to resolve the case?

public class SincronizarPresenter implements MVPSincronizar.PresenterImpl {

private MVPSincronizar.ViewImpl view;
TarefaAsync mTarefaAsync;

public SincronizarPresenter() {
}

@Override
public void sincronizarFromRemoteServer() {

    if(!Helper.isNetworkAvailable(getContext())){
        showToastErro("Sem conexão");
    } else {
        if (mTarefaAsync == null || mTarefaAsync.getStatus() != AsyncTask.Status.RUNNING) {
            mTarefaAsync = new TarefaAsync(this);
            mTarefaAsync.execute();
        }
    }
}

@Override
public void fimSincronismo(Boolean status) {
   hideProgress();
   if (status){
       showToast("Fim do processo de sincronização");
   } else {
       showToastErro("Ocorreu um erro.");
   }
}

@Override
public void hideProgress() {
    view.hideProgress();
}

@Override
public void showProgress(String mensagem) {
   view.showProgress(mensagem);
}

@Override
public void showToast(String mensagem) {
   view.showToast(mensagem);
}

@Override
public void showToastErro(String mensagem) {
    view.showToastErro(mensagem);
}

@Override
public Context getContext() {
    return (Context) view;
}

@Override
public void setView(MVPSincronizar.ViewImpl view) {
   this.view = view;
}

@Override
public User getUser() {
    return view.getUser();
}

@Override
public void showQtdClientes(int qtd) {
    view.showQtdClientes(qtd);
}

@Override
public void showQtdVeiculos(int qtd) {
   view.showQtdVeiculos(qtd);
}

@Override
public void showQtdOrdens(int qtd) {
   view.showQtdOrdens(qtd);
}

@Override
public void showQtdTipoVeiculos(int qtd) {
    view.showQtdTipoVeiculos(qtd);
}

@Override
public void showQtdEquipamentos(int qtd) {
    view.showQtdEquipamentos(qtd);
}

@Override
public void showQtdPortas(int qtd) {
    view.showQtdPortas(qtd);
}


//AsyncTask
public static class TarefaAsync extends AsyncTask<Void, Integer, Void>{

    private static final String TAG = TarefaAsync.class.getSimpleName();

    public static final int STATE_ERROR=0;
    public static final int STATE_LOADING=1;
    public static final int STATE_EMPTY=2;
    public static final int STATE_UPDATING=3;
    public static final int STATE_END=100;

    private final MVPSincronizar.PresenterImpl presenter;
    private final OrdemServicoService ordemServicoService;
    private final TipoVeiculoService tipoVeiculoService;
    private final TipoAtendimentoService tipoAtendimentoService;
    private final ClienteService clienteService;
    private final CustomSharedPreference shared;


    public TarefaAsync(MVPSincronizar.PresenterImpl presenter) {
        this.presenter = presenter;
        ordemServicoService = new OrdemServicoService(presenter.getContext());
        tipoVeiculoService = new TipoVeiculoService(presenter.getContext());
        tipoAtendimentoService = new TipoAtendimentoService(presenter.getContext());
        clienteService = new ClienteService(presenter.getContext());
        shared = ((Aplicacao) presenter.getContext().getApplicationContext()).getShared();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        switch (values[0]) {
            case STATE_ERROR:
                presenter.hideProgress();
                presenter.showToastErro("Ocorreu um erro");
                break;
            case STATE_LOADING:
                presenter.showProgress("Sincronizando, aguarde...");
                break;
            case STATE_EMPTY:
                presenter.hideProgress();
                break;
            case STATE_UPDATING:
                presenter.showProgress("Aguarde, atualizando dados...");
                break;
            case 10:
                presenter.showQtdClientes(values[1]);
                break;
            case 11:
                presenter.showQtdOrdens(values[1]);
                break;
            case 12:
                presenter.showQtdEquipamentos(values[1]);
                break;
            case 13:
                presenter.showQtdVeiculos(values[1]);
                break;
            case 14:
                presenter.showQtdPortas(values[1]);
                break;
            case 15:
                Log.d(TAG, "Tipos de veiculos = " + String.valueOf(values[1]) );
                presenter.showQtdTipoVeiculos(values[1]);
                break;
            case STATE_END:
                presenter.hideProgress();
                presenter.fimSincronismo(true);
                break;
        }
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        //presenter.hideProgress();
    }

    @Override
    protected Void doInBackground(Void... params) {
        publishProgress(STATE_LOADING);

        // Apagar todos os registros
        tipoAtendimentoService.DeleteTodos();
        statusService.DeleteTodos();
        portasVeiculoService.DeleteTodos();
        clienteService.DeleteTodos();
        tipoVeiculoService.DeleteTodos();
        contatoService.DeleteTodos();
        equipamentoService.DeleteTodos();
        veiculoService.DeleteTodos();
        ordemServicoService.DeleteTodos();
        errosService.DeleteTodos();
        sincronismoService.DeleteTodos();
        //
        shared.setDataAtualizacao((int) new Date().getTime());
        shared.setDataSincronismo((int) new Date().getTime());

        Map<String, String> parametros = new HashMap<String,String>();

        parametros.put(Helper.TOKEN, presenter.getUser().getToken());
        parametros.put(Helper.SERVIDOR, "1");
        parametros.put("completo", "1");

        CustomRequest serverRequest = new CustomRequest(
                Helper.PATH_TO_SINCRONIZAR,
                parametros,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        publishProgress(STATE_EMPTY);
                        try {
                            Log.d(TAG, "Json Response " + response);
                            if (response.getJSONArray("errors").length() == 0) {
                                publishProgress(STATE_UPDATING);
                                JSONObject json = response.getJSONObject("results");
                                Iterator keys = json.keys();

                                Integer[] recupdate = new Integer[2];
                                recupdate[0] = 0;
                                recupdate[1] = 0;

                                while(keys.hasNext()){
                                    String currentDynamicKey = (String)keys.next();
                                    JSONArray records = null;
                                    Log.d(TAG, "Chave: " + currentDynamicKey );

                                    switch (currentDynamicKey) {
                                        case "tipos_veiculo":
                                            try {
                                                records = json.getJSONArray("tipos_veiculo");
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            SincronizaTipoDeVeiculos(records);
                                            Log.d(TAG, "Tipos de veiculos " + String.valueOf(records.length()) );
                                            recupdate[0]=15;
                                            recupdate[1]=records.length();
                                            publishProgress(recupdate);
                                            break;
                                        case "status":
                                            try {
                                                records = json.getJSONArray("status");
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            SincronizaStatus(records);
                                            Log.d(TAG, "Status " + String.valueOf(records.length()) );
                                            break;
                                        case "contatos":
                                            try {
                                                records = json.getJSONArray("contatos");
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            SincronizaContatos(records);
                                            Log.d(TAG, "Contatos " + String.valueOf(records.length()) );
                                            break;
                                        case "veiculos":
                                            try {
                                                records = json.getJSONArray("veiculos");
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            SincronizaVeiculos(records);
                                            Log.d(TAG, "Veiculos " + String.valueOf(records.length()) );
                                            recupdate[0]=13;
                                            recupdate[1]=records.length();
                                            publishProgress(recupdate);
                                            break;
                                        case "clientes":
                                            try {
                                                records = json.getJSONArray("clientes");
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            SincronizaClientes(records);
                                            Log.d(TAG, "Clientes " + String.valueOf(records.length()) );
                                            recupdate[0]=10;
                                            recupdate[1]=records.length();
                                            publishProgress(recupdate);
                                            break;
                                        case "portas_veiculo":
                                            try {
                                                records = json.getJSONArray("portas_veiculo");
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            SincronizaPortasVeiculos(records);
                                            Log.d(TAG, "Portas " + String.valueOf(records.length()) );
                                            recupdate[0]=14;
                                            recupdate[1]=records.length();
                                            publishProgress(recupdate);
                                            break;
                                        case "equipamentos":
                                            try {
                                                records = json.getJSONArray("equipamentos");
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            SincronizaEquipamentos(records);
                                            Log.d(TAG, "Equipamentos " + String.valueOf(records.length()) );
                                            recupdate[0]=12;
                                            recupdate[1]=records.length();
                                            publishProgress(recupdate);
                                            break;
                                        case "ordens_servico":
                                            try {
                                                records = json.getJSONArray("ordens_servico");
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            SincronizaOrdemServico(records);
                                            Log.d(TAG, "O. Servicos " + String.valueOf(records.length()) );
                                            recupdate[0]=11;
                                            recupdate[1]=records.length();
                                            publishProgress(recupdate);
                                            break;
                                        case "tipos_atendimento":
                                            try {
                                                records = json.getJSONArray("tipos_atendimento");
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            SincronizaTipoAtendimento(records);
                                            Log.d(TAG, "Tipos de atendimento " + String.valueOf(records.length()) );
                                            break;
                                    }
                                }
                                shared.setDataAtualizacao( new Date().getTime() );
                                shared.setDataSincronismo( new Date().getTime() );
                                publishProgress(100);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        publishProgress(STATE_ERROR);
                        Log.d(TAG, "Erro - mensagem: " + error.getMessage());
                        error.printStackTrace();
                    }
                });

        serverRequest.setRetryPolicy(new DefaultRetryPolicy(
                Helper.MY_SOCKET_TIMEOUT_MS * 2,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        VolleySingleton.getInstance(presenter.getContext()).addToRequestQueue(serverRequest);

        return null;
    }

    private void SincronizaTipoDeVeiculos(JSONArray records){

        for (int i = 0; i < records.length(); i++ ){
            JSONObject jRecord = null;
            try {
                jRecord = records.getJSONObject(i);
                // Preenche o objeto Tipo veiculo
                TipoVeiculo entity = new TipoVeiculo(jRecord.getInt("id"),
                        Helper.removeAccents(jRecord.getString("descricao")),
                        jRecord.getInt("servidor"));
                tipoVeiculoService.Inserir(entity);
            } catch (JSONException e) {
                salvaErros(e);
                e.printStackTrace();
            }
        }
    }

    private void SincronizaTipoAtendimento(JSONArray records){

        for (int i = 0; i < records.length(); i++ ){
            JSONObject jRecord = null;
            try {
                jRecord = records.getJSONObject(i);
                // Preenche o objeto Tipo veiculo
                TipoAtendimento entity = new TipoAtendimento(jRecord.getInt("id"),
                        Helper.removeAccents(jRecord.getString("descricao")),
                        0);
                tipoAtendimentoService.Atualizar(entity);

            } catch (JSONException e) {
                salvaErros(e);
                e.printStackTrace();
            }
        }
    }

    private void SincronizaStatus(JSONArray records){

        for (int i = 0; i < records.length(); i++ ){
            JSONObject jRecord = null;
            try {
                jRecord = records.getJSONObject(i);
                // Preenche o objeto Tipo veiculo
                br.com.grupoecs.tecnico.entidades.Status entity = new
                        br.com.grupoecs.tecnico.entidades.Status(jRecord.getInt("id"),
                          Helper.removeAccents(jRecord.getString("descricao")),
                           0);
                statusService.Atualizar(entity);

            } catch (JSONException e) {
                salvaErros(e);
                e.printStackTrace();
            }
        }
    }

    private void SincronizaVeiculos(JSONArray records){

        for (int i = 0; i < records.length(); i++ ){
            JSONObject jRecord = null;
            try {
                jRecord = records.getJSONObject(i);

                // Preenche o objeto veiculo
                Veiculo entity = new Veiculo();
                entity.setId(jRecord.getInt("id"));
                entity.setFrota(jRecord.getString("frota"));
                entity.setPlaca(jRecord.getString("placa"));
                entity.setEquipamento(jRecord.getInt("equipamento"));
                entity.setTipoVeiculo(jRecord.getInt("tipo_veiculo"));

                veiculoService.Inserir(entity);

            } catch (JSONException e) {
                salvaErros(e);
                e.printStackTrace();
            }
        }
    }

    private void SincronizaOrdemServico(JSONArray records){

        for (int i = 0; i < records.length(); i++ ){
            JSONObject jRecord = null;
            try {
                jRecord = records.getJSONObject(i);

                Date ldData = new Date();

                // Preenche o objeto veiculo
                OrdemServico entity = new OrdemServico();
                entity.setId(jRecord.getInt("id"));
                entity.setCodigo(jRecord.getString("codigo"));
                entity.setCliente(jRecord.getInt("cliente"));
                entity.setStatus(jRecord.getInt("status"));
                entity.setTipo_atendimento(jRecord.getInt("tipo_atendimento"));
                entity.setProcedimento_realizado(jRecord.getString("procedimento_realizado"));
                entity.setPendencia(jRecord.getString("pendencia"));
                entity.setObservacao(jRecord.getString("observacao"));

                ordemServicoService.Inserir(entity);

            } catch (JSONException e) {
                salvaErros(e);
                e.printStackTrace();
            }
        }
    }


    private void SincronizaClientes(JSONArray records){
        for (int i = 0; i < records.length(); i++ ){
            JSONObject jRecord = null;
            try {
                jRecord = records.getJSONObject(i);
                Cliente cliente = new Cliente();
                cliente.setId(jRecord.getInt("id"));
                cliente.setNome(Helper.removeAccents(jRecord.getString("nome")));
                clienteService.Inserir(cliente);

            } catch (JSONException e) {
                salvaErros(e);
                e.printStackTrace();
            }
        }
    }

}

}
    
asked by anonymous 24.01.2018 / 16:51

0 answers