Android4.0 以後不允許在主線程進行網絡連接

Android4.0 以後不允許在主線程進行網絡連接,否則會出現 android.os.NetworkOnMainThreadException。因此,必須另起一個線程進行網絡連接方面的操作。

 

 

package com.lujinhong.irmcdc.dao;  
  
import java.io.IOException;  
import java.net.Socket;  
import java.net.UnknownHostException;  
import java.util.Scanner;  
  
public class ResourceDao {  
  
    String returnLine = "hi";  
  
    public String getAllContentByName() {  
        Runnable r = new NetWorkHandler();  
        Thread thread = new Thread(r);  
        thread.start();  
  
        try {  
            Thread.sleep(15000);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
        return returnLine;  
    }  
  
    private class NetWorkHandler implements Runnable {  
  
        String line = "line";  
        Socket socket = null;  
        Scanner scanner = null;  
        @Override  
        public void run() {  
            try {  
                socket = new Socket("time-A.timefreq.bldrdoc.gov", 13);  
                scanner = new Scanner(socket.getInputStream());  
                while (scanner.hasNextLine()) {  
                    line = scanner.nextLine();  
                    returnLine += line;  
                }  
  
            } catch (UnknownHostException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            } finally {  
                scanner.close();  
                try {  
                    socket.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  
}  

 

 

 

1、由於網絡連接需要一定時間,為瞭在主界面上進行網絡信息的展現,暫時用sleep()方法簡單實現,使主線程等待網絡信息讀取完成。

 

Thread.sleep(5000);  

 

 

發佈留言