智能农业的开发步骤

   首先需要导一下数据包。
     compile 'com.makeramen:roundedimageview:2.2.1'--让图片变成圆形的效果compile 'com.loopj.android:android-async-http:1.4.9'compile 'com.google.code.gson:gson:2.8.2'implementation 'com.squareup.okhttp3:okhttp:3.10.0'

第一步

我们先做三个页面的滑动,用fragment和viewPager来实现。先建一个三个fragment。把HomePageFragment作为首页。fragment_help布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="android.coolweather2.com.agriculturedemo.fragment.HelpFragment"><LinearLayout
        android:layout_width="match_parent"android:layout_height="50dp"><TextView
            android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:text="帮助"android:textColor="#6cd545"android:textSize="35sp" /></LinearLayout><LinearLayout
        android:layout_width="match_parent"android:layout_height="50dp"><TextView
            android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:text="操作指引"android:textSize="25sp" /></LinearLayout><LinearLayout
        android:layout_width="match_parent"android:layout_height="50dp"android:background="#5fb953"><TextView
            android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:text="1、第一条操作指引"android:textSize="25sp" /></LinearLayout><RelativeLayout
        android:layout_width="match_parent"android:layout_height="50dp"><ImageView
            android:layout_width="50dp"android:layout_height="50dp"android:layout_centerInParent="true"android:src="@mipmap/xiangxia" /></RelativeLayout><LinearLayout
        android:layout_width="match_parent"android:layout_height="50dp"android:background="#5fb953"><TextView
            android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:text="2、第二条操作指引"android:textSize="25sp" /></LinearLayout><RelativeLayout
        android:layout_width="match_parent"android:layout_height="50dp"><ImageView
            android:layout_width="50dp"android:layout_height="50dp"android:layout_centerInParent="true"android:src="@mipmap/xiangxia" /></RelativeLayout><LinearLayout
        android:layout_width="match_parent"android:layout_height="50dp"android:background="#5fb953"><TextView
            android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:text="3、第三条操作指引"android:textSize="25sp" /></LinearLayout><RelativeLayout
        android:layout_width="match_parent"android:layout_height="50dp"><ImageView
            android:layout_width="50dp"android:layout_height="50dp"android:layout_centerInParent="true"android:src="@mipmap/xiangxia" /></RelativeLayout><LinearLayout
        android:layout_width="match_parent"android:layout_height="50dp"android:background="#5fb953"><TextView
            android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:text="4、第四条操作指引"android:textSize="25sp" /></LinearLayout></LinearLayout>
fragment_set布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="android.coolweather2.com.agriculturedemo.fragment.SetFragment"><LinearLayout
        android:layout_width="match_parent"android:layout_height="50dp"><TextView
            android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:text="设置"android:textColor="#23a949"android:textSize="30sp" /></LinearLayout><View
        android:layout_width="match_parent"android:layout_height="1dp"android:background="#716c6c" /><LinearLayout
        android:layout_width="match_parent"android:layout_height="50dp"android:orientation="horizontal"><ImageView
            android:layout_width="40dp"android:layout_height="40dp"android:layout_gravity="center"android:src="@mipmap/zidongkongzhi" /><TextView
            android:layout_width="0dp"android:layout_height="match_parent"android:layout_marginLeft="15dp"android:layout_weight="1"android:gravity="center_vertical"android:text="自动控制"android:textSize="25sp" /><ImageView
            android:layout_width="20dp"android:layout_height="40dp"android:layout_gravity="right|center_vertical"android:layout_marginRight="15dp"android:src="@mipmap/gengduo" /></LinearLayout><View
        android:layout_width="match_parent"android:layout_height="1dp"android:background="#716c6c" /><LinearLayout
        android:layout_width="match_parent"android:layout_height="50dp"android:orientation="horizontal"><ImageView
            android:layout_width="40dp"android:layout_height="40dp"android:layout_gravity="center"android:src="@mipmap/qinchuhuancun" /><TextView
            android:layout_width="0dp"android:layout_height="match_parent"android:layout_marginLeft="15dp"android:layout_weight="1"android:gravity="center_vertical"android:text="清除缓存"android:textSize="25sp" /><TextView
            android:layout_width="80dp"android:layout_height="40dp"android:gravity="center"android:paddingRight="5dp"android:text="660M"android:textSize="20sp" /></LinearLayout><View
        android:layout_width="match_parent"android:layout_height="1dp"android:background="#716c6c" /><LinearLayout
        android:layout_width="match_parent"android:layout_height="50dp"android:orientation="horizontal"><ImageView
            android:layout_width="40dp"android:layout_height="40dp"android:layout_gravity="center"android:src="@mipmap/banbengengx" /><TextView
            android:layout_width="0dp"android:layout_height="match_parent"android:layout_marginLeft="15dp"android:layout_weight="1"android:gravity="center_vertical"android:text="版本更新"android:textSize="25sp" /><TextView
            android:layout_width="80dp"android:layout_height="40dp"android:gravity="center"android:paddingRight="5dp"android:text="V2.0"android:textSize="20sp" /></LinearLayout><View
        android:layout_width="match_parent"android:layout_height="1dp"android:background="#716c6c" /><LinearLayout
        android:layout_width="match_parent"android:layout_height="50dp"android:orientation="horizontal"><ImageView
            android:layout_width="40dp"android:layout_height="40dp"android:layout_gravity="center"android:src="@mipmap/guanyuwomen" /><TextView
            android:layout_width="0dp"android:layout_height="match_parent"android:layout_marginLeft="15dp"android:layout_weight="1"android:gravity="center_vertical"android:text="关于我们"android:textSize="25sp" /><ImageView
            android:layout_width="20dp"android:layout_height="40dp"android:layout_gravity="right|center_vertical"android:layout_marginRight="15dp"android:src="@mipmap/gengduo" /></LinearLayout><View
        android:layout_width="match_parent"android:layout_height="1dp"android:background="#716c6c" /><LinearLayout
        android:layout_width="match_parent"android:layout_height="50dp"android:layout_marginTop="15dp"android:orientation="horizontal"><ImageView
            android:layout_width="40dp"android:layout_height="40dp"android:layout_gravity="center"android:src="@mipmap/my_exit" /><TextView
            android:layout_width="0dp"android:layout_height="match_parent"android:layout_marginLeft="15dp"android:layout_weight="1"android:gravity="center_vertical"android:text="退出登录"android:textSize="25sp" /></LinearLayout></LinearLayout>
