Android严格模式

时间:2013-03-21 10:26:22

标签: android android-asynctask android-strictmode

我使用AsyncTask编写了一个关于JSON解析的简单代码。我只是在TextView中显示回复。我不知道这是对还是错。它在GingerBread上工作并在JellyBean上显示NetworkOnMainThreadException。如果我使用StrictMode,它将在JellyBean上工作并在GingerBread上关闭力量。如何编写支持Android 3.0及以上Android 3.0的代码。

public class MainActivity extends Activity {
TextView tv;
Button b;
InputStream is = null;

DefaultHttpClient client;
HttpGet get;
HttpResponse response;
HttpEntity entity;
StringBuffer buffer;

@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  //    StrictMode.setThreadPolicy(policy);
    tv = (TextView) findViewById(R.id.texty);
    b = (Button) findViewById(R.id.buttonGET);

    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            MyOperation mytask = new MyOperation();
            mytask.execute();
        }
    });

}

private class MyOperation extends AsyncTask<String, Void, String> {
    ProgressDialog dialog = new ProgressDialog(MainActivity.this);

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        dialog.setMessage("Loading...");
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        client = new DefaultHttpClient();
        get = new HttpGet("http://www.google.com");
        try {
            response = client.execute(get);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        entity = response.getEntity();

        try {
            is = entity.getContent();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub

        super.onPostExecute(result);
        dialog.dismiss();
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(is));
        StringBuffer buffer = new StringBuffer();
        String line = null;
        do {
            try {
                line = reader.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            buffer.append(line);
        } while (line != null);
        tv.setText(buffer);
    }

}

}

3 个答案:

答案 0 :(得分:2)

   public class MainActivity extends Activity {
     TextView tv;
    Button b;
    InputStream is = null;

    DefaultHttpClient client;
    HttpGet get;
    HttpResponse response;
HttpEntity entity;
StringBuffer buffer;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //StrictMode.ThreadPolicy policy = new 
  //    StrictMode.setThreadPolicy(policy);
    tv = (TextView) findViewById(R.id.texty);
    b = (Button) findViewById(R.id.buttonGET);

    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            MyOperation mytask = new MyOperation();
            mytask.execute();
        }
    });

}

private class MyOperation extends AsyncTask<String, Void, String> {
    ProgressDialog dialog = new ProgressDialog(MainActivity.this);

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        dialog.setMessage("Loading...");
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
StringBuffer buffer = new StringBuffer();
        // TODO Auto-generated method stub
        client = new DefaultHttpClient();
        get = new HttpGet("http://www.google.com");
        try {
            response = client.execute(get);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        entity = response.getEntity();

        try {
            is = entity.getContent();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    BufferedReader reader = new BufferedReader(
                new InputStreamReader(is));

        String line = null;
        do {
            try {
                line = reader.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            buffer.append(line);
        } while (line != null);

        return buffer.tostring();
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub

        super.onPostExecute(result);
        dialog.dismiss();

        tv.setText(result);
    }}

}

否则您正在主线程中运行读取线操作

答案 1 :(得分:1)

is中创建InputStream entity和Entity doInBackground()本地字段变量作为结果返回您想要在TextView上设置的字符串...以及{{1你得到结果(字符串)并直接在TextView中设置它。

答案 2 :(得分:1)

您应该在doInBackground函数中读取inputStream数据,而不是在onPostExecute中读取。因此,在doInBackground中构造StringBuffer会将所有行追加到它并返回StringBuffer.toString作为结果。在onPostExecute中,您将获得什么字符串作为参数。