• Android 网路编程


    1、获得网络信息

    首先在AndroidManifest.xml中加入权限

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    

     Code代码如下:

    public class MainActivity extends Activity {
    
    	TextView netWorkTextView;
    	ConnectivityManager cManager;
    	NetworkInfo networkInfo;
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		netWorkTextView = (TextView)findViewById(R.id.networkInfo);
    		cManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    	}
    	
    	@Override
    	protected void onStart()
    	{
    		super.onStart();
    		networkInfo = cManager.getActiveNetworkInfo();
    		netWorkTextView.setText(networkInfo.toString());	
    	}
    
    }
    

     显示入下图:代表的意思,采用WIFI连接,其它不解释。

    2 .Socket的网络通信

    1)服务端: 新建Android工程SocketServerDemo。

    public class MainActivity extends Activity {
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		startService(new Intent(this,SocketService.class));
    	}
    }
    

     SocketService类

    public class SocketService extends Service{
    
    	Thread mServiceThread;
    	Socket client;
    	@Override
    	public IBinder onBind(Intent intent) {
    		// TODO Auto-generated method stub
    		return null;
    	}
    	
    	@Override
    	public void onCreate()
    	{
    		super.onCreate();
    		mServiceThread = new Thread(new SocketServerThread());
    	}
    	
    	public class SocketServerThread extends Thread {
    
    		private static final int PORT = 8801;
    		private SocketServerThread() {
    			
    		}
    		
    		@Override
    		public void run() {
    			// TODO Auto-generated method stub
    			try {
    				ServerSocket serverSocket = new ServerSocket(PORT);
    				
    				while(true)
    				{
    					System.out.println("begin client connected");
    					client = serverSocket.accept();
    					System.out.println("client connected");
    					
    					BufferedReader reader = new BufferedReader(
    							new InputStreamReader(client.getInputStream()));
    					System.out.println("read from client:");
    					String textLine = reader.readLine();
    					if (textLine.equalsIgnoreCase("EXIT")) {
    						System.out.println("EXIT invoed, closing client");
    						break;
    					}
    					System.out.println(textLine);
    					
    					PrintWriter writer = new PrintWriter(
    							new BufferedWriter(new OutputStreamWriter(client.getOutputStream())));
    					writer.println("ECHO from server: " + textLine);
    					writer.flush();
    					writer.close();
    					reader.close();
    					
    				}
    			} catch (IOException e) {
    				// TODO: handle exception
    				System.err.println(e);
    			}
    		}
    
    	}
    
    }
    

    2)客户端:新建Android工程SocketClientDemo

    public class MainActivity extends Activity {
    
    	private static final String SERVERIP = "192.168.1.100"; //自己电脑的IP
    	private static final int SERVERPORT = 8801;
    
    	TextView mMsgRev;
    	EditText mMsgEdit;
    	Button mMsgSendBtn;
    
    	String mSendMsg;
    	String mReceivedMsg;
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    
    		mMsgRev = (TextView) findViewById(R.id.receive_msg);
    		mMsgEdit = (EditText) findViewById(R.id.edit_msg);
    		mMsgSendBtn = (Button) findViewById(R.id.send_msg);
    		
    		mMsgSendBtn.setOnClickListener(new View.OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				Socket socket = null;
    				mSendMsg = mMsgEdit.getText().toString();
    				try {
    					socket = new Socket(SERVERIP, SERVERPORT);
    					
    					PrintWriter writer = new PrintWriter(
    							new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
    					writer.println(mSendMsg);
    					writer.flush();
    					
    					BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    					mReceivedMsg = reader.readLine();
    					if (mReceivedMsg != null) {
    						mMsgRev.setText(mReceivedMsg);
    					}
    					else {
    						mMsgRev.setText("receive data error");
    					}
    					writer.close();
    					reader.close();
    					socket.close();
    					
    				} catch (UnknownHostException e) {
    					// TODO: handle exception
    					Log.i("Error", e.getMessage());
    				}
    				catch (IOException e) {
    					// TODO: handle exception
    					Log.i("Error", e.getMessage());
    				}
    			}
    		});
    
    	}
    }
    

     其中客户端跑在我的平板上,服务端跑在我的手机上。然后再服务端的文本框中输入文本,点击Send按钮,最后会收到信息。

     注意:两个程序的端口号8801都是相同的,客户端的IP地址是我的电脑IP地址,两个程序都要有权限

    <uses-permission android:name="android.permission.INTERNET" ></uses-permission>
    

      参考:基于Socket的网络通信

    作者:Work Hard Work Smart
    出处:http://www.cnblogs.com/linlf03/
    欢迎任何形式的转载,未经作者同意,请保留此段声明!

  • 相关阅读:
    Ceph纠删码编码机制
    Vmware error:无法获得 VMCI 驱动程序的版本: 句柄无效。
    Virtual Box 安装过程(卸载Vmware后)
    解决安卓SDK更新dl-ssl.google.com无法连接的方法
    《中文核心期刊要目总览(2014年版)》——计算机、自动化类
    2014中国科技核心期刊(中国科技论文统计源期刊)名录——计算机类
    计算机专业方面的期刊
    Office 中的各种小tips(更新中)
    博客园添加背景音乐
    jmeter定时器
  • 原文地址:https://www.cnblogs.com/linlf03/p/2997992.html
Copyright © 2020-2023  润新知