安卓开发项目——智能农业

智能农业的开发步骤

   首先需要导一下数据包。
     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;

    @Override
    protected 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);

    }

    @Override
    public 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对象
    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    //返回fragmentList对象个数
    @Override
    public 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;

    @Override
    protected 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() {
                    @Override
                    public 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对象
    @Override
    public Fragment getItem(int position) {
        return fragmentImgList.get(position);
    }
    //返回fragmentList对象个数
    @Override
    public 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() {
            @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")) {
                        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")) {
                        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();
                }

            }
        });

    }


}

接着在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() {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        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);

        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() {
            @Override
            public void onFailure(Call call, IOException e) {

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Toast.makeText(getActivity(), "失败", 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();

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public 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() {
            @Override
            public void onFailure(Call call, IOException e) {

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Toast.makeText(getActivity(), "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();

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public 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);

    }

    @Override
    public 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();
        }
    }

    @Override
    public 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;
        }
    }



    @Override
    protected 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);
    }

    @Override
    public 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;
        }
    }




    @Override
    protected 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);

    }

    @Override
    public 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;
        }
    }



    @Override
    protected 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);

    }

    @Override
    public 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;
        }
    }



    @Override
    protected 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);

    }

    @Override
    public 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;

        }

    }


}

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

阅读更多
上一篇智能农业——AsyncHttpClient获取传感器和控制沙盘
想对作者说点什么? 我来说一句

Android应用源码之智能农业

2016年09月08日 4.64MB 下载

智能农业控制系统

2016年01月18日 2.8MB 下载

没有更多推荐了,返回首页

关闭
关闭