sharedPerference保存本机ip和mac地址

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;



	private SharedPreferences sharedPreferences;
	private SharedPreferences.Editor editor;
	private final static String TAG = "http";
	private final static String VALUE = "192.168.3.3";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		// 获取本机mac和ip
		String macAddress = null, ip = null;
		WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());
		if (null != info) {
			macAddress = info.getMacAddress();
			ip = int2ip(info.getIpAddress());
		}
		System.out.println("mac:" + macAddress + ",ip:" + ip);
		// 写入?
//		write2SharedPreferences(TAG, "192.168.1.1");

		// 读取
//		String str = getPreferences(MODE_PRIVATE).getString("http", "");
//		System.out.println("-------->" + str);

	}

	/**
	 * @description int转成ip地址格式
	 * @param ipInt
	 * @return
	 */
	public static String int2ip(long ipInt) {
		StringBuilder sb = new StringBuilder();
		sb.append(ipInt & 0xFF).append(".");
		sb.append((ipInt >> 8) & 0xFF).append(".");
		sb.append((ipInt >> 16) & 0xFF).append(".");
		sb.append((ipInt >> 24) & 0xFF);
		return sb.toString();
	}

	/**
	 * @description 写入sharedPreferences方法
	 * @param tag
	 * @param value
	 */
	private void write2SharedPreferences(String tag, String value) {
		try {
			sharedPreferences = getPreferences(MODE_PRIVATE);
			editor = sharedPreferences.edit();

			editor.putString(tag, value);
			editor.commit();
			System.out.println("write success!");
		} catch (Exception e) {
			System.out.println("write error!");
			e.printStackTrace();
		}
	}


你可能感兴趣的:(sharedPerference保存本机ip和mac地址)