How to resolve android.os.NetworkOnMainThreadException?
This question already has an answer here:
The Android OS does not allow heavy process to execute in the main thread/UI Thread because the application will slow down, decreasing performance and the application will lag.
However, you can execute it in an AsyncTask as shown here. Do your process/call your function in the doInBackground
of this asyncTask.
private class Download extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("Hi", "Download Commencing");
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Downloading Database...");
String message= "Executing Process";
SpannableString ss2 = new SpannableString(message);
ss2.setSpan(new RelativeSizeSpan(2f), 0, ss2.length(), 0);
ss2.setSpan(new ForegroundColorSpan(Color.BLACK), 0, ss2.length(), 0);
pDialog.setMessage(ss2);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
//INSERT YOUR FUNCTION CALL HERE
return "Executed!";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("Hi", "Done Downloading.");
pDialog.dismiss();
}
}
and call it as such: new Download().execute("");
from another function.
You can do away with the Progress Dialog. I personally like it because I know my process will finish (like data loading) before the user can do anything, ensuring that no error occurs when the user interacts with the program.
将此代码用于活动
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
链接地址: http://www.djcxy.com/p/29542.html