fragment_home_page布局:在这里面需要用到ScrollView来进行页面的滚动。我们可以把homepage里面的东西单独拿出来,放在各自的XML文件里面。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="android.coolweather2.com.agriculturedemo.fragment.HomePageFragment"><TextView
        android:id="@+id/home_page_top_lin"android:layout_width="match_parent"android:layout_height="50dp"android:gravity="center_horizontal"android:text="智能农业"android:textColor="#24bd3b"android:textSize="30dp" /><ScrollView
        android:layout_width="match_parent"android:layout_height="match_parent"android:layout_above="@+id/main_bottom_lin"android:layout_alignParentLeft="true"android:layout_below="@+id/home_page_top_lin"android:overScrollMode="never"android:scrollbars="none"><LinearLayout
            android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><android.support.v4.view.ViewPager                android:id="@+id/home_page_vp"android:layout_width="match_parent"android:layout_height="150dp"></android.support.v4.view.ViewPager><include layout="@layout/co2" /><include layout="@layout/light" /><include layout="@layout/soil" /><include layout="@layout/air" /></LinearLayout></ScrollView></RelativeLayout>

几个布局都差不多,我这边就列出一个光照强度的布局。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><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
            android:id="@+id/light_img"android:layout_width="120dp"android:layout_height="120dp"android:src="@mipmap/guangzhao"app:riv_oval="true" /><TextView
            android:id="@+id/light_intension_tv"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignTop="@+id/light_img"android:layout_margin="5dp"android:layout_toLeftOf="@+id/light_warn_img"android:layout_toRightOf="@+id/light_img"android:text="光照强度"android:textColor="#000000"android:textSize="20sp" /><RelativeLayout
            android:id="@+id/light_relative"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_below="@+id/light_intension_tv"android:layout_margin="5dp"android:layout_toLeftOf="@+id/light_right_img"android:layout_toRightOf="@+id/light_img"><TextView
                android:id="@+id/light_light_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/light_values_tv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="15dp"android:layout_toRightOf="@+id/light_light_tv"android:gravity="center_vertical"android:text="200"android:textColor="#e80c0c"android:textSize="20sp" /></RelativeLayout><RelativeLayout
            android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignBottom="@+id/light_img"android:layout_below="@+id/light_relative"android:layout_margin="5dp"android:layout_toLeftOf="@+id/light_right_img"android:layout_toRightOf="@+id/light_img"><TextView
                android:id="@+id/light_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/light_set_tv"android:gravity="center_vertical"android:text="200"android:textColor="#605858"android:textSize="15sp" /></RelativeLayout><ImageView
            android:id="@+id/light_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/light_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>

接着在MainActivity里面填充fragment数据,然后用viewpager来滑动。最后来绑定适配器。

