即使在新线程上网络主线程异常

时间:2013-10-05 04:29:16

标签: android

我在主线程异常上获得此网络,即使我正在运行新线程。知道这里出了什么问题吗?

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    final EditText txturl=(EditText) findViewById(R.id.txtedit);
    Button btngo=(Button) findViewById(R.id.btngo);
    final WebView wv=(WebView) findViewById(R.id.webview);

    btngo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Thread t=new Thread(new  Runnable() 
            {

                public void run() 
                {

                    try 
                    {
                        InputStream in=OpenHttpConnection("http://google.com");
                        byte [] buffer = new byte[10000];
                        in.read(buffer);

                        final String s=new String(buffer);

                        wv.post(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub

                                wv.loadData(s, "text/html", "utf-8");

                            }
                        }) ;



                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            });

             t.run();

        }
    });


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private InputStream OpenHttpConnection (String urlString) throws IOException
{
    URL url=new URL(urlString);
    InputStream in=null;
    int response=-1;

    URLConnection uc=url.openConnection();

    if(!(uc instanceof HttpURLConnection))
        throw new IOException("Not an http connection");

    HttpURLConnection httpCon=(HttpURLConnection) uc;

    httpCon.connect();

    response=httpCon.getResponseCode();
    if(response==HttpURLConnection.HTTP_OK)
        in=httpCon.getInputStream();

    return in;



}
}

2 个答案:

答案 0 :(得分:6)

run()在当前(主)线程上执行方法,而不是start(),它在新线程上运行run方法。

答案 1 :(得分:1)

如前所述,运行线程在主线程上执行,并且根据新的android apis,在主线程上执行IO操作或网络操作将引发此错误。因此,您需要在异步任务中执行网络调用,并在后执行方法上返回或更新GUI。