Android项目实战——智能农业开发及思路

一、前言

智能农业这个项目是现在学习Android进行实战的必备之一,也是,智能农业这个项目虽说是移动开发的项目,但准确的来说更符合现在的物联网项目。智能农业项目需要用到模拟沙盘,我们需要从沙盘中获取沙盘中的信息。当然,想要获取沙盘中服务器的信息就必须要与沙盘在同一个局域网内,只有这样才能成功。

二、智能农业项目实现操作的思路

  1. 获取IP地址,进入所要连接的服务器
  2. 进入服务器之后获取沙盘中的信息
  3. 实现对沙盘的操控

要想实现项目的操作首先需要插入一些第三方依赖库
使用Gradle包下面的build.gradel中添加依赖库

dependencies {
    //这是里面将图片改变为圆形的插件
    compile 'com.makeramen:roundedimageview:2.2.1'
    //使用AsyncHttpClient的第三方插件
    compile 'com.loopj.android:android-async-http:1.4.9'
    //使用OkHttpClient的第三方插件
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
}

1、获取IP地址进入沙盘服务器

首先创建一个公共类来获取API接口,同时后边的操作同样需要获取API接口
公共类HttpUtil

public class HttpUtil {
    //用static做静态布局供全局使用
    private static final String BASE_URL = "http://"+ MainActivity.URL+":8890/type/jason/action/";
    //用OkHttpClient进行http请求,OkHttpClient比AsyncHttpClient获取更快
    private  static OkHttpClient client=new OkHttpClient();
    //MediaType是用OkHttpClient所要传递的json数据格式的方法
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");


    //OkHttpClient中的get与post方法
    public static void getClient(String url,Callback callback) {
        Request request=new Request.Builder().url(getAbsoluteUrl(url)).build();
        client.newCall(request).enqueue(callback);
    }
    public static void postClient(String url, JSONObject jsonObject,Callback callback){
        //RequestBody是OkHttpClient中post获取json的实例对象
        RequestBody body=RequestBody.create(JSON, jsonObject.toString());
        Request request = new Request.Builder().url(getAbsoluteUrl(url)).post(body).build();
        client.newCall(request).enqueue(callback);

    }
//这是AsyncHttpClient进行http请求的get与post方法
//    public  static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler){
//        client.get(getAbsoluteUrl(url), params, responseHandler);
//    }
//
//    public static void post(Context context,String url, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler) {
//        client.post(context,getAbsoluteUrl(url),entity, contentType, responseHandler);
//    }
    //定义一个方法进行API接口的拼接
    private static String getAbsoluteUrl(String url) {
        return BASE_URL + url;
    }

}

Activity代码

public class MainActivity extends AppCompatActivity {
    //全局定义IP接口
    public static String URL="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        modify();

    }
    private void modify() {
        //定义对话框,同时定义对话框中的输入框
        final EditText editText = new EditText(this);
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        builder.setTitle("欢迎您,请先设置服务器IP");
        builder.setView(editText);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //获取对话框中所输入的IP,进入正确的服务器
               URL= editText.getText().toString();
               //进行界面跳转
               Intent intent=new Intent(MainActivity.this,AgricultureActivity.class);
               startActivity(intent);
            }
        });
        builder.show();
    }

效果如下
这里写图片描述 这里写图片描述

2.、进入服务器之后获取沙盘中的信息

进入界面同样需要进行http请求获取沙盘的数据
界面操作我就不写了,同时这下面打的代码也只是首页的代码,后面的太多我就不写了,后面的操作基本相同
由于Activity编写下来可能会太多,这里我用了Fragment(碎片)来进行此操作

public class FirstFragment extends Fragment implements View.OnClickListener {
    ArrayList<Fragment> fragmentList = new ArrayList<>();
    private LinearLayout co2Layout;
    private LinearLayout guangzhaoLayout;
    private LinearLayout turangLayout;
    private LinearLayout kongqiLayout;
    private ViewPager viewPager;
    private Tu1Fragment tu1Fragment;
    private Tu2Fragment tu2Fragment;
    private Tu3Fragment tu3Fragment;

    private TextView conTV;
    private TextView lightTV;
    private TextView temTV1;
    private TextView humTV1;
    private TextView temTV2;
    private TextView humTV2;
    private ProgressDialog progressDialog;

