项目展现:
项目分析
1.第一张图片使用了actiity的自动销毁效果
2.第二张图片使用了自定义AlertDialog
3.动态图,首先图片使用了插件使图片以圆形展示和ScrollView的使用,
如何在一个布局文件中,引入其他布局,接着首页还使用Okhttp获取网络的请求使用get和post两种方法,接着使用gson解析json数据,在点击按钮进入第二个页面时有如何更好的利用全局变量的使用。还有如何更好的使用公共地静态方法,以实现代码的复用。
下面我就来讲解如何实现一步步的效果,这里我将做一个简约版的
实现三秒后调转到主页面的效果,新建一个类,用于展示三秒跳转效果
public class DelayActivity extends AppCompatActivity {
//设置多少秒后跳转
private long delayLength = 3000;
//新建Handler对象
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delay);
//使用postDelayed()方法试下界面的三秒展现
handler.postDelayed(new Runnable() {
@Override
public void run() {
//三秒之后将实现调转,同时,销毁当前的页面
Intent intent = new Intent(DelayActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
},delayLength);
}
}
效果:
下面我们来实现三秒后,跳出自定义提示框,点击确定按钮后,跳转到主页面:
1.新建一个布局文件alert_dialog.xml,是自定义提示框的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="20dp"
android:text="欢迎您,请先设置服务器IP"
android:gravity="center"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#716c6c"/>
<EditText
android:id="@+id/dialog_et"
android:layout_width="match_parent"
android:hint="请输入设备上显示的IP地址"
android:padding="15dp"
android:layout_height="50dp" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#716c6c"/>
<Button
android:id="@+id/dialog_btn"
android:layout_width="match_parent"
android:layout_margin="15dp"
android:text="确定"
android:textSize="20sp"
android:gravity="center"
android:layout_gravity="center"
android:layout_height="50dp" />
</LinearLayout>
2.在DelayActivity中添加提示框的代码:
public class DelayActivity extends AppCompatActivity {
//设置多少秒后跳转
private long delayLength = 3000;
//新建Handler对象
private Handler handler = new Handler();
private EditText IPEt;
private Button comfirmBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delay);
//使用postDelayed()方法试下界面的三秒展现
handler.postDelayed(new Runnable() {
@Override
public void run() {
//创建AlertDialog.Buillder对象
AlertDialog.Builder builder = new AlertDialog.Builder(DelayActivity.this);
//绑定布局
/**
* @param context The Context object for your activity or application.
* @param resource The resource ID to inflate
* @param root A view group that will be the parent. Used to properly inflate the
* layout_* parameters.
*
*/
View view = View.inflate(DelayActivity.this,R.layout.alert_dialog,null);
IPEt = view.findViewById(R.id.dialog_et);
comfirmBtn = view.findViewById(R.id.dialog_btn);
builder.setView(view);
//创建Dialog对象
AlertDialog dialog = builder.create();
//展示Dialog
dialog.show();
//对按钮进行监听
comfirmBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String IP = IPEt.getText().toString();
//三秒之后将实现调转,同时,销毁当前的页面
Intent intent = new Intent(DelayActivity.this,MainActivity.class);
intent.putExtra("IP",IP);
startActivity(intent);
finish();
}
});
}
},delayLength);
}
}
效果展现:
下面我们就来实现添加空气item吧,首先创建空气布局,然后修改Mainactiity中的布局,添加空气布局
1.在创建空气布局时,要实现方形图片的圆形展示,需要首先需要添加依赖包:这里我将gson包和okhttp包一并导入,用于以后的使用:
compile 'com.makeramen:roundedimageview:2.2.1'
compile 'com.google.code.gson:gson:2.8.2'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
2.创建air.xml的布局文件:注意我在加载空气图片时,并没用用imageview,而是使用了RoundedImageView,就是我们之前添加的依赖包中的控件,这样图片就会以圆形展示了
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#716c6c"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.makeramen.roundedimageview.RoundedImageView
app:riv_oval="true"
android:id="@+id/soil_img"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="@mipmap/kongqi" />
<TextView
android:id="@+id/soil_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/soil_img"
android:layout_margin="5dp"
android:layout_toLeftOf="@+id/air_warn_img"
android:layout_toRightOf="@+id/soil_img"
android:text="空气指数"
android:textColor="#100909"
android:textSize="20sp" />
<RelativeLayout
android:id="@+id/light_relative"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/soil_tv"
android:layout_margin="5dp"
android:layout_toLeftOf="@+id/air_right_img"
android:layout_toRightOf="@+id/soil_img">
<TextView
android:id="@+id/soil_temp_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="温度:"
android:textColor="#100909"
android:textSize="20sp" />
<TextView
android:id="@+id/air_temp_values_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/soil_temp_tv"
android:gravity="center_vertical"
android:text="35"
android:textColor="#e80c0c"
android:textSize="20sp" />
<TextView
android:layout_toRightOf="@+id/air_temp_values_tv"
android:id="@+id/air_wetness_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="湿度:"
android:textColor="#100909"
android:textSize="20sp" />
<TextView
android:id="@+id/air_wetness_values_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/air_wetness_tv"
android:gravity="center_vertical"
android:text="35"
android:textColor="#e80c0c"
android:textSize="20sp" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/soil_set_relative"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_below="@+id/light_relative"
android:layout_toLeftOf="@+id/air_right_img"
android:layout_toRightOf="@+id/soil_img">
<TextView
android:id="@+id/soil_temp_set_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="温度设定值:"
android:textColor="#1fa433"
android:textSize="15sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_toRightOf="@+id/soil_temp_set_tv"
android:gravity="center_vertical"
android:text="200"
android:textColor="#605858"
android:textSize="15sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_alignBottom="@+id/soil_img"
android:layout_below="@+id/soil_set_relative"
android:layout_toLeftOf="@+id/air_right_img"
android:layout_toRightOf="@+id/soil_img">
<TextView
android:id="@+id/soil_wetness_set_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="湿度设定值:"
android:textColor="#1fa433"
android:textSize="15sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_toRightOf="@+id/soil_wetness_set_tv"
android:gravity="center_vertical"
android:text="200"
android:textColor="#605858"
android:textSize="15sp" />
</RelativeLayout>
<ImageView
android:id="@+id/air_right_img"
android:layout_width="20dp"
android:layout_height="60dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="@mipmap/right" />
<ImageView
android:id="@+id/air_warn_img"
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="@mipmap/p2" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#716c6c"/>
</LinearLayout>
3.修改Mainactivity中的布局文件,引入ari.xml文件,再布局文件中我添加了scrollview控件,用于加载的item过多时可以滑动展现。为了可以看出滑动效果,我直接多次引入air.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="android.photowallfallsdemo.com.myapplication.MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include layout="@layout/air"/>
<include layout="@layout/air"/>
<include layout="@layout/air"/>
<include layout="@layout/air"/>
<include layout="@layout/air"/>
<include layout="@layout/air"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
效果展现:
不知道什么原因,动态图传不了了,就看静态图吧
下面我们将是实现获取网络数据和解析json数据,不过因为我们没有智能农业的服务器和沙盘,就难看到效果了,就只能看到弹出联网失败了。后面控制开关也是一样的。因为你们看不到效果,下面的代码就是我自己写给自己看的了,只会写核心的代码:
在MainActivity中的onResume()方法,实现对服务器各个控件和状态的读取:
public class MainActivity extends AppCompatActivity {
public static int airHumidity;
public static int PM25;
public static int airTemperature;
public static int soilTemperature;
public static int co2;
public static int soilHumidity;
public static int light;
//将基本的URL设为一个公共静态变量,需要时直接引用就可以了
public static String basicUrl;
private ProgressDialog progressDialog;
//flag标志位用于在获取服务器状态和获取服务器数据后关闭进度条
private int flag = 0;
private String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取IP
Intent intent1 = getIntent();
String IP = intent1.getStringExtra("IP");
basicUrl = "http://" + IP + ":8890/type/jason/action/";
}
@Override
protected void onResume() {
super.onResume();
//在没有获取到服务器状态和获取服务器数据前展现进度条
showProgressDialog();
//获取服务器状态
getStatus();
//获取服务器数据
getAppValues();
}
private void getStatus() {
Okhttp.sendOkHttpRequest(basicUrl + "getContorllerStatus", new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(MainActivity.this, "失败", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
flag++;
String responseString = null;
try {
responseString = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
Log.e(TAG, "onSuccess: " + responseString);
Gson gson = new Gson();
AppStatus appStatus = gson.fromJson(responseString, AppStatus.class);
//在获到状态后赋给公共类的公共静态变量,用于以后需要时进行获取和改变
Status.WaterPump = appStatus.getWaterPump();
Status.Blower = appStatus.getBlower();
Status.Roadlamp = appStatus.getRoadlamp();
Status.Buzzer = appStatus.getBuzzer();
Status.resultStr = appStatus.getResult();
runOnUiThread(new Runnable() {
@Override
public void run() {
if (flag == 2) {
closeProgressDialog();
}
Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show();
}
});
}
});
}
//获取服务器的数据
private void getAppValues() {
Okhttp.sendOkHttpRequest(basicUrl + "getSensor?username=admin", new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(MainActivity.this, "network failture", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
flag++;
String responseString = null;
try {
responseString = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
Log.e(TAG, "onResponse: getval" + responseString);
Gson gson = new Gson();
App app = gson.fromJson(responseString, App.class);
airHumidity = app.getAirHumidity();
PM25 = app.getPM25();
airTemperature = app.getAirTemperature();
soilTemperature = app.getSoilTemperature();
co2 = app.getCo2();
soilHumidity = app.getSoilHumidity();
light = app.getLight();
runOnUiThread(new Runnable() {
@Override
public void run() {
if (flag == 2) {
closeProgressDialog();
}
//在这里对各个控件赋值
Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
}
});
}
});
}
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("loading....");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
private void closeProgressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
@Override
protected void onPause() {
super.onPause();
//归零是因为在调转到另一个页面后,如果在返回当前页面,flag标志位需要归零
flag = 0;
}
}
之前代码涉及到另外较为关键的类:用于存储服务器状态的类
public class Status {
public static int WaterPump = 0;
public static int Blower = 0;
public static int Roadlamp = 0;
public static int Buzzer = 0;
}
下面我们就要实现控制开关的功能了,首先要做的就是设置监听,跳转到开关界面,然后进行点击图片就可以实现控制开关,并改变图片的内容:
public class AirActivity extends AppCompatActivity implements View.OnClickListener{
private ImageView openFanImg;
private ImageView openLightImg;
private ImageView openPumpImg;
private ImageView openAlertImg;
private TextView airTemp;
private TextView airWet;
private void modifierBlowerStatus() {
if (Status.Blower == 0) {
openFanImg.setImageResource(R.mipmap.dakaifengshan);
DeviceControl.Result = 0;
} else if (Status.Blower == 1) {
openFanImg.setImageResource(R.mipmap.dakaifengshan2);
DeviceControl.Result = 1;
}
}
private void modifierBuzzerStatus() {
//这时候全局变量就有作用了
if (Status.Buzzer == 0) {
openAlertImg.setImageResource(R.mipmap.dakaibaojing);
//通过状态来改变标志位,用标志位来改变以后再这个页面图片的转换
//标志位依然是全局的变量,会在实现设备开关的类进行定义
DeviceControl.alertResult = 0;
} else if (Status.Buzzer == 1) {
openAlertImg.setImageResource(R.mipmap.dakaibaojing2);
DeviceControl.alertResult = 1;
}
}
private void modifierLightStatus() {
if (Status.Roadlamp == 0) {
openLightImg.setImageResource(R.mipmap.dakaiguangzhao);
DeviceControl.lightResult = 0;
} else if (Status.Roadlamp == 1) {
openLightImg.setImageResource(R.mipmap.dakaiguangzhao2);
DeviceControl.lightResult = 1;
}
}
private void modifierPumpStatus() {
if (Status.WaterPump == 0) {
openPumpImg.setImageResource(R.mipmap.dakaishui);
DeviceControl.pumpResult = 0;
} else if (Status.WaterPump == 1) {
openPumpImg.setImageResource(R.mipmap.dakaishui2);
DeviceControl.pumpResult = 1;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_air);
bangID();
//下面四个方法都是判断沙盘上各个控件的状态,如果有开的,就需要改变图片
modifierBlowerStatus();
modifierBuzzerStatus();
modifierLightStatus();
modifierPumpStatus();
airTemp.setText(MainActivity.airTemperature+"");
airWet.setText(MainActivity.airHumidity+"");
}
private void bangID() {
openFanImg = findViewById(R.id.air_fan_img);
openLightImg = findViewById(R.id.air_light_img);
openPumpImg = findViewById(R.id.air_pump_img);
openAlertImg = findViewById(R.id.air_alert_img);
airTemp = findViewById(R.id.air_temp_values);
airWet = findViewById(R.id.air_wet_values);
openFanImg.setOnClickListener(this);
openLightImg.setOnClickListener(this);
openPumpImg.setOnClickListener(this);
openAlertImg.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.air_alert_img:
if (DeviceControl.alertResult == 0) {
openAlertImg.setImageResource(R.mipmap.dakaibaojing2);
//调用开报警的方法
DeviceControl.openAlert(MainActivity.basicUrl, AirActivity.this);
Toast.makeText(this, "开警报", Toast.LENGTH_SHORT).show();
} else if (DeviceControl.alertResult == 1) {
openAlertImg.setImageResource(R.mipmap.dakaibaojing);
Intent intent = getIntent();
String basicUrl = intent.getStringExtra("basicUrl");
//调用关报警的方法
DeviceControl.closeAlert(basicUrl, AirActivity.this);
Toast.makeText(this, "关警报", Toast.LENGTH_SHORT).show();
}
break;
case R.id.air_fan_img:
if (DeviceControl.Result == 0) {
openFanImg.setImageResource(R.mipmap.dakaifengshan2);
DeviceControl.openFan(MainActivity.basicUrl, AirActivity.this);
Toast.makeText(this, "开风扇", Toast.LENGTH_SHORT).show();
} else if (DeviceControl.Result == 1) {
openFanImg.setImageResource(R.mipmap.dakaifengshan);
DeviceControl.closeFan(MainActivity.basicUrl, AirActivity.this);
Toast.makeText(this, "关风扇", Toast.LENGTH_SHORT).show();
}
break;
case R.id.air_light_img:
if(DeviceControl.lightResult==0){
openLightImg.setImageResource(R.mipmap.dakaiguangzhao2);
DeviceControl.openLight(MainActivity.basicUrl,AirActivity.this);
Toast.makeText(this, "开灯", Toast.LENGTH_SHORT).show();
}else if( DeviceControl.lightResult==1){
openLightImg.setImageResource(R.mipmap.dakaiguangzhao);
DeviceControl.closeLight(MainActivity.basicUrl,AirActivity.this);
Toast.makeText(this, "关灯", Toast.LENGTH_SHORT).show();
}
break;
case R.id.air_pump_img:
if (DeviceControl.pumpResult == 0) {
openPumpImg.setImageResource(R.mipmap.dakaishui2);
DeviceControl.openPump(MainActivity.basicUrl, AirActivity.this);
Toast.makeText(this, "开水泵", Toast.LENGTH_SHORT).show();
} else if (DeviceControl.pumpResult == 1) {
openPumpImg.setImageResource(R.mipmap.dakaishui);
DeviceControl.closePump(MainActivity.basicUrl, AirActivity.this);
Toast.makeText(this, "关水泵", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
最后就是如何实现设备开关的功能了,这里我们依然建一个公共类和公共的静态方法,可以在不同的界面里调用开关设备的功能,实现代码的复用。
public class DeviceControl {
public static int Result = 0;
public static int alertResult = 0;
public static int lightResult = 0;
public static int pumpResult = 0;
public static void openFan(String basicUrl, final Context context) {
//因为实现开关的功能,不再是只需要传递url就可以了,还需要传递json数据以告诉服务器是开还是关
//因此我们需要如何传递json数据给okhttp
//创建JSONObject[]数组,当我们需要传递多组json数据时可以用到
final JSONObject[] jsonObject = {new JSONObject()};
try {
jsonObject[0].put("Blower", 1);
} catch (JSONException e) {
e.printStackTrace();
}
/**
* param 1 :url
* param 2:jsonobject对象
* param 3:回调方法
*/
Okhttp.postJsonByOkHttp(basicUrl +"control", jsonObject[0], new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseString = response.body().string();
try {
JSONObject jsonObject1 = new JSONObject(responseString);
if (jsonObject1.getString("result").equals("ok")) {
//如果实现打开设备,将标志位和状态都设为1
Status.Blower = 1;
DeviceControl.Result = 1;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public static void closeFan(String basicUrl, Context context) {
final JSONObject[] jsonObject = {new JSONObject()};
try {
jsonObject[0].put("Blower", 0);
} catch (JSONException e) {
e.printStackTrace();
}
Okhttp.postJsonByOkHttp(basicUrl +"control", jsonObject[0], new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseString = response.body().string();
try {
JSONObject jsonObject1 = new JSONObject(responseString);
if (jsonObject1.getString("result").equals("ok")) {
//如果关闭设备,将标志位和状态都设为0
Status.Blower = 0;
DeviceControl.Result = 0;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public static void openAlert(String basicUrl, Context context) {
final JSONObject[] jsonObject = {new JSONObject()};
try {
jsonObject[0].put("Buzzer", 1);
} catch (JSONException e) {
e.printStackTrace();
}
Okhttp.postJsonByOkHttp(basicUrl +"control", jsonObject[0], new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseString = response.body().string();
try {
JSONObject jsonObject1 = new JSONObject(responseString);
if (jsonObject1.getString("result").equals("ok")) {
DeviceControl.alertResult = 1;
Status.Buzzer = 1;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public static void closeAlert(String basicUrl, Context context) {
final JSONObject[] jsonObject = {new JSONObject()};
try {
jsonObject[0].put("Buzzer", 0);
} catch (JSONException e) {
e.printStackTrace();
}
Okhttp.postJsonByOkHttp(basicUrl +"control", jsonObject[0], new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseString = response.body().string();
try {
JSONObject jsonObject1 = new JSONObject(responseString);
if (jsonObject1.getString("result").equals("ok")) {
DeviceControl.alertResult = 0;
Status.Buzzer = 0;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public static void openLight(String basicUrl, Context context) {
final JSONObject[] jsonObject = {new JSONObject()};
try {
jsonObject[0].put("Roadlamp", 1);
} catch (JSONException e) {
e.printStackTrace();
}
Okhttp.postJsonByOkHttp(basicUrl +"control", jsonObject[0], new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseString = response.body().string();
try {
JSONObject jsonObject1 = new JSONObject(responseString);
if (jsonObject1.getString("result").equals("ok")) {
DeviceControl.lightResult = 1;
Status.Roadlamp = 1;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public static void closeLight(String basicUrl, Context context) {
final JSONObject[] jsonObject = {new JSONObject()};
try {
jsonObject[0].put("Roadlamp", 0);
} catch (JSONException e) {
e.printStackTrace();
}
Okhttp.postJsonByOkHttp(basicUrl +"control", jsonObject[0], new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseString = response.body().string();
try {
JSONObject jsonObject1 = new JSONObject(responseString);
if (jsonObject1.getString("result").equals("ok")) {
DeviceControl.lightResult = 0;
Status.Roadlamp = 0;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public static void openPump(String basicUrl, Context context) {
final JSONObject[] jsonObject = {new JSONObject()};
try {
jsonObject[0].put("WaterPump", 1);
} catch (JSONException e) {
e.printStackTrace();
}
Okhttp.postJsonByOkHttp(basicUrl +"control", jsonObject[0], new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseString = response.body().string();
try {
JSONObject jsonObject1 = new JSONObject(responseString);
if (jsonObject1.getString("result").equals("ok")) {
DeviceControl.pumpResult = 1;
Status.WaterPump = 1;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public static void closePump(String basicUrl, Context context) {
final JSONObject[] jsonObject = {new JSONObject()};
try {
jsonObject[0].put("WaterPump", 0);
} catch (JSONException e) {
e.printStackTrace();
}
Okhttp.postJsonByOkHttp(basicUrl +"control", jsonObject[0], new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseString = response.body().string();
try {
JSONObject jsonObject1 = new JSONObject(responseString);
if (jsonObject1.getString("result").equals("ok")) {
DeviceControl.pumpResult = 0;
Status.WaterPump = 0;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
对应的okhttp类也需要添加post()方法
public class Okhttp {
private static OkHttpClient client = new OkHttpClient();
public static void sendOkHttpRequest(String address,okhttp3.Callback callback){
Request request = new Request.Builder().url(address).build();
client.newCall(request).enqueue(callback);
}
public static void postJsonByOkHttp(String url, JSONObject jsonObject,okhttp3.Callback callback){
//告诉网络传入的数据为json数据
MediaType mediaType = MediaType.parse("application/json;Charset=UTF-8");
RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString());
Request request = new Request.Builder().url(url).post(requestBody).build();
//回调
client.newCall(request).enqueue(callback);
}
}