实验04-android-ip定位

实验目的

  1. 掌握再移动设备上获取ip的方法
  2. 掌握通过连接URL,再返回字符串中解析出外网ip并获取地址和经纬度的方法
    移动设备获取ip分两种情况
  3. 通过wifi的方式(只能获取内网ip)
  4. 通过移动网络方式,

Manifest.xml文件添加权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    

布局文件略

MainActivity.java

package com.example.lu01_lab04_ip;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity{
	TextView tv,tv2,tv3,tv4,tv5;
	
@Override
protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	Button bt = (Button) findViewById(R.id.bt);
	Button bt2 = (Button) findViewById(R.id.bt2);
	Button bt3= (Button) findViewById(R.id.bt3);
	Button bt4= (Button) findViewById(R.id.bt4);
	Button bt5 = (Button) findViewById(R.id.bt5);
	
	tv = (TextView) findViewById(R.id.tv);
	tv2 = (TextView) findViewById(R.id.tv2);
	tv3 = (TextView) findViewById(R.id.tv3);
	tv4 = (TextView) findViewById(R.id.tv4);
	tv5 = (TextView) findViewById(R.id.tv5);
	bt.setOnClickListener(new OnClickListener() {

		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			tv.setText(getIpFromWifi());
			
		}
	});
	bt2.setOnClickListener(new OnClickListener() {

		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			tv2.setText(getLocalIpv6Address());
			
		}
	});
	bt3.setOnClickListener(new OnClickListener() {

		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			tv3.setText(getLocalpv4Address());
			
		}
	});
	bt4.setOnClickListener(new OnClickListener() {

		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			NetworkInfo mobilecon =null;
			NetworkInfo wificon =null;
//			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			mobilecon = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			wificon = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			if(mobilecon.isConnected()){
				tv4.setText(getLocalpv4Address());
			}else if(wificon.isConnected()){
				tv4.setText(getIpFromWifi());
			}
		}
	});
	bt5.setOnClickListener(new OnClickListener() {

		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			tv5.setText(getMacAdd());
			
		}
	});
	


}


protected String getMacAdd() {
	String macString ="";
	if(Build.VERSION.SDK_INT < Build.VERSION_CODES.BASE){
		macString = getMacDefault();
	}if (Build.VERSION.SDK_INT > Build.VERSION_CODES.BASE) {
		macString = getMac();
	}else{
		macString = getMacAddress();
	}
	
	return macString;
}

private String getMac(){//7.0以上
	try {
		ArrayList<NetworkInterface>  all = Collections.list(NetworkInterface.getNetworkInterfaces());
		for (NetworkInterface networkInterface : all) {
			if (!networkInterface.getName().equals("wlan0")) 
				continue;
				byte[] mactBytes = networkInterface.getHardwareAddress();
				if(mactBytes == null)
					return "";
				StringBuilder res1 = new StringBuilder();
				for (byte b : mactBytes) {
					res1.append(String.format("%02x", b));
				}
				if(!TextUtils.isEmpty(res1)){
					res1.deleteCharAt(res1.length()-1);
				}
				return res1.toString();
		}
	} catch (SocketException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
	
}
private String getMacDefault() {//6.0以下
	// TODO Auto-generated method stub
String mac = "";
WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = null;
wifiInfo = wifi.getConnectionInfo();
if(wifiInfo == null){
	return null;
}
 mac = wifiInfo.getMacAddress();
if(!TextUtils.isEmpty(mac)){
	mac = mac.toUpperCase(Locale.ENGLISH);
}
return mac;
}

private String getMacAddress() {//6.0-7.0
	// TODO Auto-generated method stub
String mac = null;
String  string = null;
try {
	Process pp = Runtime.getRuntime().exec("cat/sys/class/net/wlan0/address");
	InputStreamReader ir = new InputStreamReader(pp.getInputStream());
	LineNumberReader input = new LineNumberReader(ir);
	while(null != string){
		string = input.readLine();
		if(string != null){
			mac = string.trim();
		}
	}
} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
return mac;

}


protected String getLocalpv4Address() {
	String ipv4;
	try {
		ArrayList<NetworkInterface> niList = Collections.list(NetworkInterface.getNetworkInterfaces());
		for (NetworkInterface networkInterface : niList) {
			ArrayList<InetAddress> iaList = Collections.list(networkInterface.getInetAddresses());
			for (InetAddress inetAddress : iaList) {
				ipv4 = inetAddress.getHostAddress();
				if(!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)){
					return ipv4;
				}
			}
		}
	} catch (SocketException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	return null;
}

protected String getLocalIpv6Address() {
	try {
		Enumeration<NetworkInterface> enni = NetworkInterface.getNetworkInterfaces();
		while (enni.hasMoreElements()) {
			NetworkInterface networkInterface = (NetworkInterface) enni
					.nextElement();
			Enumeration<InetAddress> eniaEnumeration =networkInterface.getInetAddresses();
			while (eniaEnumeration.hasMoreElements()) {
				InetAddress inetAddress = (InetAddress) eniaEnumeration
						.nextElement();
				if (inetAddress.isLinkLocalAddress() && !inetAddress.isLoopbackAddress()) {
					return inetAddress.getHostAddress().toString();
				}
				
			}
		}
	} catch (SocketException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}

protected String getIpFromWifi() {
	WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
	if(!wifiManager.isWifiEnabled()){
		wifiManager.setWifiEnabled(true);
	}
	WifiInfo wifiInfo = wifiManager.getConnectionInfo();
	int ipAdd = wifiInfo.getIpAddress();
	String ip = intToIP(ipAdd);
	return ip;
}

private String intToIP(int ip) {
	return (ip & 0xFF)+"."+((ip >> 8) & 0xFF)+"."+((ip >> 16) & 0xFF)+"."+((ip >> 24) & 0xFF);
}	


}

实验结果
在这里插入图片描述

小结:

在InternetworkInterface之下默认拿出的是ipv6的,遍历的情况下拿ipv4的
MaC地址是辅助性的功能,身份验证的时候拿到,用那种方式需要进行判断安卓系统版本,
外网地址在WiFi下无法获得,只能通过第三方网站.移动网络下可以获得,获得的ipv4地址是真正的外网地址,然后通过json的解析方式完成基本的定位

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
多种GPS定位方式和定位研究开发心得,提供了百度定位 和 谷歌定位两种方式,基站、wifi、net定位。 google定位代码   package com.javenwong.google_gps; import android.app.Activity;import android.content.Context;import android.content.Intent;import android.location.Criteria;import android.location.Location;import android.location.LocationListener;import android.location.LocationManager;import android.os.Bundle;import android.widget.TextView;import android.widget.Toast; public class Google_gpsActivity extends Activity { TextView tv1;     /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                        Intent i = new Intent(this, ServiceTest.class);         i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);         startService(i);         tv1 = (TextView) this.findViewById(R.id.tv1);                openGPSSettings();//        String ip=GetHostIp();//        tv1.setText(ip);//        Log.i("hello", "ip is"+ip);      //  getLocation();        //tv1.setText(ip);                    tv1.setText("hello");    }        private void openGPSSettings() {        LocationManager alm = (LocationManager) this                .getSystemService(Context.LOCATION_SERVICE);        if (alm                .isProviderEnabled(android.location.LocationManager.NETWORK_PROVIDER)) {            Toast.makeText(this, "Net模块正常", Toast.LENGTH_SHORT)                    .show();            return;        }         Toast.makeText(this, "请开启GPS!", Toast.LENGTH_SHORT).show();//        Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);//        startActivityForResult(intent,0); //此为设置完成后返回到获取界面     } ......

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值