    private String airHumidity;
    private String airTemperature;
    private String soilTemperature;
    private String co2;
    private String soilHumidity;
    private String light;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_first, container, false);

        co2Layout = view.findViewById(R.id.co2_layout);
        guangzhaoLayout = view.findViewById(R.id.guangzhao_layout);
        turangLayout = view.findViewById(R.id.turang_layput);
        kongqiLayout = view.findViewById(R.id.kongqi_layout);
        viewPager = view.findViewById(R.id.view_viewpager);
        conTV = view.findViewById(R.id.concentration_tv);
        lightTV = view.findViewById(R.id.guanzhao_tv);
        temTV1 = view.findViewById(R.id.tem_tv1);
        temTV2 = view.findViewById(R.id.tem_tv2);
        humTV1 = view.findViewById(R.id.hum_tv1);
        humTV2 = view.findViewById(R.id.hum_tv2);

        co2Layout.setOnClickListener(this);
        guangzhaoLayout.setOnClickListener(this);
        turangLayout.setOnClickListener(this);
        kongqiLayout.setOnClickListener(this);


        tu1Fragment = new Tu1Fragment();
        tu2Fragment = new Tu2Fragment();
        tu3Fragment = new Tu3Fragment();


        fragmentList.add(tu1Fragment);
        fragmentList.add(tu2Fragment);
        fragmentList.add(tu3Fragment);

        progressDialog = new ProgressDialog(getContext());
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
        progressDialog.setCancelable(false);// 设置是不能取消
        progressDialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        // 设置提示的title的图标,默认是没有的,如果没有设置title的话只设置Icon是不会显示图标的
        progressDialog.setTitle("正在加载");
        progressDialog.setMessage("请稍后");
        progressDialog.show();

        //OkHttpClient请求数据的方法
        HttpUtil.getClient("getSensor", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                progressDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                progressDialog.dismiss();
                String string = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(string);
                     airHumidity = jsonObject.getString("airHumidity");
                     airTemperature = jsonObject.getString("airTemperature");
                     soilTemperature = jsonObject.getString("soilTemperature");
                     co2 = jsonObject.getString("co2");
                     soilHumidity = jsonObject.getString("soilHumidity");
                     light = jsonObject.getString("light");
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            conTV.setText(co2);
                            lightTV.setText(light);
                            temTV1.setText(soilTemperature);
                            temTV2.setText(airTemperature);
                            humTV1.setText(soilHumidity);
                            humTV2.setText(airHumidity);
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
  //AsyncHttpClient获取http请求的数据
//        HttpUtil.get("getSensor", null, new TextHttpResponseHandler() {
//            @Override
//            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
////                Toast.makeText(AgricultureActivity.this,"访问失败",Toast.LENGTH_SHORT).show();
//                Log.e( "onFailure: ", "失败+++++++++++++++++++++++++++++++++++++++++++++++");
//                progressDialog.dismiss();
//            }
//
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, String responseString) {
////                Toast.makeText(AgricultureActivity.this,responseString,Toast.LENGTH_SHORT).show();
//                Log.e( "onSuccess: ", responseString+"+++++++++++++++++++++++++++++++++++");
//                progressDialog.dismiss();
//                try {
//                    JSONObject jsonObject=new JSONObject(responseString);
//                    String airHumidity=jsonObject.getString("airHumidity");
//                    String airTemperature=jsonObject.getString("airTemperature");
//                    String soilTemperature=jsonObject.getString("soilTemperature");
//                    String co2=jsonObject.getString("co2");
//                    String soilHumidity=jsonObject.getString("soilHumidity");
//                    String light=jsonObject.getString("light");
//                    conTV.setText(co2);
//                    lightTV.setText(light);
//                    temTV1.setText(soilTemperature);
//                    temTV2.setText(airTemperature);
//                    humTV1.setText(soilHumidity);
//                    humTV2.setText(airHumidity);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
        PagerAdapter adapter = new com.lenovo.liu.agriculture.adapter.PagerAdapter(getFragmentManager(), fragmentList);
        //运用fragment需要运用viewPager
        viewPager.setAdapter(adapter);
        return view;
    }

    private void bindID() {
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.co2_layout:
                Intent intent = new Intent(getContext(), CO2Activity.class);
                startActivity(intent);
                break;
            case R.id.guangzhao_layout:
                Intent intent1 = new Intent(getContext(), GuangZhao2Activity.class);
                startActivity(intent1);
                break;
            case R.id.turang_layput:
                Intent intent2 = new Intent(getContext(), TuRangActivity.class);
                startActivity(intent2);
                break;
            case R.id.kongqi_layout:
                Intent intent3 = new Intent(getContext(), KongqiActivity.class);
                startActivity(intent3);
                break;
        }

    }

}

