Skip to content Skip to sidebar Skip to footer

Prevent Crashing While Heavy Process

I am making a Map based app where users would often load over 10k polygons on the map. The only problem is that the only way to add a polygon to the map is in the UI thread, which

Solution 1:

Here there is a pseudo code about how I solve this:

privatefinalHandlerhandler_render_data=newHandler ();
privateint actualItemRendering;
privatestaticfinalintHANDLER_RUN_DELAY=1000;



    @OverrideprotectedvoidonCreate(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 taskprivatevoidcallbackHere(Data myData) {

    this.localMyData = myData;

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


privateRunnablecreateDataFromTaskResult=newRunnable () {

    @Overridepublicvoidrun() {

        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);
        }
    }
};

privateRunnablehideProgressBarTask=newRunnable () {

    @Overridepublicvoidrun() {

        lyt_report_progress.setVisibility (View.GONE);

    }
};

Hope it helps you.

Solution 2:

Split it into several tasks and execute each task on main thread separately. I.e.

for (int i = 0; i < 20; ++i) {
    runOnUiThread(newRunnable() { .. process 1/20 of your work });
}

You don't need to add a delay. Also you can experiment with granularity, probably better to increase it from 1/20.

Post a Comment for "Prevent Crashing While Heavy Process"