gpt4 book ai didi

android - 即使在新线程上,主线程上的网络异常

转载 作者:太空狗 更新时间:2023-10-29 16:04:38 26 4
gpt4 key购买 nike

即使我正在运行一个新线程,我也会在主线程异常上收到此网络。知道这里出了什么问题吗?

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;



}
}

最佳答案

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

关于android - 即使在新线程上,主线程上的网络异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19193967/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com