package com.sgxy_ict.onetnet_demo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import com.google.gson.Gson;
import com.sgxy_ict.onetnet_demo.data.Get_Temp;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
TextView TX_Temp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TX_Temp = findViewById(R.id.tx_temp_show);
Thread_Onenet_Get thread_onenet_get = new Thread_Onenet_Get();
thread_onenet_get.start();
}
private class Thread_Onenet_Get extends Thread{
@Override
public void run() {
String url = "http://api.heclouds.com/devices/652822497/datastreams/temp";
String api_key = "XXDim0pplVQNIDFRZwmKQGQxdFs=";
Request request = new Request.Builder().
url(url).
addHeader("api-key",api_key).
get().
build();
Call call = new OkHttpClient().newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.d("Wlei","------------onFailure-----");
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String get_Json = response.body().string();
Log.d("Wlei",get_Json);
Get_Temp get_temp = new Gson().fromJson(get_Json,Get_Temp.class);
int temp = get_temp.getData().getCurrent_value();
Message msg = new Message();
msg.what = 1001;
Bundle bundle = new Bundle();
bundle.putInt("temp",temp);
msg.setData(bundle);
myhandler.sendMessage(msg);
}
});
}
}
Handler myhandler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what){
case 1001:
Log.d("Wlei",""+msg.getData().getInt("temp",20));
TX_Temp.setText(""+msg.getData().getInt("temp",20));
break;
}
}
};
}
|