java - 防止繁重进程时崩溃

标签 java android

我正在制作一个基于 map 的应用程序,用户经常会在 map 上加载超过 10k 个多边形。唯一的问题是,向 map 添加多边形的唯一方法是在 UI 线程中,这意味着当我添加它们时,它要么卡住 5 - 10 秒,要么崩溃。

我已经准备好接受它只需要花费一些时间来加载,但是当系统努力防止崩溃甚至卡住时,有没有办法可以减慢 for 循环?我想到的一种方法是在 for 循环上设置一个短暂的延迟,但这不太理想,因为它需要花费更长的时间才能保证安全。

          protected void onPostExecute(HashMap<String, ArrayList> result){
            for(String key : result.keySet()){
                List<PolygonOptions> thisList = result.get(key);
                for(PolygonOptions poly: thisList){
                    Polygon thisPoly = mMap.addPolygon(poly);
                }
            }
          }

最佳答案

这里有一个关于我如何解决这个问题的伪代码:

private final Handler handler_render_data = new Handler ();
private int actualItemRendering;
private static final int HANDLER_RUN_DELAY = 1000;



    @Override
protected void onCreate(Bundle savedInstanceState)  {
    super.onCreate(savedInstanceState);

    //  Display the message telling the user to wait
    //  This Linear Layout includes a text and cover all teh screen
    lyt_report_progress = (LinearLayout) findViewById (R.id.lyt_report_progress);
    lyt_report_progress.setVisibility (View.VISIBLE);
    lyt_report_progress.requestFocus ();
    lyt_report_progress.setClickable (true);

    //  Your code calling your async task

}

//  Your callback from your async task
private void callbackHere (Data myData) {

    this.localMyData = myData;

    //  You store your data locally and start the rendering process
    actualItemRendering = 0;
    handler_render_data.post (createDataFromTaskResult);
}


private Runnable createDataFromTaskResult = new Runnable () {

    @Override
    public void run () {

        if (actualItemRendering < myData.length ()) {

            //  Render your data here

            //  Continue with the next item to render
            actualItemRendering++;
            handler_render_data.post (createDataFromTaskResult);

        } else {
            //  All fields were rendered
            handler.postDelayed (hideProgressBarTask, HANDLER_RUN_DELAY);
        }
    }
};

private Runnable hideProgressBarTask = new Runnable () {

    @Override
    public void run () {

        lyt_report_progress.setVisibility (View.GONE);

    }
};

希望对您有帮助。

关于java - 防止繁重进程时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46875583/

相关文章:

java - Spring BOOT 错误

java - Android:通过 android 数据绑定(bind)将 lambda 传递给回收器适配器

java - 自定义对话与键盘 Android

java - maven如何只编译修改过的java文件?

javascript - 不同进程虚拟机的 JIT 编译器如何实现事件窥视?

java - 在 Linux 上运行的 Java 应用程序中使用 PGP 兼容的文件加密的推荐解决方案?

java - 尽管代码执行成功,但回滚不适用于 GAE 中使用 Jdo 的事务

java - 如何清除内存以防止java.lang.OutOfMemoryError

java - 只有创建 View 层次结构的原始线程才能触及它的 View - Android

Android ClassNotFound 和 android.view.InflateException :