Android网络编程--问题汇总(01) NetworkOnMainThreadException

问题描述:

在安卓4.0版本以上运行联网程序时,常会遇到NetworkOnMainThreadException这类错误,初步猜测是因为安卓自身优化所致,为了避免主线程(UI线程)由于访问网络等待时间过长导致界面假死现象的发生做出的优化。


解决方式:

1.直接忽视掉,不推荐使用,限于在调试时临时使用

在联网activity中,嵌入下面代码即可解决。

@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		}
	}	

2.开启另一个线程,避免UI线程阻塞假死

写一个内部类实现Runnable接口

private Runnable runnable = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				ChatClient.getDataOutputStream().writeUTF(ChatClient.getSocket().getInetAddress().getHostAddress());
				ChatClient.getDataOutputStream().writeUTF("{GETALL}");
				String response = ChatClient.getDataInputStream().readUTF();
				mUsers = response.split(";");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
	        ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, mUsers); 
	        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
	        
	        userList.setAdapter(adapter); 
		}
	};

然后在onCreate中启动该线程

@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		new Thread(runnable).start();
	}	


你可能感兴趣的:(Android,Android网络编程)