获取连接到本机AP热点设备的IP地址

Android系统是基于Linux的,所连接的设备的一些信息保存在了  /proc/net/arp 文件中。

下面直接上我编写的程序,当前手机开启AP后,点击按钮直接获取连接到本热点的IP,然后显示在Textview控件上。

下载地址:点击打开

代码如下:

package com.example.test;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/*
 * 本例可以获取到连接到本手机AP热点设备的IP地址
 */
public class MainActivity extends Activity {
	private Button button;
	private TextView textView;
	StringBuilder resultList;
	ArrayList connectedIP;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button = (Button) findViewById(R.id.button);
		textView = (TextView) findViewById(R.id.textview);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				try {
					connectedIP = getConnectIp();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				resultList = new StringBuilder();
				for (String ip : connectedIP) {
					resultList.append(ip);
					resultList.append("\n");
					try {
						connectedIP = getConnectIp();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				System.out.print(resultList);
				String textString = resultList.toString();
				textView.setText(textString);
			}
		});
	}

	private ArrayList getConnectIp() throws Exception {
		ArrayList connectIpList = new ArrayList();
		BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"));
		String line;
		while ((line = br.readLine()) != null) {
			String[] splitted = line.split(" +");
			if (splitted != null && splitted.length >= 4) {
				String ip = splitted[0];
				connectIpList.add(ip);
			}
		}
		return connectIpList;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

你可能感兴趣的:(android开发)