private static final String TAG = "MainActivity";List<Fragment> fragmentList = new ArrayList<>();private ViewPager agricultureVp;private LinearLayout homeLin;private LinearLayout setLin;private LinearLayout helpLin;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);bangID();HomePageFragment homePageFragment = new HomePageFragment();SetFragment setFragment = new SetFragment();HelpFragment helpFragment = new HelpFragment();fragmentList.add(homePageFragment);fragmentList.add(setFragment);fragmentList.add(helpFragment);MyPageAdapter adapter = new MyPageAdapter(getSupportFragmentManager(), fragmentList);agricultureVp.setAdapter(adapter);}private void bangID() {agricultureVp = findViewById(R.id.main_vp);homeLin = findViewById(R.id.home_page_lin);setLin = findViewById(R.id.set_lin);helpLin = findViewById(R.id.help_lin);homeLin.setOnClickListener(this);setLin.setOnClickListener(this);helpLin.setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.home_page_lin:agricultureVp.setCurrentItem(0);break;case R.id.set_lin:agricultureVp.setCurrentItem(1);break;case R.id.help_lin:agricultureVp.setCurrentItem(2);break;default:}}
}
  MyPageAdapter适配器布局:
 //创建fragmentList集合private List<Fragment> fragmentList;//构造方法实现传值public MyPageAdapter(FragmentManager fm, List<Fragment> fragmentList) {super(fm);this.fragmentList = fragmentList;}//返回fragmentList对象@Overridepublic Fragment getItem(int position) {return fragmentList.get(position);}//返回fragmentList对象个数@Overridepublic int getCount() {return fragmentList.size();}

布局做好了,我们需要做一个自定义的对话框,需要用到alertdialog的知识。首先我们还是要先写一个一个alertdialog的布局。

    <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
            android:id="@+id/light_img"android:layout_width="120dp"android:layout_height="120dp"android:src="@mipmap/guangzhao"app:riv_oval="true" /><TextView
            android:id="@+id/light_intension_tv"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignTop="@+id/light_img"android:layout_margin="5dp"android:layout_toLeftOf="@+id/light_warn_img"android:layout_toRightOf="@+id/light_img"android:text="光照强度"android:textColor="#000000"android:textSize="20sp" /><RelativeLayout
            android:id="@+id/light_relative"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_below="@+id/light_intension_tv"android:layout_margin="5dp"android:layout_toLeftOf="@+id/light_right_img"android:layout_toRightOf="@+id/light_img"><TextView
                android:id="@+id/light_light_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/light_values_tv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="15dp"android:layout_toRightOf="@+id/light_light_tv"android:gravity="center_vertical"android:text="200"android:textColor="#e80c0c"android:textSize="20sp" /></RelativeLayout><RelativeLayout
            android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignBottom="@+id/light_img"android:layout_below="@+id/light_relative"android:layout_margin="5dp"android:layout_toLeftOf="@+id/light_right_img"android:layout_toRightOf="@+id/light_img"><TextView
                android:id="@+id/light_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/light_set_tv"android:gravity="center_vertical"android:text="200"android:textColor="#605858"android:textSize="15sp" /></RelativeLayout><ImageView
            android:id="@+id/light_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/light_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" />

