测试手机模拟位置

准备:

1.添加访问权限:

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

2.在手机设置中,"开发人员选项"-->"允许模拟地点"。


工作流程:

测试手机模拟位置_第1张图片

点击下载demo

3.下面是关键代码:

public class NetUtils {
	/**
	 * 获取外网地址
	 * 
	 * @return
	 */
	public static IpBean GetNetIp() {
		IpBean bean = new IpBean();
		try {
			// 访问外网ip
			String address = "http://ip.taobao.com/service/getIpInfo2.php?ip=myip";
			URL url = new URL(address);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setUseCaches(false);

			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream in = connection.getInputStream();

				// 将流转化为字符串
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(in));

				String tmpString = "";
				StringBuilder retJSON = new StringBuilder();
				while ((tmpString = reader.readLine()) != null) {
					retJSON.append(tmpString + "\n");
				}

				// {"data":{"city_id":"510100","region":"四川省","area_id":"500000","area":"西南","county":"","isp":"电信","county_id":"-1","country_id":"CN","region_id":"510000","ip":"218.88.4.195","isp_id":"100017","city":"成都市","country":"中国"},"code":0}
				JSONObject jsonObject = new JSONObject(retJSON.toString());
				String code = jsonObject.getString("code");
				if (code.equals("0")) {
					JSONObject data = jsonObject.getJSONObject("data");
					bean.setInfo(data.getString("ip") + "("
							+ data.getString("country")
							+ data.getString("area") + "区"
							+ data.getString("region") + data.getString("city")
							+ data.getString("isp") + ")");
					bean.setCity(data.getString("city"));
					bean.setIp(data.getString("ip"));
					return bean;
				} else {
					Log.e("提示", "IP接口异常,无法获取IP地址!");
				}
			} else {
				Log.e("提示", "网络连接异常,无法获取IP地址!");
			}
		} catch (Exception e) {
			Log.e("提示", "获取IP地址时出现异常,异常信息是:" + e.toString());
		}

		return null;
	}

	/**
	 * 获取城市经纬度
	 * 
	 * @param city
	 * @return
	 */
	public static LatLonBean GetNetGps(String city) {
		LatLonBean bean = new LatLonBean();
		bean.setCity(city);
		try {
			// 阿里云接口
			String address = "http://gc.ditu.aliyun.com/geocoding?a="
					+ Uri.encode(city, "utf-8");
			URL url = new URL(address);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setUseCaches(false);
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream in = connection.getInputStream();

				// 将流转化为字符串
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(in));

				String tmpString = "";
				StringBuilder retJSON = new StringBuilder();
				while ((tmpString = reader.readLine()) != null) {
					retJSON.append(tmpString + "\n");
				}

				JSONObject jsonObject = new JSONObject(retJSON.toString());
				String lon = jsonObject.getString("lon");
				String lat = jsonObject.getString("lat");
				bean.setLon(lon);
				bean.setLat(lat);
				return bean;

			}
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 改变经纬度
	 * 
	 * @param bean
	 * @return
	 */
	public static LatLonBean changeLatLon(LatLonBean bean) {
		int m1 = (int) (Math.random() * 1000000);
		int m2 = (int) (Math.random() * 1000000);

		// 30.51723
		String lat = bean.getLat();
		bean.setLat(lat.substring(0, lat.indexOf(".") + 1) + m1);
		// 104.04987
		String lon = bean.getLon();
		bean.setLon(lon.substring(0, lon.indexOf(".") + 1) + m2);

		// bean.setLat("39.9084974220");
		// bean.setLon("116.3974337341");
		return bean;
	}

	/**
	 * 模拟经纬度
	 * 
	 * @param context
	 * @param bean
	 */
	@SuppressLint("NewApi")
	public static void setLocation(Context context, LatLonBean bean) {
		LocationManager locmanag = (LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE);
		String mock = LocationManager.GPS_PROVIDER;

		locmanag.addTestProvider(mock, false, true, false, false, false, false,
				false, 0, 5);
		locmanag.setTestProviderEnabled(mock, true);

		Location loc = new Location(mock);
		loc.setTime(System.currentTimeMillis());
		loc.setLatitude(Double.parseDouble(bean.getLat()));
		loc.setLongitude(Double.parseDouble(bean.getLon()));

		// 下面这两句很关键
		loc.setAccuracy(Criteria.ACCURACY_FINE);// 精确度
		loc.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());// 实时运行时间
		locmanag.setTestProviderStatus(mock, LocationProvider.AVAILABLE, null,
				System.currentTimeMillis());
		locmanag.setTestProviderLocation(mock, loc);
	}
}

界面上绑定服务:

// 保持启动的binder对象
	LocBinder locBinder;
	// 定义服务连接对象
	ServiceConnection conn = new ServiceConnection() {
		// 当活动与服务连接断开时,回调该方法
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			Log.d("Main", "断开连接");
		}

		// 当活动与服务连接成功时,回调该方法
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			// 获取onbind()放回的对象
			locBinder = (LocBinder) service;
		}
	};

服务中开启线程,不断的刷新位置:

public class LocService extends Service {
	private LatLonBean bean = new LatLonBean();
	private LocBinder locBinder = new LocBinder();

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return locBinder;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		send();
	}

	public void send() {
		new Thread() {
			public void run() {
				while (true) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (null != bean && null != bean.getLat()) {
						NetUtils.setLocation(LocService.this, bean);
					}
				}
			};
		}.start();
	}

	class LocBinder extends Binder {
		public void setBean(LatLonBean bean) {
			LocService.this.bean = bean;
		}
	}
}

运行效果:
测试手机模拟位置_第2张图片


注意:

1.

测试手机模拟位置_第3张图片

少了对精确度和实时的设置,添加进去就可以了。

	loc.setAccuracy(Criteria.ACCURACY_FINE);// 精确度
		loc.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());// 实时运行时间

2.手机获取外网的位置,要通过访问外网,否则就是局域网的地址了。

  try {  
  
            for (Enumeration<NetworkInterface> en = NetworkInterface  
  
            .getNetworkInterfaces(); en.hasMoreElements();) {  
  
                NetworkInterface intf = en.nextElement();  
  
                for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr  
  
                .hasMoreElements();) {  
  
                    InetAddress inetAddress = ipAddr.nextElement();  
                    // ipv4地址  
                    if (!inetAddress.isLoopbackAddress()  
                            && InetAddressUtils.isIPv4Address(inetAddress  
                                    .getHostAddress())) {  
  
                        return inetAddress.getHostAddress();  
  
                    }  
  
                }  
  
            }  
  
        } catch (Exception ex) {  
  
        } 

WiFi测试时,是连接路由器的局域网ip位置。手机测试也是局域网,类似10.48.92.102。

你可能感兴趣的:(局域网)