【网络连接接口】
<span style="font-size:14px;">public class CheckVersionTask implements Runnable{
public void run() {
try {
String path = context.getResources().getString(R.string.version_addr);
Log.d("rwb:","path:"+path);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
conn.setRequestMethod("GET");
int responseCode = conn.getResponseCode();
}
catch (Exception e)
{
}</span>
【主线程】
<span style="font-size:14px;"> String localVersion = getVersionName();
CheckVersionTask cv = new CheckVersionTask(localVersion,getApplicationContext());
runOnUiThread(cv);
//new Thread(cv).start();</span>
【错误现象:】
代码执行至:int responseCode = conn.getResponseCode(); ,出现异常,报错:android.os.NetworkOnMainThreadException 。
【问题定位:】
runOnUiThread(cv); 并不是开启新线程执行网络连接,必须改为new Thread(cv).start();方式启动新线程。