即使我正在運行新線程,我在主線程異常中獲取此網絡。任何想法這裏有什麼問題?即使在新線程上的主線程異常網絡
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;
}
}
使用AsyncTask代替線程,可以解決你的問題 – Richa
正如@Richa所說的,使用'AsyncTask'。如果你真的想用'Thread'嘗試使用'start()'而不是'run()'。 – Squonk
可能重複的[android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – JoxTraex