StrictMode of android
分类:Android
阅读 (2,305)
Add comments
7月 122012
StrictMode is a developer tool which used to detect accident in program. For example, if you do internet access or local file operation in the UI directly, the strictmode mechanism will throw an error to the application.
StrictMode is used default since Android 3.0(HoneyComb).
example of a wrong case
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public void downloadHtml(View view) throws IOException{ String response = ""; DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://svn1.bcoder.com"); HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } TextView tv = (TextView)findViewById(R.id.textView1); tv.setText(response); } |
If you request an url like above, your app will crashes.
So the right thing we do this is we can run the internet request in thread(Threads, AsyncTask, Handler), I give a simple by AsyncTask.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
public void downloadHtml(View view) throws IOException{ DownloadHtmlTask task = new DownloadHtmlTask(); task.execute(new String[] { "http://svn1.bcoder.com" }); } private class DownloadHtmlTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String response = ""; InputStream in = null; for (String url : urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { URL urlget = new URL(url); HttpURLConnection conn = (HttpURLConnection)urlget.openConnection(); conn.connect(); in = (conn.getInputStream()); BufferedReader buffer = new BufferedReader(new InputStreamReader(in)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } } catch (Exception e) { e.printStackTrace(); } } return response; } @Override protected void onPostExecute(String result) { TextView textView = (TextView)findViewById(R.id.textView1);; textView.setText(result); } } |
It looks very troublesome when we just debug the program, so we can also use a simple code to disable ThreadPolicy to avoid errors.
1 2 3 4 5 6 7 |
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } |
…