Android学习--智能农业

基于之前的基础了解如何获得接口参数,这篇文章将会基于这样的基础将智能农业项目进一步完善,尚在学习,有问题的我将新一步讨论改善。

具体步骤

1、添加依赖

dependencies {
    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'
    }

2、创建第一个视图,跳出自定义对话框

创建自定义对话框布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textSize="20dp"
        android:text="欢迎您,请先设置服务器IP"
        android:gravity="center"/>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#716c6c"/>
    <EditText
        android:id="@+id/dialog_et"
        android:layout_width="match_parent"
        android:hint="请输入设备上显示的IP地址"
        android:padding="15dp"
        android:layout_height="50dp" />
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#716c6c"/>
    <Button
        android:id="@+id/dialog_btn"
        android:layout_width="match_parent"
        android:layout_margin="15dp"
        android:text="确定"
        android:textSize="20sp"
        android:gravity="center"
        android:layout_gravity="center"
        android:layout_height="50dp" />
</LinearLayout>

ImgActivity定义自定义对话框,并将输入的IP地址传入第一个fragment页面,判定连接哪一个接口,换句话说就是想连哪一个机器就连哪个机器

public class ImgActivity extends AppCompatActivity {
    private final long SPLASH_LENGTH = 3000;
    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);//3秒后跳转至应用主界面MainActivity
    }
}

3、创建Mainactivity及视图文件,以及这个框架内的三个fragment可滑动页面

Mainactivity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //创建fragmentList集合,并进行实例化
    List<Fragment> fragmentList = new ArrayList<>();
    private ViewPager agricultureVp;
    private LinearLayout homeLin;
    private LinearLayout setLin;
    private LinearLayout helpLin;
    private static final String TAG = "MainActivity";

    @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:
        }
    }
}

activity_main:

<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.MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/main_vp"
        android:layout_width="match_parent"
        android:layout_above="@+id/main_bottom_lin"
        android:layout_height="match_parent"></android.support.v4.view.ViewPager>
    <LinearLayout
        android:id="@+id/main_bottom_lin"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">
        <LinearLayout
            android:id="@+id/home_page_lin"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center_horizontal"
            android:layout_weight="1">
            <ImageView
                android:layout_width="60dp"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:src="@mipmap/b1"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="15dp"
                android:text="首页"/>

        </LinearLayout>
        <LinearLayout
            android:id="@+id/set_lin"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center_horizontal"
            android:layout_weight="1">
            <ImageView
                android:layout_width="60dp"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:src="@mipmap/b2"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="15dp"
                android:text="设置"/>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/help_lin"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center_horizontal"
            android:layout_weight="1">
            <ImageView
                android:layout_width="60dp"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:src="@mipmap/b3"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="15dp"
                android:text="帮助"/>
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

3.1 创建适配器MyPageAdapter

public class MyPageAdapter extends FragmentPagerAdapter {
    //创建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();
    }
}

3.2

  • 创建第一个fragment,HomePageFragment,绑定适配器,接收第一个传入的IP地址适配值
  • 创建接收数据方法getAppValues,获得机器内部实时数据
  • 设置进度条,接收数据后消失(采用OKHttp方法,接收数据更快)
  • 创建方法getStatus,获得机器内部部件实时状态,接收第一个输入框传入的IP地址适配
  • 并在几个按钮上设置传值
  • 绑定图片适配器

    HomePageFragment

public class HomePageFragment extends Fragment implements View.OnClickListener {

    List<Fragment> fragmentImgList = new ArrayList<>();
    private ImageView co2Img;
    private ImageView lightImg;
    private ImageView soilImg;
    private ImageView airImg;
    private ViewPager ImgVp;
    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;
    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();
                    }
                });
            }
        });
    }

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

    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(), SunActivity.class);
                intent1.putExtra("basicUrl",basicUrl);
                startActivity(intent1);
                break;
            case R.id.soil_right_img:
                Intent intent2 = new Intent(getActivity(), TuActivity.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();
    }
}

3.3 创建App实体类作为getAppValues接收数据工具类

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

3.4 创建AppStatus实体类作为getStatus获取仪器状态工具类

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

3.5 创建OKHttp实体类方法

public class Okhttp {

    private static OkHttpClient client = new OkHttpClient();

