本帖最后由 瘦网虫 于 2013-3-21 15:04 编辑
抛砖,给大家参考。这个功能有什么用,可以自己琢磨。
车辆定位,人员定位等等,都可以做了。准实时监控啊。
不多说,贴代码。
设备要求:1,有gps模块;2,可以移动上网(gprs或3G或其他方式)
注意:这个会增加你的移动流量,会有一定的费用产生。
下面的代码为了省事,在 StrictMode里面做了策略设置,为了在主UI线程里发起网络请求(让我懒~)。这个在4.0以后版本里面是不建议的,同学可以自行修改。
安卓代码如下:
[pre lang="java" line="1" file="GpsToYeelinkActivity.java"]
package com.shouwangchong.gps2yeelink;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class GpsToYeelinkActivity extends Activity {
Button button;
TextView textview;
LocationManager manager;
Location location;
int tagertSiteId = 1;//0:yeelink,1:lewei50
String apiKey = "";
String site = "";
String siteUrl = "";
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // 这里可以替换为detectAll() 就包括了磁盘读写和网络I/O
.penaltyLog() //打印logcat,当然也可以定位到dropbox,通过文件保存相应的log
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects() //探测SQLite数据库操作
.penaltyLog() //打印logcat
.penaltyDeath()
.build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps_to_yeelink);
textview=(TextView)findViewById(R.id.txt_out);
button=(Button)findViewById(R.id.button);
manager=(LocationManager)getSystemService(LOCATION_SERVICE);
//从GPS_PROVIDER获取最近的定位信息
location=manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateView(location);
//判断GPS是否可用
System.out.println("state="+manager.isProviderEnabled(LocationManager.GPS_PROVIDER));
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//设置每60秒,每移动十米向LocationProvider获取一次GPS的定位信息
//当LocationProvider可用,不可用或定位信息改变时,调用updateView,更新显示
setText("clicked");
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10*1000, 10, new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
//
updateView(manager.getLastKnownLocation(provider));
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
updateView(null);
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
//location为变化完的新位置,更新显示
updateView(location);
}
});
}
});
}
//更新显示内容的方法
public void updateView(Location location)
{
StringBuffer buffer=new StringBuffer();
if(location==null)
{
textview.setText("未获得服务");
return;
}
buffer.append("经度:"+location.getLongitude()+"\n");
buffer.append("纬度:"+location.getLatitude()+"\n");
buffer.append("高度:"+location.getAltitude()+"\n");
buffer.append("速度:"+location.getSpeed()+"\n");
buffer.append("方向:"+location.getBearing()+"\n");
textview.setText(buffer.toString());
sendSensorValueToYeelink(123,456,location);//replace123 to your device id,456 to your sensor id
sendSensorValueToLewei50("01","GPS",location);//replace 01 to your gateway number,GPS to your sensor name
}
private void setText(String text)
{
textview.setText(text);
}
private void sendSensorValueToYeelink(int deviceId,int sensorId,Location location)
{
System.out.println("try to send sensor value");
site = "http://api.yeelink.net/";
// site = "http://192.168.1.254/";
siteUrl = site + "v1.0/device/"+deviceId+"/sensor/"+sensorId+"/datapoints";
try {
URL url = new URL(siteUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "close");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("U-ApiKey", "123456789abcdefghijklmnopqrstuvwxyz"); //your api key in yeelink.net
conn.setRequestProperty("Accept", "*/*");
conn.connect();
OutputStream out = conn.getOutputStream();
String value = "{\"value\":{\"lat\":"+location.getLatitude()+",\"lng\":"+location.getLongitude()+",\"speed\":"+location.getSpeed()+",\"offset\":\"yes\"}}";
out.write(value.getBytes());
out.flush();
InputStream stream = conn.getInputStream();
byte[] data=new byte[102400];
int length=stream.read(data);
// String str=new String(data,0,length);
conn.disconnect();
// System.out.println(str);
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void sendSensorValueToLewei50(String deviceId,String deviceName,Location location)
{
System.out.println("try to send sensor value");
site = "http://open.lewei50.com/";
// site = "http://192.168.1.254/";
siteUrl = site + "api/V1/Gateway/UpdateSensors/"+deviceId;
try {
URL url = new URL(siteUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "close");
// conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("userkey", "123456789abcdefghijklmnopqrstuvwxyz"); //your api key in lewei50.com
// conn.setRequestProperty("Accept", "*/*");
conn.connect();
OutputStream out = conn.getOutputStream();
String value = "[{\"Name\":\""+deviceName+"\",\"value\":\""+location.getLongitude()+","+location.getLatitude()+"\"}]";
out.write(value.getBytes());
out.flush();
InputStream stream = conn.getInputStream();
byte[] data=new byte[102400];
int length=stream.read(data);
// String str=new String(data,0,length);
conn.disconnect();
// System.out.println(str);
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} [/code]
GpsToYeelinkActivity.java 结束
AndroidManifest.xml里面加上下面2个权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
[pre lang="xml" line="1" file="AndroidManifest.xml"]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.shouwangchong.gps2yeelink"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.shouwangchong.gps2yeelink.GpsToYeelinkActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>[/code].xml
AndroidManifest.xml 结束
布局很简单,1个文本框,1个按钮,用来监控数据。
[pre lang="xml" line="1" file="activiy_gps_to_yeelink.xml"]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".GpsToYeelinkActivity" >
<TextView
android:id="@+id/txt_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/txt_out"
android:layout_centerHorizontal="true"
android:layout_marginTop="29dp"
android:text="Button" />
</RelativeLayout>
[/code]
activiy_gps_to_yeelink.xml 结束
想象下,其实这个就是车辆防盗报警系统的最初始原型啊~物联网果然扩展了想象空间,支持下。 |