Search code examples
androidokhttpnetworkonmainthread

Network connection on main thread - alternative in this case?


I need to get a color in the server and set it as a theme

setTheme(colorId);

it needs to be set inside onCreate() and at the beginning to work.

I'm doing this:

    protected void onCreate(Bundle savedInstanceState) {

        getColor();
    ...
    }

public void getColor() {

        StrictMode.ThreadPolicy tp = StrictMode.ThreadPolicy.LAX; //force network on main thread
        StrictMode.setThreadPolicy(tp);

                    OkHttpClient client = new OkHttpClient();
                    okhttp3.Request request = new okhttp3.Request.Builder()
                            .url("http://myip/color.php")
                            .build();
                    try {
                        okhttp3.Response response = client.newCall(request).execute();

                        String color = response.body().string();
                        setTheme(color);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    }
}

So, I'm forcing a network connection on main thread because if I add doInBackground(), on response... it will run after my onCreate() and the color will not be set.

My question here is:

1) Is it the only way?

2) Can I do things without force network on main thread?

3) I'd like an example, if possible, not just: "yes, it is possible" or "do XYZ" because I'm new to Android and without examples it doesn't help much.


Solution

  • You shouldn't make any network requests on the main thread. Instead, you should show the user a progress bar whilst it fetches the data on a background thread.

    BUT: Since you have to set the theme in the onCreate() it means you can't show the user any progress because the views won't be inflated at that point. A better solution would be to get the color from the server on a previous activity and pass it in as and intent parameter.