3.、实现对沙盘的操控

同样我们需要进行对各项进行http请求,获取沙盘内各种开关的控制状态
同时我们也需要进行对沙盘进行开关操控
这里写图片描述
这里面我们要用到标志位的操作,这里我将标志位写在了一个公共类中
开关的API接口中只有0和1两种操作,0代表的状态是关,1代表的状态则是开

public class Contorl {
    public static int anInt1=0;
    public static int anInt2=0;
    public static int anInt3=0;
    public static int anInt4=0;

}

我也将获取状态的方法写在了一个公共类中,只需要调动就可以,这里我就写了一个操作的获取,其他的和其差不多

public class Uitil {


    public  void Guang(String guang,int i) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(guang, i);

        } catch (JSONException e) {
            e.printStackTrace();
        }
 //这是AsyncHttpClient进行json格式获取的一个必要方法ByteArrayEntity 
//        ByteArrayEntity entity = null;
//        try {
//            entity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
//            entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        HttpUtil.postClient("control", jsonObject, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });
//        HttpUtil.post(context, "control", entity, "application/json", new JsonHttpResponseHandler() {
//            @Override
//            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
//                super.onFailure(statusCode, headers, throwable, errorResponse);
//            }
//
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
//                super.onSuccess(statusCode, headers, response);
//            }
//
//        });
    }
}

Activity代码中需要进行一个判断,以此改变图片的状态

//判断方法,改变图片
 public static void judgedata(){
        if (Contorl.anInt1%2==0){
            fengImg.setImageResource(R.mipmap.dakaifengshan);
        }else {
            fengImg.setImageResource(R.mipmap.dakaifengshan2);
        }
        if (Contorl.anInt4%2==0){
            baoImg.setImageResource(R.mipmap.dakaibaojing);
        }else{
            baoImg.setImageResource(R.mipmap.dakaibaojing2);
        }
    }
//进行点击实现控制
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.dakaifeng_img:
                Contorl.anInt1++;
                //再次判断
                judgedata();
                uitil.Feng("Blower",Contorl.anInt1%2);

                break;
            case R.id.dakaibao_img:
                Contorl.anInt4++;
                judgedata();
                uitil.Jing("Buzzer",Contorl.anInt4%2);
                break;
        }
    }
//解析json数据,并获取数据
public static void contorl() {
        HttpUtil.getClient("getContorllerStatus", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                try {
                    JSONObject jsonObject=new JSONObject(string);
                    String Blower=jsonObject.getString("Blower");
                    String Roadlamp=jsonObject.getString("Roadlamp");
                    String WaterPump=jsonObject.getString("WaterPump");
                    String Buzzer=jsonObject.getString("Buzzer");
                    Contorl.anInt1=Integer.parseInt(Blower);
                    Contorl.anInt2=Integer.parseInt(Roadlamp);
                    Contorl.anInt3=Integer.parseInt(WaterPump);
                    Contorl.anInt4=Integer.parseInt(Buzzer);

                    //此步是更新UI的操作,但是不能在此方法中写,必须在主线程中写入,在onCreate方法中写
                    runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    judgedata();
                                 }
                    });

                    Log.e("CO2Activity: ",string+"*********************" );
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

三、总结

智能农业这个项目大多都是界面的编写比较累,其余的都没什么太大难度,里面主要的操作主要就是通过OkHttpClient进行的数据请求,里面post进行json数据解析是个难点
若想进行OkHttpClient可进入下面GitHub中一位大神的代码中学习

https://github.com/jeasonlzy/okhttp-OkGo

阅读更多

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