然后在ImgActivity里面定义一个按钮,IP,一个输入框,需要在里面使用handler来启动子线程。

  private final long SPLASH_LENGTH = 2000;Handler handler = new Handler();private Button button;private String IP;private EditText editText;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_img);handler.postDelayed(new Runnable() {  //使用handler的postDelayed实现延时跳转public void run() {AlertDialog.Builder builder = new AlertDialog.Builder(ImgActivity.this);View view = View.inflate(ImgActivity.this,R.layout.alert_dialog,null);builder.setView(view);builder.setCancelable(true);editText = view.findViewById(R.id.dialog_et);button = view.findViewById(R.id.dialog_btn);AlertDialog dialog = builder.create();dialog.show();button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent(ImgActivity.this, MainActivity.class);IP = editText.getText().toString();intent.putExtra("IP",IP);startActivity(intent);finish();}});}}, SPLASH_LENGTH);//2秒后跳转至应用主界面MainActivity}
 首页上面的图片,也要实现手动滑动,同样的都是用fragment和viewpager的知识来实现。
View view =inflater.inflate(R.layout.fragment_home_page, container, false);bangID(view);ImgAFragment imgAFragment = new ImgAFragment();ImgBFragment imgBFragment = new ImgBFragment();fragmentImgList.add(imgAFragment);fragmentImgList.add(imgBFragment);MyImgPageAdapter adapter1 = new MyImgPageAdapter(getChildFragmentManager(), fragmentImgList);ImgVp.setAdapter(adapter1);

最后也是用myimgadapter来绑定。

public class MyImgPageAdapter extends FragmentPagerAdapter {//创建fragmentList集合private List<Fragment> fragmentImgList;//构造方法实现传值public MyImgPageAdapter(FragmentManager fm, List<Fragment> fragmentImgList) {super(fm);this.fragmentImgList = fragmentImgList;}//返回fragmentList对象@Overridepublic Fragment getItem(int position) {return fragmentImgList.get(position);}//返回fragmentList对象个数@Overridepublic int getCount() {return fragmentImgList.size();}
}
   公共类状态的标志位:
public class Status {public static int WaterPump = 0;public static int Blower = 0;public static int Roadlamp = 0;public static int Buzzer = 0;public static String resultStr;public  static String TAG = "Status";}
获取传感器的类:
public class App {private int airHumidity;private int PM25;private int airTemperature;private int soilTemperature;private int co2;private int soilHumidity;private int light;public int getAirHumidity() {return airHumidity;}public void setAirHumidity(int airHumidity) {this.airHumidity = airHumidity;}public int getPM25() {return PM25;}public void setPM25(int PM25) {this.PM25 = PM25;}public int getAirTemperature() {return airTemperature;}public void setAirTemperature(int airTemperature) {this.airTemperature = airTemperature;}public int getSoilTemperature() {return soilTemperature;}public void setSoilTemperature(int soilTemperature) {this.soilTemperature = soilTemperature;}public int getCo2() {return co2;}public void setCo2(int co2) {this.co2 = co2;}public int getSoilHumidity() {return soilHumidity;}public void setSoilHumidity(int soilHumidity) {this.soilHumidity = soilHumidity;}public int getLight() {return light;}public void setLight(int light) {this.light = light;}
}

控制的类:

public class AppStatus {private int WaterPump;private int Blower;private int Roadlamp;private int Buzzer;private String result;public int getWaterPump() {return WaterPump;}public void setWaterPump(int waterPump) {WaterPump = waterPump;}public int getBlower() {return Blower;}public void setBlower(int blower) {Blower = blower;}public int getRoadlamp() {return Roadlamp;}public void setRoadlamp(int roadlamp) {Roadlamp = roadlamp;}public int getBuzzer() {return Buzzer;}public void setBuzzer(int buzzer) {Buzzer = buzzer;}public String getResult() {return result;}public void setResult(String result) {this.result = result;}
}

接下来我们就是需要打开农业接口的文件,我们通过获取传感器来获取数据。所以这个时候我们可以定义一个公共的类,和一个公共的方法,在这里我们可以不用AsyncHttpClient,可以用OkHttpClient,这样的话速度更快一点。记得要postJsonByOkHttp来封装东西。

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

我们在devicecontrol的类里面写八个公共的方法,来控制开关的状态。

package android.coolweather2.com.agriculturedemo.util;import android.content.Context;import com.loopj.android.http.TextHttpResponseHandler;import org.json.JSONException;
import org.json.JSONObject;import java.io.IOException;
import java.io.UnsupportedEncodingException;import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.entity.ByteArrayEntity;
import cz.msebera.android.httpclient.message.BasicHeader;
import cz.msebera.android.httpclient.protocol.HTTP;
import okhttp3.Call;
import okhttp3.Response;/*** Created by Administrator on 2018/4/11.*/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) {final JSONObject[] jsonObject = {new JSONObject()};try {jsonObject[0].put("Blower", 1);} catch (JSONException e) {e.printStackTrace();}Okhttp.postJsonByOkHttp(basicUrl +"control", jsonObject[0], new okhttp3.Callback() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic 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")) {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() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic 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")) {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() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic 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();}}});}}

接着在homepagefragment里面写一个获取数据和控制的方法接下来。可以在添加一个progressdialog的进度条,感受一下OKHTTPclient的速度。

