使用AsyncTask时冻结应用程序

时间:2017-01-13 12:59:23

标签: android android-asynctask freeze

我从API下载了大量数据,并希望提高效率,因此我在一个asyncTask中获得前100个记录,然后在另一个asyncTask中获得另外几千个(500个部分)loadListAsynchronously();看起来相同作为没有content,progress,loadContent();函数的loadData函数,但这个函数不是问题 - 没有loadListAsynchronously();应用程序在frezee下载第一个数据后运行顺利。我尝试添加交易,但这对我没有帮助。

private void loadData() {
        DottedProgressBar progressBar = (DottedProgressBar) findViewById(R.id.loadIngDots);
        progressBar.startProgress();
        content = (LinearLayout)findViewById(R.id.activity_main) ;
        progress = (RelativeLayout) findViewById(R.id.progressPage) ;
        AsyncTask<String, Void, String> read =new AsyncTask<String, Void, String>() {
            SharedPreferences  keyValues;
            @Override
            protected void onPreExecute() {
                content.setVisibility(View.GONE);
                 keyValues = getSharedPreferences(Settings.MODEL_LAST_CALL, Context.MODE_PRIVATE);
                DisplayMetrics displaymetrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                height = displaymetrics.heightPixels;
                width = displaymetrics.widthPixels;

                super.onPreExecute();
            }

            @Override
            protected String doInBackground(String... params) {
                modelList = new ArrayList<>();

                Map<String,String> options= new HashMap<>();
                options.put("limit",String.valueOf(AMOUNT_OF_LOADED_modelS));


                ApiHelper.getModelWithParams(new Callback<ModelApiEnvelope>() {
                    @Override
                    public void onResponse(Call<ModelApiEnvelope> call, Response<ModelApiEnvelope> response) {
                        Log.i(TAG,"First call model Get response");
                     final   ModelApiEnvelope envelope = response.body();
                      if(envelope==null)
                          Toast.makeText(MainActivity.this,getString(R.string.server_down_explanation),Toast.LENGTH_SHORT).show();
                        else{
                        try {
                           final Dao<Model,Integer> modelDAO  = getHelper().getmodelDAO();
                           final Dao<Submodel,Integer> submodelDAO=getHelper().getsubmodelDAO();
                            TransactionManager.callInTransaction(getHelper().getConnectionSource(),
                                    new Callable<Void>() {
                                        public Void call() throws Exception {
                        modelList=envelope.getData();
                                            Log.i(TAG,"LoadData loop Start");
                        for( final model m: modelList){
                            m.setLogo(m.getLogo()+"?width="+width/2+"&height="+height);
                            m.setLanguage(m.getLanguage().substring(0,2));
                            if(m.getLanguage().equals("uk"))
                                m.setLanguage("ua");
                            if(m.getsubmodels().size()!=0){
                                    for(final submodel e: m.getsubmodels()){
                                        e.setLanguage(m.getLanguage());
                                        submodelDAO.createOrUpdate(e);
                                    }
                                  }
                            try {
                                                modelDAO.createOrUpdate(m);
                               }catch (SQLException e) {e.printStackTrace();}  
                        }

                                            return null;}
                                    });
                            if(envelope.getData().isEmpty()){
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                long time = System.currentTimeMillis();
                                editor.putString(Settings.model_LAST_CALL , Long.toString(time));
                                editor.apply();
                            }
                           else
                                loadListAsynchronously();
                        }  catch (SQLException e) {
                            Log.i(TAG," message "+e.getMessage()) ; e.printStackTrace();
                        }}
                        loadContent();
                        content.setVisibility(View.VISIBLE);
                        progress.setVisibility(View.GONE);

                    }
                    @Override
                    public void onFailure(Call<modelApiEnvelope> call, Throwable t) {
                        Log.i(TAG,"ERROR"+ t.getMessage());
                        Toast.makeText(MainActivity.this,getString(R.string.server_down_explanation),Toast.LENGTH_LONG).show();

                        loadContent();


                    }
                },MainActivity.this,options, keyValues.getString(lang,"0"));
           return null;
            }
   @Override
         protected void onProgressUpdate(Void... values) {
             super.onProgressUpdate(values);
         }

         @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

        }
    };
    read.execute();
}

更新:添加了方法跟踪 enter image description here

更新2:删除交易解决了我的问题。似乎将数千个存储的制作事务转换为数据库冻结Ui。

1 个答案:

答案 0 :(得分:0)

Retrofit1和AsyncTask中的回调不兼容。您必须通过以下方式修改API接口:

public interface Api {
    void getModelWithParams(Callback<Something> callback);
}

对此:

public interface Api {
    Something getModelWithParams();
}

然后Retrofit将不提供异步执行支持,您可以在AsyncTask.doInBackground方法中执行该行方法。

其他选项是保持该接口定义并直接调用Retrofit方法(不使用AsyncTask包装)。问题是你的进一步逻辑是否不重,因为onResponse将在UI线程上执行,导致你的冻结,并且通常是你问题的根本原因。