【问题标题】:Choreographer skipping frames(upto 400!) even after using AsyncTask即使在使用 AsyncTask 之后,编舞者也会跳帧(最多 400 个!)
【发布时间】:2020-08-15 19:26:36
【问题描述】:

我正在尝试从远程服务器获取数据,尝试在 SQLite 中创建数据库并更新我的共享首选项。我将前面提到的所有操作都放在了 AsyncTask 中,理论上它必须在 UI(主)线程之外的单独线程上运行。另外,我在实际的 Android 设备上运行该应用程序,而不是在模拟器上。

我在日志中得到以下信息:

I/Choreographer: Skipped 229 frames!  The application may be doing too much work on its main thread.

源代码:

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {

    TextView errorMessage;
    Button retryAgainButton;

    SharedPreferences sharedPrefs;

    @SuppressLint("StaticFieldLeak")
    public class FirstRunDBCreator extends AsyncTask<Void, Void, String> {
        String result = "";
        private Exception e = null;

        @Override
        protected void onPreExecute() {
            sharedPrefs = getApplicationContext().getSharedPreferences("android.content.SharedPreference", Context.MODE_PRIVATE);
            if(!sharedPrefs.contains("firstRun")) {
                sharedPrefs.edit().putBoolean("firstRun", true).apply();
            }
        }

        @Override
        protected String doInBackground(Void... voids) {
            String result = "";
            // All the heavy operations here
            // Fetching the data from the server here and creating/ storing data in my SQLite database
            // I have also used transactions and SQLite preparedStatement to increase the insert speed
            return result;
        }

        @SuppressLint("SetTextI18n")
        @Override
        protected void onPostExecute(String s) {
            // Closing the database connections and handling any exceptions here
            // Updating the UI elements such as diplaying the complete message or the visibility of a textview
        }
    }

    public void initializeTheUIComponents() {
        errorMessage = findViewById(R.id.errorMessage);
        retryAgainButton = findViewById(R.id.retryAgainButton);
        retryAgainButton.setClickable(false);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initializeTheUIComponents();
        // Running the jumpToNextActivity after the screen and the UI elements have been rendered
        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                try {
                    new FirstRunDBCreator().execute().get();
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

虽然,除了两个 TextView 和所有繁重的处理都在后台线程中执行的事实之外,我没有任何高分辨率图像或任何繁重的前端组件,是什么导致编舞者跳过帧?是因为我在onCreate() 方法中调用了AsyncTask,还是因为我在onPreExecute()onPostExecute()? 中有一些代码是Runnable run() 还是任何其他原因?

【问题讨论】:

    标签: java android android-asynctask


    【解决方案1】:

    当您调用 .get() 方法时,它将在当前线程上运行,在这种情况下是 UI 线程,因此请尝试在没有 get 的情况下执行。

    【讨论】:

    • 这立即解决了跳帧问题。尽管如此,你能解释一下为什么get()对此负责吗?是不是因为在后台运行任务后,在收到结果后,它又开始在 UI(主)线程中工作?它本质上是同步的还是阻塞的?最后,我们应该什么时候真正使用get()
    • @RishabParmar 因为当您调用 get() 方法时,它会再次开始在主线程上工作并等待工作完成。这就是为什么它需要时间。
    【解决方案2】:

    建议为 asyncTask 使用 weakReference 上下文,像这样:

     /.../in your activity
      WeakReference<Context> baseContext = new WeakReference<>(MainActivity.this);
    

    更新了 FirstRunDBCreator 类

    public class FirstRunDBCreator extends AsyncTask<Void, Void, String> {
    private WeakReference<Context> context;
    
    public FirstRunDBCreator(WeakReference<Context> context) {
        this.context = context;
    }
    
    @Override
    protected String doInBackground(Void... voids) {
        Context baseContext = context.get();
        SharedPreferences sp = baseContext.getSharedPreferences("android.content.SharedPreference", Context.MODE_PRIVATE);
        if(!sp.contains("firstRun")) {
            sp.edit().putBoolean("firstRun", true).apply();
        }
        String result = "";
        //initialize DataBase from baseContext
    
    
        return result;
    }
    
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        context.clear();
    }
    

    在你的活动中

      /.../
      new FirstRunDBCreator(baseContext).execute();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-04
      • 1970-01-01
      • 2018-11-20
      • 2013-05-14
      相关资源
      最近更新 更多