package android.coolweather2.com.agriculturedemo.fragment;import android.app.ProgressDialog;
import android.content.Intent;
import android.coolweather2.com.agriculturedemo.AirActivity;
import android.coolweather2.com.agriculturedemo.CO2Activity;
import android.coolweather2.com.agriculturedemo.LightActivity;
import android.coolweather2.com.agriculturedemo.R;
import android.coolweather2.com.agriculturedemo.SoilActivity;
import android.coolweather2.com.agriculturedemo.gson.App;
import android.coolweather2.com.agriculturedemo.gson.AppStatus;
import android.coolweather2.com.agriculturedemo.util.MyImgPageAdapter;
import android.coolweather2.com.agriculturedemo.util.Okhttp;
import android.coolweather2.com.agriculturedemo.util.Status;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;import com.google.gson.Gson;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;/*** A simple {@link Fragment} subclass.*/
public class HomePageFragment extends Fragment implements View.OnClickListener {private static final String TAG = "HomePageFragment";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;List<Fragment> fragmentImgList = new ArrayList<>();private ImageView co2Img;private ImageView lightImg;private ImageView soilImg;private ImageView airImg;private ViewPager ImgVp;private TextView co2Tv;private TextView lightTv;private TextView soilTempTv;private TextView soilWetnessTv;private TextView airTempTv;private TextView airWetnessTv;private String basicUrl;private ProgressDialog progressDialog;private int flag = 0;public HomePageFragment() {}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// Inflate the layout for this fragmentView view = inflater.inflate(R.layout.fragment_home_page, container, false);bangID(view);ImgAFragment imgAFragment = new ImgAFragment();ImgBFragment imgBFragment = new ImgBFragment();fragmentImgList.add(imgAFragment);fragmentImgList.add(imgBFragment);MyImgPageAdapter adapter1 = new MyImgPageAdapter(getChildFragmentManager(), fragmentImgList);ImgVp.setAdapter(adapter1);Intent intent = getActivity().getIntent();String relativeUrl = intent.getStringExtra("IP");basicUrl = "http://" + relativeUrl + ":8890/type/jason/action/";showProgressDialog();getStatus();getAppValues();return view;}private void getStatus() {Intent intent1 = getActivity().getIntent();String relativeUrl = intent1.getStringExtra("IP");String basicUrl1 = "http://" + relativeUrl + ":8890/type/jason/action/" + "getContorllerStatus";Okhttp.sendOkHttpRequest(basicUrl1, new Callback() {@Overridepublic void onFailure(Call call, IOException e) {getActivity().runOnUiThread(new Runnable() {@Overridepublic void run() {closeProgressDialog();Toast.makeText(getActivity(), "失败", Toast.LENGTH_SHORT).show();}});}@Overridepublic 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();getActivity().runOnUiThread(new Runnable() {@Overridepublic void run() {if (flag == 2) {closeProgressDialog();}closeProgressDialog();Toast.makeText(getActivity(), "连接成功", Toast.LENGTH_SHORT).show();}});}});
//        AsyncHttpClient client = new AsyncHttpClient();
//        client.get(basicUrl1, new TextHttpResponseHandler() {//            @Override
//            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {//            }
//
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, String responseString) {//                flag++;
//                if(flag==2){//                    closeProgressDialog();
//                }
//
//                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();
//
//                //Log.e(TAG, "onSuccess:222222 "+result+WaterPump );//
//
//            }
//        });}private void getAppValues() {Intent intent = getActivity().getIntent();String relativeUrl = intent.getStringExtra("IP");String basicUrl2 = "http://" + relativeUrl + ":8890/type/jason/action/getSensor?username=admin";Log.e(TAG, "getAppValues: " + basicUrl2);Okhttp.sendOkHttpRequest(basicUrl2, new Callback() {@Overridepublic void onFailure(Call call, IOException e) {getActivity().runOnUiThread(new Runnable() {@Overridepublic void run() {closeProgressDialog();Toast.makeText(getActivity(), "network failture", Toast.LENGTH_SHORT).show();}});}@Overridepublic 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();getActivity().runOnUiThread(new Runnable() {@Overridepublic void run() {if (flag == 2) {closeProgressDialog();}co2Tv.setText(co2 + "");lightTv.setText(light + "");soilTempTv.setText(soilTemperature + "");soilWetnessTv.setText(soilHumidity + "");airTempTv.setText(airTemperature + "");airWetnessTv.setText(airHumidity + "");//Log.e(TAG, "onSuccess: "+responseString );Toast.makeText(getActivity(), "Success", Toast.LENGTH_SHORT).show();}});}});//        RequestParams params = new RequestParams();
//        params.put("username","admin");
//        HttpUtil.get(basicUrl+"getSensor", params, new TextHttpResponseHandler() {//            @Override
//            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {//                closeProgressDialog();
//                Toast.makeText(getActivity(), "network failture", Toast.LENGTH_SHORT).show();
//
//            }
//
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, String responseString) {//
//                flag++;
//                if(flag==2){//                    closeProgressDialog();
//                }
//
//                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();
//
//                co2Tv.setText(co2+"");
//                lightTv.setText(light+"");
//                soilTempTv.setText(soilTemperature+"");
//                soilWetnessTv.setText(soilHumidity+"");
//                airTempTv.setText(airTemperature+"");
//                airWetnessTv.setText(airHumidity+"");
//
//                Log.e(TAG, "onSuccess: "+responseString );
//                Toast.makeText(getActivity(), "success", Toast.LENGTH_SHORT).show();
//
//               // closeProgressDialog();
//
//
//            }
//        });}private void bangID(View view) {co2Img = view.findViewById(R.id.co2_right_img);ImgVp = view.findViewById(R.id.home_page_vp);lightImg = view.findViewById(R.id.light_right_img);soilImg = view.findViewById(R.id.soil_right_img);airImg = view.findViewById(R.id.air_right_img);co2Tv = view.findViewById(R.id.co2_values_tv);lightTv = view.findViewById(R.id.light_values_tv);soilTempTv = view.findViewById(R.id.soil_temp_values_tv);soilWetnessTv = view.findViewById(R.id.soil_wetness_values_tv);airTempTv = view.findViewById(R.id.air_temp_values_tv);airWetnessTv = view.findViewById(R.id.air_wetness_values_tv);co2Img.setOnClickListener(this);lightImg.setOnClickListener(this);soilImg.setOnClickListener(this);airImg.setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.co2_right_img:Intent intent = new Intent(getActivity(), CO2Activity.class);intent.putExtra("basicUrl", basicUrl);startActivity(intent);break;case R.id.light_right_img:Intent intent1 = new Intent(getActivity(), LightActivity.class);intent1.putExtra("basicUrl", basicUrl);startActivity(intent1);break;case R.id.soil_right_img:Intent intent2 = new Intent(getActivity(), SoilActivity.class);intent2.putExtra("basicUrl", basicUrl);startActivity(intent2);break;case R.id.air_right_img:Intent intent3 = new Intent(getActivity(), AirActivity.class);intent3.putExtra("basicUrl", basicUrl);startActivity(intent3);break;default:}}private void showProgressDialog() {if (progressDialog == null) {progressDialog = new ProgressDialog(getActivity());progressDialog.setMessage("loading....");progressDialog.setCanceledOnTouchOutside(false);}progressDialog.show();}private void closeProgressDialog() {if (progressDialog != null) {progressDialog.dismiss();}}@Overridepublic void onResume() {super.onResume();closeProgressDialog();}
}

