2013-10-05 30 views
1

即使我正在運行新線程,我在主線程異常中獲取此網絡。任何想法這裏有什麼問題?即使在新線程上的主線程異常網絡

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

使用AsyncTask代替線程,可以解決你的問題 – Richa

+0

正如@Richa所說的,使用'AsyncTask'。如果你真的想用'Thread'嘗試使用'start()'而不是'run()'。 – Squonk

+0

可能重複的[android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – JoxTraex

回答

5

run()執行於當前(主)線程的方法,而不是start(),運行在一個新的線程run方法。

+0

你能否提供任何文檔鏈接以獲得更深入的觀點? –

+1

@RaviBhatt - 從[主題](http://developer.android.com/reference/java/lang/Thread.html):「在'開始()'方法必須調用實際執行新的主題。」 – ianhanniballake

1

正如之前發佈的運行線程執行的主線程,並按照新的Android的API,執行主線程上的IO操作或網絡操作將拋出此錯誤。因此,需要在異步任務中執行網絡調用,並在後執行方法中返回或更新GUI。

相關問題