    public static void sendOkHttpRequest(String address,okhttp3.Callback callback){

        Request request = new Request.Builder().url(address).build();
        client.newCall(request).enqueue(callback);
    }

    public static void postJsonByOkHttp(String url, JSONObject jsonObject,okhttp3.Callback callback){

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

3.6 最上方图片滑动切换,运用fragment和adapter
创建图片适配器MyImgPageAdapter:

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

3.7创建一个HttpUtil实体类,连接接口文件

public class HttpUtil {

   // private static final String basicUrl = "http://192.168.1.100:8890/type/jason/action/";

    private static AsyncHttpClient client = new AsyncHttpClient();
    public static void get (String url, RequestParams params, AsyncHttpResponseHandler responseHandler){
        client.get(url,params,responseHandler);
    }
    public static void post(Context context, String url, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler) {
        client.post(context,url,entity,contentType,responseHandler);
    }

4、

  • 创建第二个fragment,SetFragment
    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:orientation="horizontal"
        android:layout_height="50dp">
        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:src="@mipmap/zidongkongzhi" />
        <TextView
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="自动控制"
            android:layout_marginLeft="15dp"
            android:textSize="25sp"
            android:gravity="center_vertical"/>
        <ImageView
            android:layout_width="20dp"
            android:layout_height="40dp"
            android:src="@mipmap/gengduo"
            android:layout_marginRight="15dp"
            android:layout_gravity="right|center_vertical" />
    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#716c6c"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="50dp">
        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:src="@mipmap/qinchuhuancun" />
        <TextView
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="清除缓存"
            android:layout_marginLeft="15dp"
            android:textSize="25sp"
            android:gravity="center_vertical"/>
        <TextView
            android:layout_width="80dp"
            android:layout_height="40dp"
            android:text="660M"
            android:textSize="20sp"
            android:paddingRight="5dp"
            android:gravity="center"/>
    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#716c6c"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="50dp">
        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:src="@mipmap/banbengengx" />
        <TextView
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="版本更新"
            android:layout_marginLeft="15dp"
            android:textSize="25sp"
            android:gravity="center_vertical"/>
        <TextView
            android:layout_width="80dp"
            android:layout_height="40dp"
            android:text="V2.0"
            android:textSize="20sp"
            android:paddingRight="5dp"
            android:gravity="center"/>
    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#716c6c"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="50dp">
        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:src="@mipmap/guanyuwomen" />
        <TextView
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="关于我们"
            android:layout_marginLeft="15dp"
            android:textSize="25sp"
            android:gravity="center_vertical"/>
        <ImageView
            android:layout_width="20dp"
            android:layout_height="40dp"
            android:src="@mipmap/gengduo"
            android:layout_marginRight="15dp"
            android:layout_gravity="right|center_vertical" />
    </LinearLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#716c6c"/>
    <LinearLayout
       android:layout_marginTop="15dp"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="50dp">
        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:src="@mipmap/my_exit" />

        <TextView
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="退出登录"
            android:layout_marginLeft="15dp"
            android:textSize="25sp"
            android:gravity="center_vertical"/>
    </LinearLayout>
</LinearLayout>
  • 第三个fragment,HelpFragment
    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:text="帮助"
            android:textSize="35sp"
            android:textColor="#6cd545"
            android:gravity="center"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="操作指引"
            android:textSize="25sp"
            android:gravity="center"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:background="#5fb953"
        android:layout_height="50dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="1、第一条操作指引"
            android:textSize="25sp"
            android:gravity="center"/>
    </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:background="#5fb953"
        android:layout_height="50dp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="2、第二条操作指引"
            android:textSize="25sp"
            android:gravity="center"/>
    </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:background="#5fb953"
        android:layout_height="50dp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="3、第三条操作指引"
            android:textSize="25sp"
            android:gravity="center"/>
    </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:background="#5fb953"
        android:layout_height="50dp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="4、第四条操作指引"
            android:textSize="25sp"
            android:gravity="center"/>
    </LinearLayout>
</LinearLayout>

5、第一个主页面fragment主页面点击事件中传入IP值,且需要控制各个仪器,创建HTTP实体类封装8个开关方法,并创建两个标志位实体类,Status实体类判断点击之前,HTTP内含有实体类判断类点击之后
Status:

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";

}

HTTP:

public class Http {

    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;
                        Http.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;
                        Http.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")) {
                        Http.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")) {
                        Http.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")) {
                        Http.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")) {
                        Http.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")) {
                        Http.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")) {
                        Http.pumpResult = 0;
                        Status.WaterPump = 0;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

5、创建四个分类控制AirActivity,SunActivity,CO2Activity,TuActivity,并调用HTTP及Status方法,例如AirActivity

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);
            Http.Result = 0;
        } else if (Status.Blower == 1) {
            openFanImg.setImageResource(R.mipmap.dakaifengshan2);
            Http.Result = 1;
        }
    }

    private  void modifierBuzzerStatus() {
        if (Status.Buzzer == 0) {
            openAlertImg.setImageResource(R.mipmap.dakaibaojing);
            Http.alertResult = 0;
        } else if (Status.Buzzer == 1) {
            openAlertImg.setImageResource(R.mipmap.dakaibaojing2);
            Http.alertResult = 1;
        }
    }

    private  void modifierLightStatus() {
        if (Status.Roadlamp == 0) {
            openLightImg.setImageResource(R.mipmap.dakaiguangzhao);
            Http.lightResult = 0;
        } else if (Status.Roadlamp == 1) {
            openLightImg.setImageResource(R.mipmap.dakaiguangzhao2);
            Http.lightResult = 1;
        }
    }

    private  void modifierPumpStatus() {
        if (Status.WaterPump == 0) {
            openPumpImg.setImageResource(R.mipmap.dakaishui);
            Http.pumpResult = 0;
        } else if (Status.WaterPump == 1) {
            openPumpImg.setImageResource(R.mipmap.dakaishui2);
            Http.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 (Http.alertResult == 0) {
                    openAlertImg.setImageResource(R.mipmap.dakaibaojing2);
                    Intent intent = getIntent();
                    String basicUrl = intent.getStringExtra("basicUrl");
                    Http.openAlert(basicUrl, AirActivity.this);
                } else if (Http.alertResult == 1) {
                    openAlertImg.setImageResource(R.mipmap.dakaibaojing);
                    Intent intent = getIntent();
                    String basicUrl = intent.getStringExtra("basicUrl");
                    Http.closeAlert(basicUrl, AirActivity.this);
                }
                break;
            case R.id.air_fan_img:
                if (Http.Result == 0) {
                    openFanImg.setImageResource(R.mipmap.dakaifengshan2);
                    Intent intent = getIntent();
                    String basicUrl = intent.getStringExtra("basicUrl");
                    Http.openFan(basicUrl, AirActivity.this);
                } else if (Http.Result == 1) {
                    openFanImg.setImageResource(R.mipmap.dakaifengshan);
                    Intent intent = getIntent();
                    String basicUrl = intent.getStringExtra("basicUrl");
                    Http.closeFan(basicUrl, AirActivity.this);
                }
                break;
            case R.id.air_light_img:
                if(Http.lightResult==0){
                    openLightImg.setImageResource(R.mipmap.dakaiguangzhao2);
                    Intent intent = getIntent();
                    String basicUrl = intent.getStringExtra("basicUrl");
                    Http.openLight(basicUrl,AirActivity.this);
                }else if( Http.lightResult==1){
                    openLightImg.setImageResource(R.mipmap.dakaiguangzhao);
                    Intent intent = getIntent();
                    String basicUrl = intent.getStringExtra("basicUrl");
                    Http.closeLight(basicUrl,AirActivity.this);
                }
                break;
            case R.id.air_pump_img:
                if (Http.pumpResult == 0) {
                    openPumpImg.setImageResource(R.mipmap.dakaishui2);
                    Intent intent = getIntent();
                    String basicUrl = intent.getStringExtra("basicUrl");
                    Http.openPump(basicUrl, AirActivity.this);
                } else if (Http.pumpResult == 1) {
                    openPumpImg.setImageResource(R.mipmap.dakaishui);
                    Intent intent = getIntent();
                    String basicUrl = intent.getStringExtra("basicUrl");
                    Http.closePump(basicUrl, AirActivity.this);
                }
                break;
        }
    }
}

展示成果图片示图:
这里写图片描述

这里写图片描述

这里写图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值