然后在四个页面来判断打开开关的状态,和实现改变图片的功能。这时候我们 可以用到devicecontrol了。用status里面e 标志位来判断它们的状态

     SoilActivity:

public class SoilActivity extends AppCompatActivity implements View.OnClickListener{private static ImageView openPumpImg;private static ImageView openLightImg;private static ImageView openAlertImg;private TextView soilTemp;private TextView soilWet;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;}}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 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;}}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_soil);bangID();modifierPumpStatus();modifierLightStatus();modifierBuzzerStatus();soilWet.setText(HomePageFragment.soilHumidity+"");soilTemp.setText(HomePageFragment.soilTemperature+"");}private void bangID() {openPumpImg = findViewById(R.id.soil_WaterPump_img);openLightImg = findViewById(R.id.soil_light_img);openAlertImg = findViewById(R.id.soil_alert_img);soilTemp = findViewById(R.id.soil_temp_values);soilWet = findViewById(R.id.soil_wet_values);openPumpImg.setOnClickListener(this);openLightImg.setOnClickListener(this);openAlertImg.setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()){case R.id.soil_WaterPump_img:if (DeviceControl.pumpResult == 0) {openPumpImg.setImageResource(R.mipmap.dakaishui2);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.openPump(basicUrl, SoilActivity.this);} else if (DeviceControl.pumpResult == 1) {openPumpImg.setImageResource(R.mipmap.dakaishui);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.closePump(basicUrl, SoilActivity.this);}break;case R.id.soil_light_img:if(DeviceControl.lightResult==0){openLightImg.setImageResource(R.mipmap.dakaiguangzhao2);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.openLight(basicUrl,SoilActivity.this);}else if( DeviceControl.lightResult==1){openLightImg.setImageResource(R.mipmap.dakaiguangzhao);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.closeLight(basicUrl,SoilActivity.this);}break;case R.id.soil_alert_img:if (DeviceControl.alertResult == 0) {openAlertImg.setImageResource(R.mipmap.dakaibaojing2);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.openAlert(basicUrl, SoilActivity.this);} else if (DeviceControl.alertResult == 1) {openAlertImg.setImageResource(R.mipmap.dakaibaojing);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.closeAlert(basicUrl, SoilActivity.this);}break;}}}

