Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way where I can call an network API call on main thread in android honeycomb?

I am creating a service and an app. App can call a method on a service. The method is calling an API and based on API, giving the result. Since the app is targetting android 3.0, I am getting "NetworkOnMainThreadException".

My requirement is such a way that I cannot call the method in background thread from app. Also the method on service should return a boolean based on API call.

is there a way where I can call an network API call on main thread in android honeycomb?

like image 827
Nandakumar R Avatar asked Nov 27 '22 01:11

Nandakumar R


2 Answers

import android.os.StrictMode;

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
like image 57
Vishal Gaurav Avatar answered Dec 24 '22 10:12

Vishal Gaurav


I am creating a service and an app.

A service is a part of an "app". I am going to assume that you meant "activity" where you wrote "app".

My requirement is such a way that I cannot call the method in background thread from app.

Then whoever created this "requirement" is an idiot and should be fired. Then, remove this requirement. Always perform network operations on a background thread.

Since the app is targetting android 3.0, I am getting "NetworkOnMainThreadException".

That is because StrictMode is on to warn you about these things by default. While the warning is new, the problem exists on all versions of Android your code is running on.

is there a way where I can call an network API call on main thread in android honeycomb?

This should never be done in production code. Rework your application to do the network I/O on a background thread (e.g., AsyncTask).

like image 21
CommonsWare Avatar answered Dec 24 '22 10:12

CommonsWare