Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing GoogleMap from outside the UI thread in Android

I'm using Google Map Android API v2 for my android application. There I have initialize GoogleMap as follows inside onCreate

SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mGoogleMap = fm.getMap();

In my application, I need to do some background tasks and I'm using AsybcTask for that. While progress through the background tasks I want to update the map. Please refer the following sample.

@Override
    protected Void doInBackground(Void...voids) {
        while(Condition)
        {
            mGoogleMap.clear();
            mGoogleMap.addMarker(marker);
            Thread.sleep(5000);
        }
     }

I know that I can't directly access UI components inside the doInBackground method. Common UI components like buttons, edittexts, textviews can be accessed by parsing the context of the application to the AsyncTask class. But I can't figure out a way to access GoogleMap from the doInBackground method. Could you please give me a solution.

like image 406
ANJ Avatar asked Nov 16 '14 17:11

ANJ


1 Answers

if your AsyncTask is a part of the Activity you can simply use runOnUiThread method, like this:

@Override
    protected Void doInBackground(Void...voids) {
        while(Condition)
        {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mGoogleMap.clear();
                    mGoogleMap.addMarker(marker);
                    Thread.sleep(5000);
                }
            });
        }
     }
like image 182
romtsn Avatar answered Nov 15 '22 05:11

romtsn