光照的代码、co2浓度代码、空气代码基本上都差不多。

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;}}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_air);bangID();modifierBlowerStatus();modifierBuzzerStatus();modifierLightStatus();modifierPumpStatus();airTemp.setText(HomePageFragment.airTemperature+"");airWet.setText(HomePageFragment.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);}@Overridepublic void onClick(View v) {switch (v.getId()){case R.id.air_alert_img:if (DeviceControl.alertResult == 0) {openAlertImg.setImageResource(R.mipmap.dakaibaojing2);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.openAlert(basicUrl, AirActivity.this);} else if (DeviceControl.alertResult == 1) {openAlertImg.setImageResource(R.mipmap.dakaibaojing);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.closeAlert(basicUrl, AirActivity.this);}break;case R.id.air_fan_img:if (DeviceControl.Result == 0) {openFanImg.setImageResource(R.mipmap.dakaifengshan2);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.openFan(basicUrl, AirActivity.this);} else if (DeviceControl.Result == 1) {openFanImg.setImageResource(R.mipmap.dakaifengshan);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.closeFan(basicUrl, AirActivity.this);}break;case R.id.air_light_img:if(DeviceControl.lightResult==0){openLightImg.setImageResource(R.mipmap.dakaiguangzhao2);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.openLight(basicUrl,AirActivity.this);}else if( DeviceControl.lightResult==1){openLightImg.setImageResource(R.mipmap.dakaiguangzhao);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.closeLight(basicUrl,AirActivity.this);}break;case R.id.air_pump_img:if (DeviceControl.pumpResult == 0) {openPumpImg.setImageResource(R.mipmap.dakaishui2);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.openPump(basicUrl, AirActivity.this);} else if (DeviceControl.pumpResult == 1) {openPumpImg.setImageResource(R.mipmap.dakaishui);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.closePump(basicUrl, AirActivity.this);}break;}}
}
public class CO2Activity extends AppCompatActivity implements View.OnClickListener {private static final String TAG = "CO2Activity";private static ImageView openFanImg;private static ImageView openAlertImg;private TextView co2ValuseTv;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;}}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_co2);bangID();modifierBlowerStatus();modifierBuzzerStatus();App app = new App();co2ValuseTv.setText(HomePageFragment.co2+"");}private void bangID() {openFanImg = findViewById(R.id.co2_open_fan_img);openAlertImg = findViewById(R.id.co2_openalert_img);co2ValuseTv = findViewById(R.id.co_values_tv);openFanImg.setOnClickListener(this);openAlertImg.setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.co2_open_fan_img:if (DeviceControl.Result == 0) {openFanImg.setImageResource(R.mipmap.dakaifengshan2);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.openFan(basicUrl, CO2Activity.this);} else if (DeviceControl.Result == 1) {openFanImg.setImageResource(R.mipmap.dakaifengshan);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.closeFan(basicUrl, CO2Activity.this);}break;case R.id.co2_openalert_img:if (DeviceControl.alertResult == 0) {openAlertImg.setImageResource(R.mipmap.dakaibaojing2);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.openAlert(basicUrl, CO2Activity.this);} else if (DeviceControl.alertResult == 1) {openAlertImg.setImageResource(R.mipmap.dakaibaojing);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.closeAlert(basicUrl, CO2Activity.this);}break;}}}
public class LightActivity extends AppCompatActivity implements View.OnClickListener{private static ImageView opneLightImg;private static ImageView opneAlertImg;private TextView lightTv;private  void modifierLightStatus() {if (Status.Roadlamp == 0) {opneLightImg.setImageResource(R.mipmap.dakaiguangzhao);DeviceControl.lightResult = 0;} else if (Status.Roadlamp == 1) {opneLightImg.setImageResource(R.mipmap.dakaiguangzhao2);DeviceControl.lightResult = 1;}}private  void modifierBuzzerStatus() {if (Status.Buzzer == 0) {opneAlertImg.setImageResource(R.mipmap.dakaibaojing);DeviceControl.alertResult = 0;} else if (Status.Buzzer == 1) {opneAlertImg.setImageResource(R.mipmap.dakaibaojing2);DeviceControl.alertResult = 1;}}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_light);bangID();modifierLightStatus();modifierBuzzerStatus();App app = new App();lightTv.setText(HomePageFragment.light+"");}private void bangID() {opneLightImg = findViewById(R.id.light_openLight_img);opneAlertImg = findViewById(R.id.light_alert_img);lightTv = findViewById(R.id.light_values_tv2);opneLightImg.setOnClickListener(this);opneAlertImg.setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()){case R.id.light_openLight_img:if(DeviceControl.lightResult==0){opneLightImg.setImageResource(R.mipmap.dakaiguangzhao2);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.openLight(basicUrl,LightActivity.this);}else if( DeviceControl.lightResult==1){opneLightImg.setImageResource(R.mipmap.dakaiguangzhao);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.closeLight(basicUrl,LightActivity.this);}break;case R.id.light_alert_img:if (DeviceControl.alertResult == 0) {opneAlertImg.setImageResource(R.mipmap.dakaibaojing2);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.openAlert(basicUrl, LightActivity.this);} else if (DeviceControl.alertResult == 1) {opneAlertImg.setImageResource(R.mipmap.dakaibaojing);Intent intent = getIntent();String basicUrl = intent.getStringExtra("basicUrl");DeviceControl.closeAlert(basicUrl,LightActivity.this);}break;}}}

