极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 24838|回复: 12

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

[复制链接]
发表于 2013-3-21 11:19:01 | 显示全部楼层 |阅读模式
本帖最后由 瘦网虫 于 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 结束


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

使用道具 举报

 楼主| 发表于 2013-3-21 11:25:08 | 显示全部楼层


使用效果见上图。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册

x
回复 支持 反对

使用道具 举报

发表于 2013-3-21 13:39:35 | 显示全部楼层
这个我喜欢
回复 支持 反对

使用道具 举报

发表于 2013-3-22 08:55:21 | 显示全部楼层
貌似需要一定的手机软件开发的基础
回复 支持 反对

使用道具 举报

发表于 2013-4-30 02:40:09 | 显示全部楼层
没有编译环境啊。悲催
回复 支持 反对

使用道具 举报

发表于 2013-5-2 12:45:10 | 显示全部楼层
你没有调用Yeelink平台带的纠偏功能啊,地图上的轨迹偏移了,在国内,设置纠偏可以让轨迹回到路上来
回复 支持 反对

使用道具 举报

发表于 2013-12-20 15:36:57 | 显示全部楼层
楼主能提供程序  很感谢分享,很希望你能分享开发环境和详细的搭建步骤~~~果断点赞啊!
回复 支持 反对

使用道具 举报

 楼主| 发表于 2014-2-21 10:19:18 | 显示全部楼层
Champ 发表于 2013-12-20 15:36
楼主能提供程序  很感谢分享,很希望你能分享开发环境和详细的搭建步骤~~~果断点赞啊!

安卓程序开发环境搭建,你搜一下。
回复 支持 反对

使用道具 举报

发表于 2014-12-21 21:12:53 | 显示全部楼层
谢谢分享,设备要求是针对手机的要求吗?
回复 支持 反对

使用道具 举报

发表于 2014-12-22 11:57:32 | 显示全部楼层
suoma 发表于 2014-12-21 21:12
谢谢分享,设备要求是针对手机的要求吗?

谢谢,我以为需要外扩该模块
回复 支持 反对

使用道具 举报

发表于 2014-12-25 19:11:52 | 显示全部楼层
电路图公开一下吧?
回复 支持 反对

使用道具 举报

发表于 2014-12-26 15:00:43 | 显示全部楼层
分享一下线路连接情况,就一个GPS模块和一个手机吗?手机是怎样接收GPS数据的?如果有带GPS功能的手机,还要GPS模块干嘛?
回复 支持 反对

使用道具 举报

发表于 2014-12-26 15:03:05 | 显示全部楼层
懂了,你相当于做了个app,实现数据的上传。我以为有硬件的搭建,谢谢
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 需要先绑定手机号

Archiver|联系我们|极客工坊

GMT+8, 2024-4-20 05:20 , Processed in 0.042471 second(s), 24 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表