当前位置:操作系统 > 安卓/Android >>

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);  

 

 
补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,