最后智能农业大体上就是这样的步骤。因为我也是初学者,不懂的你们可以去查看相关的知识。

安卓开发项目——智能农业相关推荐

  1. Android开发项目——智能农业(知识点整理回顾)

    前言:智能农业这个项目可以说是大多都是我们自己完成的.是对于前一个多月Android学习的一个检验,同时也是对我们成绩的一个凭据.意义非常重大. 一.对于布局方面 下面我放两张例图,是我认为在布局上对 ...

  2. 实战项目——智能农业沙盘

    智能农业的实现 前言:前面我们学习了一系列的Android基础知识点,而一些重要知识点将在我们的实战项目中灵活运用到. 关于智能农业 这是一款基于Android开发的农业管理系统,通过移动端(Andr ...

  3. Android项目——智能农业

    总结一下这一周关于智能农业APP项目的学习. ####一.布局 APP最重要的就是与用户的交互界面,布局很重要.在智能农业APP这个项目中,布局十分简单,用户不需要花费多少时间便能熟练使用. #### ...

  4. 安卓开发项目(微信简单界面)

    安卓项目----微信简单界面(1) 一.开发所需软件:Android studio 二.功能说明 在安卓studio中建立一个新的项目后,我们可以看到在项目中存在两个不一样的未经修改的原文件 acti ...

  5. Android 9,安卓开发项目实战

    以机器学习为核心,打造更为智能的手机 Android 9 赋予手机强大的学习能力:系统能够根据用户在使用过程中展露的习惯与偏好,进行自我学习与适应 -- 从强劲续航到人性化应用推荐,Android 9 ...

  6. 安卓开发: Jetpack compose + kotlin 实现 俄罗斯方块游戏

    文章目录 前言 俄罗斯方块开发文档 1.摘要 2.开发工具选取 2.1.Compose 的自身优点 2.2.数据驱动界面 3.设计需求 3.1.功能需求 3.1.1.基本游戏功能 3.1.2.拓展功能 ...

  7. 学习笔记 | Android Studio安卓开发入门经验总结 干货

    前言 最近完成了移动编程课程的学习,加上其它安卓开发项目的经历,感觉收获颇为丰富.故在此总结整理安卓开发中比较常见的一些问题,技巧和指南. 0.目录 文章目录 前言 0.目录 1.开发环境 2. 项目 ...

  8. 安卓开发 智能农业 详细

    大局观: 智能农业是 远程监控一定区域内的 空气浓度,co2浓度,预警,等 效果图 首先 我们首先的问题就是静态布局: 难点 :Fragment碎片布局 和 图片设置 强调内容 Fragment 碎片 ...

  9. 基于5G技术的智能导航机器人及AR巡逻应用开发项目实施方案(上)

    目录 1 项目总体概述 1.1 项目背景 1.2 建设内容 1.3 建设目标 2 项目需求理解 2.1 业务需求 2.2 功能需求 3 项目技术方案 3.1 建设方案 3.1.1 设计思路 3.1.2 ...

最新文章

  1. Libevent实现TCP服务循环监听
  2. 【Anychat音视频开发】apache防盗链之mod_perl
  3. vscode怎么执行python_VScode | 执行python
  4. react 子组件ref_React中Ref 的使用方法详解
  5. CSS中的未定义行为,浏览器的差异(一)
  6. 史上最硬核的数学老师!搞发明、造大炮,让战斗民族直叫爸爸,看完我跪了......
  7. 华为鸿蒙系统使用视频,原生鸿蒙系统,华为WATCH 3上手视频曝光
  8. 利用DOSBox运行汇编超详细步骤
  9. C语言之取反和取相反数
  10. 前端单点登录(SSO)
  11. FreeSwitch 相关资料
  12. 【转载】机器指令计算机
  13. PDO简介及其基本使用
  14. Excel如何批量添加超链接
  15. 6岁女孩出口之乎者也 用《论语》典故批评妈妈
  16. Polar码(2)- Polar编码
  17. spin_lock 自旋锁
  18. ag-Grid 超丰富的表格插件(1)——简易使用
  19. 智能科技五大创新商业模式
  20. python代码桌面壁纸_python设置windows桌面壁纸的实现代码

热门文章

  1. python爬虫淘宝登录_python爬虫实现模拟淘宝登录
  2. 【珍藏】开发人员必看资料
  3. 关于影子(shadow)DOM
  4. 验证码机制之验证码重复使用
  5. C# GDI+双倍缓冲技术
  6. 将BT进行到底-BT客户端工具全收集
  7. BCGControlBar使用说明
  8. 实用的PyCharm编写项目教程
  9. virtualization - Ubuntu Budgie screen distortion in Hyper-V - Ask Ubuntu
  10. Ubuntu Budgie 22.10 有什么新变化