瘦网虫 发表于 2013-3-21 11:19:01

安卓发送GPS数据到物联网网站yeelink/乐联网

本帖最后由 瘦网虫 于 2013-3-21 15:04 编辑

抛砖,给大家参考。这个功能有什么用,可以自己琢磨。
车辆定位,人员定位等等,都可以做了。准实时监控啊。

不多说,贴代码。

设备要求:1,有gps模块;2,可以移动上网(gprs或3G或其他方式)
注意:这个会增加你的移动流量,会有一定的费用产生。

下面的代码为了省事,在 StrictMode里面做了策略设置,为了在主UI线程里发起网络请求(让我懒~)。这个在4.0以后版本里面是不建议的,同学可以自行修改。

安卓代码如下:

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;
                        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;
                                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();
                        }
          
    }
   
   
}



GpsToYeelinkActivity.java 结束

AndroidManifest.xml里面加上下面2个权限
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET"/>


<?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>.xml



AndroidManifest.xml 结束

布局很简单,1个文本框,1个按钮,用来监控数据。

<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>




activiy_gps_to_yeelink.xml 结束


想象下,其实这个就是车辆防盗报警系统的最初始原型啊~物联网果然扩展了想象空间,支持下。

瘦网虫 发表于 2013-3-21 11:25:08



使用效果见上图。

laoliu1982 发表于 2013-3-21 13:39:35

这个我喜欢

葱拌豆腐 发表于 2013-3-22 08:55:21

貌似需要一定的手机软件开发的基础

darkorigin 发表于 2013-4-30 02:40:09

没有编译环境啊。悲催

erjiang 发表于 2013-5-2 12:45:10

你没有调用Yeelink平台带的纠偏功能啊,地图上的轨迹偏移了,在国内,设置纠偏可以让轨迹回到路上来

Champ 发表于 2013-12-20 15:36:57

楼主能提供程序很感谢分享,很希望你能分享开发环境和详细的搭建步骤~~~果断点赞啊!

瘦网虫 发表于 2014-2-21 10:19:18

Champ 发表于 2013-12-20 15:36 static/image/common/back.gif
楼主能提供程序很感谢分享,很希望你能分享开发环境和详细的搭建步骤~~~果断点赞啊!

安卓程序开发环境搭建,你搜一下。

suoma 发表于 2014-12-21 21:12:53

谢谢分享,设备要求是针对手机的要求吗?

suoma 发表于 2014-12-22 11:57:32

suoma 发表于 2014-12-21 21:12 static/image/common/back.gif
谢谢分享,设备要求是针对手机的要求吗?

谢谢,我以为需要外扩该模块

suoma 发表于 2014-12-25 19:11:52

电路图公开一下吧?

suoma 发表于 2014-12-26 15:00:43

分享一下线路连接情况,就一个GPS模块和一个手机吗?手机是怎样接收GPS数据的?如果有带GPS功能的手机,还要GPS模块干嘛?

suoma 发表于 2014-12-26 15:03:05

懂了,你相当于做了个app,实现数据的上传。我以为有硬件的搭建,谢谢
页: [1]
查看完整版本: 安卓发送GPS数据到物联网网站yeelink/乐联网