Android 创建App 连接onenet实例

本文档详细介绍了如何创建一个Android项目,并连接到onenet平台以获取温湿度数据。首先,在布局文件中添加button和三个TextView用于显示数据。接着,获取onenet API并修改数据获取URL。然后在MainActivity.java中编写代码,同时更新build.gradle和AndroidManifest.xml。通过json转换工具将数据转换为Java对象,并处理时间格式。完成上述步骤后,启动应用,与onenet平台数据进行对比,实现温湿度数据的实时显示。
摘要由CSDN通过智能技术生成

##Android App 连接onenet获取温湿度实例

创建一个新project
在这里插入图片描述

先添加一个button和三个TextView(分别是温度,湿度,时间)

把温度和湿度两个TextView拉大点,用来显示数据。
TextView的位置随便放。

先去onenet官网查看自己账号的api

在这里插入图片描述
根据这里修改获取数据的URL
在这里插入图片描述

再利用Apipost软件进行连接测试获取数据(点击此处下载

在这里插入图片描述

在MainActivity.java中添加代码块

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import com.example.test1.util.Json;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
   
    static String time;//时间 
    static Double wendu;//温度
    static Double shidu;//湿度
    

//onenet连接的api
    public final String url1 = "http://api.heclouds.com/devices/629063002/datapoints?datastream_id=3303_0_5700&limit=5";
    //device/填写自己的设备ID,
    //datastream_id填写自己的nbiot相应的onenet里温度湿度的数据
    public final String url2 = "http://api.heclouds.com/devices/629063002/datapoints?datastream_id=3304_0_5700&limit=5";
    	
    private TextView txtwendu,txtshidu,shijian,txtwendu1,txtshidu1;
    private Button btn;

   @Override
    protected void onCreate(Bundle savedInstanceState) {
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtwendu = findViewById(R.id.txtwendu);
        txtshidu = findViewById(R.id.txtshidu);
        btn = findViewById(R.id.kaiqi);
        shijian = findViewById(R.id.shijian);
        txtwendu1 = findViewById(R.id.txtwendu1);
        txtshidu1 = findViewById(R.id.txtshidu1);

        //开启应用按钮点击事件
        btn.setOnClickListener(
### 回答1: 要在Android创建连接OneNet的应用程序,您需要使用OneNet提供的API和SDK。您可以使用HTTP API或MQTT协议来连接OneNet。以下是一些步骤: 1.注册OneNet账户并创建设备和数据流。 2.下载OneNet提供的Android SDK并将其添加到您的项目中。 3.使用SDK中提供的API连接OneNet并发送数据。 4.在应用程序中添加UI元素以显示从OneNet接收的数据。 5.测试应用程序并确保它可以正确连接和发送数据到OneNet。 请注意,您需要了解Android开发和网络编程的基础知识才能成功创建连接OneNet的应用程序。 ### 回答2: 要在Android创建一个连接OneNet的应用程序,您需要首先了解OneNet的API接口和Android的编程语言Java。 步骤如下: 1.注册一个OneNet账户,获取API的Key。 2.创建一个Android项目并在build.gradle文件中添加以下依赖项: ``` compile 'com.squareup.okhttp3:okhttp:3.10.0' compile 'com.google.code.gson:gson:2.8.2' ``` 这里我们使用了OKHttpClient和Gson库。 3.创建一个HttpGet请求并从OneNet获取数据,然后将数据显示在Android应用程序中。示例代码如下: ``` String apiKey = "你的APIKEY"; String deviceId = "你的设备ID"; String url = "http://api.heclouds.com/devices/" + deviceId + "/datapoints"; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .addHeader("api-key", apiKey) .build(); Response response = client.newCall(request).execute(); String responseData = response.body().string(); Gson gson = new Gson(); JsonObject jsonObject = gson.fromJson(responseData, JsonObject.class); JsonArray jsonArray = jsonObject.getAsJsonArray("datastreams"); JsonObject dataStreamObject = jsonArray.get(0).getAsJsonObject(); JsonArray dataPointsArray = dataStreamObject.getAsJsonArray("datapoints"); JSONObject latestDataObject = dataPointsArray.get(dataPointsArray.size()-1).getAsJsonObject(); String latestValue = latestDataObject.get("value").getAsString(); ``` 4.创建一个HttpPost请求并将数据发送到OneNet。示例代码如下: ``` String apiKey = "你的APIKEY"; String deviceId = "你的设备ID"; String url = "http://api.heclouds.com/devices/" + deviceId + "/datapoints"; OkHttpClient client = new OkHttpClient(); MediaType JSON = MediaType.parse("application/json; charset=utf-8"); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("temperature", "25"); jsonObject.put("humidity", "70"); } catch (JSONException e) { e.printStackTrace(); } RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString()); Request request = new Request.Builder() .url(url) .addHeader("api-key", apiKey) .post(requestBody) .build(); Response response = client.newCall(request).execute(); ``` 这是一个简单的例子,您可以根据您的需要和实际情况来修改代码。 5.在Android应用程序中操作OneNet的数据时,务必考虑到数据的安全性,避免出现数据泄露和非法访问的情况。 总之,连接OneNet涉及到HTTP请求、数据的解析和安全保护等方面的知识,您需要具备一定的编程基础和专业知识才能够实现。希望这篇答案对您有所帮助。 ### 回答3: Android创建app连接OneNet,需要按以下步骤进行: 1.注册OneNet平台账户,获取Device ID和API Key。 2.在Android Studio中新建项目,并导入MQTT库。 3.创建MQTT连接的方法,包括设置连接参数,订阅主题等。 4.使用OkHttp框架发送HTTP请求,实现与OneNet平台的交互。 5.编写App界面,包括数据显示、控制按钮等。 具体步骤如下: 1.注册OneNet平台账户,登录后进入“设备管理”页面,新建一个“设备”,获取Device ID和API Key。 2.在Android Studio中新建项目,依次点击File - New - Project,选择“Empty Activity”模板,设置项目名称和包名。点击“Finish”按钮,完成新建项目。 3.执行以下操作: (1)导入MQTT库:在app的build.gradle文件中添加以下依赖: ``` implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5' ``` (2)创建MQTT连接的方法: ``` private void connectMqtt() { try { String serverURI = "tcp://mqtt.heclouds.com:1883"; String clientId = "paho-android-example" + System.currentTimeMillis(); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(true); options.setUserName(mDeviceId); options.setPassword(mApiKey.toCharArray()); IMqttClient client = new MqttClient(serverURI, clientId); client.setCallback(new MqttCallbackExtended() { @Override public void connectComplete(boolean reconnect, String serverURI) { String topic = "/mqtt"; int qos = 1; try { IMqttToken subToken = client.subscribeWithResponse(topic, qos); } catch (MqttException e) { e.printStackTrace(); } } @Override public void connectionLost(Throwable cause) { } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { String msg = new String(message.getPayload()); // 处理收到的消息 } @Override public void deliveryComplete(IMqttDeliveryToken token) { } }); client.connect(options); } catch (MqttException e) { e.printStackTrace(); } } ``` 其中mDeviceId和mApiKey分别为OneNet平台设备的ID和API Key。 4.使用OkHttp框架发送HTTP请求,实现与OneNet平台的交互。例如,查询某个数据流的最新数值: ``` private void getLatestData() { OkHttpClient client = new OkHttpClient(); String url = "http://api.heclouds.com/devices/" + mDeviceId + "/datastreams/" + mDataStreamId; Request request = new Request.Builder() .addHeader("api-key", mApiKey) .url(url) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { String body = response.body().string(); // 解析JSON数据,获取最新数值 } }); } ``` 其中mDataStreamId为OneNet平台的数据流ID。 5.在App界面中,显示数据、控制开关等。例如,显示最新数值: ``` private void showLatestData(String value) { runOnUiThread(() -> { mValueTextView.setText("最新数值:" + value); }); } ``` 例如,控制开关: ``` private void toggleSwitch(boolean on) { OkHttpClient client = new OkHttpClient(); String url = "http://api.heclouds.com/cmds?device_id=" + mDeviceId; String body = "[{\"sn\":\"" + System.currentTimeMillis() + "\",\"datastreams\":[{\"id\":\"" + mDataStreamId + "\",\"datapoints\":[{\"value\":\"" + (on ? "1" : "0") + "\"}]}]}]"; Request request = new Request.Builder() .addHeader("api-key", mApiKey) .url(url) .post(RequestBody.create(MediaType.parse("application/json"), body)) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { String body = response.body().string(); Log.d("TAG", "toggleSwitch: " + body); // 解析JSON数据,检查控制指令是否成功发送到OneNet平台 } }); } ``` 除了以上基本步骤,根据具体需求,可添加定时上传数据、推送提醒等功能。例如,定时上传数据: ``` private void uploadData(int value) { OkHttpClient client = new OkHttpClient(); String url = "http://api.heclouds.com/devices/" + mDeviceId + "/datastreams/" + mDataStreamId + "/datapoints"; String body = "{\"datastreams\":[{\"id\":\"" + mDataStreamId + "\",\"datapoints\":[{\"value\":\"" + value + "\"}]}]}"; Request request = new Request.Builder() .addHeader("api-key", mApiKey) .url(url) .post(RequestBody.create(MediaType.parse("application/json"), body)) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { String body = response.body().string(); Log.d("TAG", "uploadData: " + body); } }); } ``` 调用该方法,可定时上传数值到OneNet平台。例如,每隔1分钟执行一次上传: ``` Observable.interval(1, TimeUnit.MINUTES) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(count -> { Random random = new Random(); int value = random.nextInt(100); uploadData(value); }); ```
评论 36
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值