I have two Android mobile devices one v2.3 api 9 and one v3.1 honeycomb I want to post an http api link for sms code. It turns that 开发者_开发技巧i got an error in honeycomb and the other mobile works fine this is the code
public void sendSMS(String phone_num, int password)
{
try
{
HttpClient hc = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.google.com/");
hc.execute(post); // I got an error here
}
catch(IOException e)
{
Log.e("error", "error");
}
}
StrictMode is enabled in HoneyComb, you must disable it to avoid NetworkOnMainThreadException
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
but that´s not recommended, use Asynctask, here you can find an example:
http://developer.android.com/reference/android/os/AsyncTask.html
You're experiencing this because of a new feature in Android Honeycomb. If you look through your logs you will see you are getting a NetworkOnMainThreadException
Exception
In Android Honeycomb there is a new application policy that restricts the execution of time consuming calls on the main thread.
Please check your exception stack if you see the following: StrictMode$AndroidBlockGuardPolicy.onNetwork
What helped me was to read this and then fix my code to not use the main execution thread for the HTTP call.
100% working solution!
Place the following codes above your super.onCreate
under protected void onCreate
method:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Idea from Jorgesys! Thanks to him! Hope it solves your problem~
I had the same problem and cleared using Async Task.So dont call httppost request in main thread Instead use Async task to do http post.It also gives you more comfortable .link:http://www.vogella.com/articles/AndroidPerformance/article.html
精彩评论