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 "NetworkOnMainTh开发者_开发知识库readException".
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?
import android.os.StrictMode;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
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
).
Just a note: making synchronous calls on the UI thread is horrible programming practice for production code - you should always make asynchronous call in a background thread and never have to force a psuedo-synchronous call in the manner shown below.
In fact, I'm only posting this because I'm miffed that the API throws an exception when I make a network call using the AndroidHttpClient on the UI thread for brief functional testing before complete implementation. Ie. Testing an operation meant for a background thread without adding frivolous code to make it a background thread when you don't yet need it.
final Object lock = new Object();
new Thread(new Runnable() {
public void run() {
synchronized(lock) {
// Perform call
// lock.notify();
}
}
}).start();
synchronized(lock) {
try {
lock.wait();
}
catch{}
}
精彩评论