Android——一个简单的智能家居系统

一个简单的智能家居系统

    • 效果展示
    • 启动应用界面
    • 登陆界面
    • 导航界面
      • 温度界面
      • 湿度界面
      • 烟雾传感器界面
      • 人体红外传感器界面

效果展示

以下为整个程序的操作流程,因为CSDN不能上传太大文件,所以画质比较模糊。

启动应用界面

先来看一下启动界面:效果图如下:
Android——一个简单的智能家居系统_第1张图片
这是一个比较简单的布局由一个ImageView,Textview,Switch组成
其中Switch组件的样式由俩个文件组成,thumb.xml,track.xml(都在Drawable文件里面创建)
thumb.xml文件代码:
其实两个Item都是一样的效果,因为thumb代表的滑动的轨迹,可以理解为滑块。一个是被按下的状态,一个是普通时的状态






因为两个item都是一样的,那我们就分析其中一个item,下面为滑块的效果
Android——一个简单的智能家居系统_第2张图片
open_thumb.xml代码如下:

    






    


我们接下来看一下承载滑块容易的track.xml他们同样表示两种状态,但他们是不一样的效果,因为为了突出滑动与未滑动的区别,所以背景色不一样,代码如下:


    
    


我们看一个open_track.xml文件效果和代码
Android——一个简单的智能家居系统_第3张图片



        
        
        
        
        
        

看一下未滑动时的状态布局文件shut_track.xml


    
    
    
    

看一下整体welcome.xml布局文件的代码如下:



    

    
    

然后分析一下Welcome.java代码
代码组成也比较简单,主要是在标题栏添加添加一个back键,并设置此键的功能为返回桌面(这种方式并为杀死进程,只是退出到界面,一个finish()方法也仅仅结束当前页,如果栈里面存在多个实例,并不会杀死进程,只会反复在几个页面跳转,杀死进程可以使用广播的方式,此处略过)。然后就是声明Switch控件,并对他进行监听,然后进行一个判断,如果滑动了就跳转到登陆界面

public class Welcome extends AppCompatActivity {
    private Switch Open;
    private ImageView imageView;
    private List list = new ArrayList<>();
    private  ExitAllProcess exit = new ExitAllProcess();

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

       // exit.addActivity(this);

//        imageView = findViewById(R.id.image);
//        Intent intent = getIntent();
//        Bundle bundle = intent.getExtras();
//        int view = bundle.getInt("Customview");
//        imageView.setImageResource(view);
        SetTitle();

        Open = findViewById(R.id.Open);

        Open.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    Intent intent = new Intent(Welcome.this,Login.class);
                    startActivity(intent);
                }
            }
        });
    }
    private void SetTitle() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                Intent MyIntent = new Intent(Intent.ACTION_MAIN);
                MyIntent.addCategory(Intent.CATEGORY_HOME);
                startActivity(MyIntent);
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

登陆界面

界面如下:
Android——一个简单的智能家居系统_第4张图片
login.xml布局文件代码如下:
布局较为简单,那个小眼睛就显示密码和隐藏密码,然后采用一些自定义Drawable,把EditText弄的圆一点,美观一点,其余没什么。



    

        
        

    


    

        
        



    
    
    
        
        
        
        
    

    

那我们现在看一下Login.java里面的代码:
其中一部分登陆是登陆新大陆云平台的方法,因为底层硬件获取的数据都是上传到云平台的,但是为了方便看效果,后面均以获取随机数据为基准。
其中的 SetTitle();方法和Welcome界面一样,添加一个back键,但是触发事件不一样,这个的功能是返回到Welcome界面。然后就是小眼睛那部分代码,实际就是给Imageview注册一个点击事件,然后点击之后换一张图片,然后利用EditText的属性将密码隐藏和显示,新大陆那一块可以省略,然后点击登陆跳转到导航界面。

//隐藏密码
 PassWord.setTransformationMethod(PasswordTransformationMethod.getInstance());
 //显示密码
 PassWord.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
public class Login extends AppCompatActivity {
    private Button Login;
    private EditText UserName,PassWord;
    private ImageView NotSeePassWord;
    private boolean Smalleye = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login2);
        InitView();
        OnClick();
        SetTitle();
       NotSeePassWord.setImageResource(R.drawable.closeeye);//设置初始化密码为不可见图片

    }
    private void InitView(){
        Login = findViewById(R.id.login);
        UserName = findViewById(R.id.username);
        PassWord = findViewById(R.id.password);
       // SeeThePassWord = findViewById(R.id.seethepassword);
        NotSeePassWord = findViewById(R.id.notseethepassword);
    }
    private void OnClick(){
        OnClick onClick = new OnClick();
        Login.setOnClickListener(onClick);
        //SeeThePassWord.setOnClickListener(onClick);
        NotSeePassWord.setOnClickListener(onClick);
    }


    private class OnClick implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.login:
                    SignIn();
                   break;
                case R.id.notseethepassword:
                    if (Smalleye == true)
                    {
                        SeeThePassWordMethod();
                        Smalleye = !Smalleye;
                    }else {
                        NotSeeThePassWordMethod();
                        Smalleye = !Smalleye;
                    }
                    break;
            }
        }
    }

    private void NotSeeThePassWordMethod(){
        NotSeePassWord.setImageResource(R.drawable.closeeye);
        PassWord.setTransformationMethod(PasswordTransformationMethod.getInstance());

    }
    private void SeeThePassWordMethod(){
        NotSeePassWord.setImageResource(R.drawable.openeye);
      PassWord.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
    }
    private void SignIn(){
        String platformAddress = NewloadParameter.IP_DEFAULT_VALUE;  //网址加端口号
        String LoginUserName = UserName.getText().toString();
        String LoginPassWord = PassWord.getText().toString();

        if (TextUtils.isEmpty(platformAddress)){
            Toast.makeText(this,"请配置新大陆云平台信息",Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(LoginUserName) || TextUtils.isEmpty(LoginPassWord)){
            Toast.makeText(this,"账号或者密码不能为空",Toast.LENGTH_SHORT).show();
            return;
        }
        if (!LoginPassWord.equals("123456")){
            Toast.makeText(this,"账号或者密码错误",Toast.LENGTH_SHORT).show();
            return;
        }
        if (!LoginUserName.equals("admin")){
            Toast.makeText(this,"账号或者密码错误",Toast.LENGTH_SHORT).show();
            return;
        }
        if (LoginPassWord.equals("123456") && LoginUserName.equals("admin")){
            Intent intent = new Intent(Login.this,ChooseInterface.class);
            startActivity(intent);
        }
        NetWorkBusiness netWorkBusiness = new NetWorkBusiness("",platformAddress);
        netWorkBusiness.signIn(new SignIn(LoginUserName, LoginPassWord), new NCallBack>(getApplicationContext()) {
            @Override
            protected void onResponse(BaseResponseEntity response) {

            }

            @Override
            public void onResponse(Call> call, Response> response) {
                super.onResponse(call, response);
                BaseResponseEntity baseResponseEntity = response.body(); //获取请求
                if (baseResponseEntity != null){
                    //获取访问令牌
                    String accestoken = baseResponseEntity.getResultObj().getAccessToken();
                    Intent intent = new Intent(Login.this,ChooseInterface.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("accestoken",accestoken);
                    intent.putExtras(bundle); // 传递令牌
                    startActivity(intent);
                    finish();
                }
            }
        });
  }
    private void SetTitle() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                Intent intent = new Intent(Login.this, Welcome.class);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

导航界面

效果图如下:
Android——一个简单的智能家居系统_第5张图片
代码较为简单,并不复杂,同样是使用自定义Drawable优化界面,然后一个搜索栏,这个搜索栏也是比较low的,并没有去自定义view,而是搜索那几个关键字,然后给那个图片这个一个点击事件,然后进行页面跳转。
布局文件代码如下:








    



    
    

    



    
    
    


        
        

            

            

            
        

        
    
    
    

    


看一下java部分代码:
SetTitle();和前面一样,此处省略,这个比较简单,就是几个页面的跳转,此处也省略。

public class ChooseInterface extends AppCompatActivity {
    private LinearLayout TmpView,HumView,SmokeView,InfraredView;
    private EditText SearchBar;
    private String SearchBarContent;
    private ImageView SearchImage;

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

        InitView();
        setListener();
        SearchContent();
        SetTitle();
    }
    private void SetTitle(){
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
               Intent intent = new Intent(ChooseInterface.this,Login.class);
               startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private class OnClick implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            Intent intent = null;
            switch (v.getId()){
                case R.id.TmpBox:
                    intent = new Intent(ChooseInterface.this,TmpInterface.class);
                    break;
                case R.id.HumBox:
                    intent = new Intent(ChooseInterface.this,HumInterface.class);
                    break;
                case R.id.SmokeBox:
                    intent = new Intent(ChooseInterface.this,MainActivity.class);
                    break;
                case R.id.InfraredBox:
                    intent = new Intent(ChooseInterface.this,InfraredInterface.class);
                    break;

            }
            startActivity(intent);
        }
    }
    private void setListener(){
        OnClick onClick = new OnClick();
        TmpView.setOnClickListener(onClick);
        HumView.setOnClickListener(onClick);
        SmokeView.setOnClickListener(onClick);
        InfraredView.setOnClickListener(onClick);
    }
    private void InitView(){
        TmpView = findViewById(R.id.TmpBox);
        HumView = findViewById(R.id.HumBox);
        SmokeView = findViewById(R.id.SmokeBox);
        InfraredView = findViewById(R.id.InfraredBox);
        SearchBar = findViewById(R.id.SearchBar);
        SearchImage = findViewById(R.id.SearchImage);
    }
    private void SearchContent() {
        SearchImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = null;
                SearchBarContent = SearchBar.getText().toString().trim();
                switch (SearchBarContent){
                    case "温度":
                        intent = new Intent(ChooseInterface.this,TmpInterface.class);
                        break;
                    case "湿度":
                        intent = new Intent(ChooseInterface.this,HumInterface.class);
                        break;
                    case "烟雾":
                        intent = new Intent(ChooseInterface.this,MainActivity.class);
                        break;
                    case "红外":
                        intent = new Intent(ChooseInterface.this,InfraredInterface.class);
                        break;
                }
                startActivity(intent);
            }
        });
    }
}

温度界面

先看一下效果:
两个Switch,一个控制风扇的旋转,一个控制灯泡的亮和灭,下面是一个SeekBar,下面那个SeekBar是自定义过的,和Switch一样改一下滑块和背景,根据滑动的大小,表示一个温度值,温度大小控制风扇和灯,风扇的旋转是采用动画,在java部分详细介绍。
Android——一个简单的智能家居系统_第6张图片
看一下java部分:
其余比较简单,我们就看一下InitAnimation();部分:
逐句解释:
第一句获取资源文件,有两个参数,第一个是Context上下文,第二个是图片要变化的文件,一般创建一个anim包,然后里面存放一些文件,比如我这里建了一个rotate文件,里面主要写了从那个角度开始旋转,旋转模式等
第二句:设置持续时间
第三句:设置重复模式(“restart” =从头开始 或者 “reverse”=从末尾开始)
第四句:是否当旋转完之后,继续从当前方向旋转
下面为插值器,因为我要的效果并不是很好,所以并没有使用。

 private void InitAnimation(){
        animation = AnimationUtils.loadAnimation(TmpInterface.this,R.anim.rotate);
        animation.setDuration(1000);
        //animation.setRepeatCount(-1); //无限旋转
        animation.setRepeatMode(1);
        animation.setFillAfter(true);
//            CycleInterpolator interpolator = new CycleInterpolator(1);
//            animation.setInterpolator(interpolator);
    }
public class TmpInterface extends AppCompatActivity {
    private TextView TmpValue;
    private SeekBar seekBar;
    private Switch ControlFan,ControlLamp;
    private ImageView Fan,CloseLamp,OpenLamp;
    private Animation animation;
    private static int size;
    private Button Back;



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

        SetTitle();
        InitView();
        InitAnimation();

        seekBar.setMax(50);//设置最大值
        seekBar.setProgress(0);//设置当前值
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                 size = progress;
                TmpValue.setText("温度: "+size+"℃");
                if (size > 30){
                    Fan.startAnimation(animation);
                }else {
                    Fan.clearAnimation();
                }

                if (size < 15){
                    OpenLamp.setVisibility(View.VISIBLE);
                    CloseLamp.setVisibility(View.INVISIBLE);
                }else {
                    OpenLamp.setVisibility(View.INVISIBLE);
                    CloseLamp.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        ControlFan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (ControlFan.isChecked()){
                    Fan.startAnimation(animation);
                }else {
                    Fan.clearAnimation();
                }
            }
        });
        ControlLamp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (ControlLamp.isChecked()){
                    OpenLamp.setVisibility(View.VISIBLE);
                    CloseLamp.setVisibility(View.INVISIBLE);
                }else {
                    OpenLamp.setVisibility(View.INVISIBLE);
                    CloseLamp.setVisibility(View.VISIBLE);
                }
            }
        });
    }
    //设置标题栏返回按钮
    private void SetTitle(){
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
    }
    private void InitView(){
        seekBar = findViewById(R.id.CustomSeekBar);
        TmpValue = findViewById(R.id.TmpText);
        ControlFan = findViewById(R.id.FansSwitch);
        ControlLamp = findViewById(R.id.LampSwitch);
        CloseLamp = findViewById(R.id.ShutLamp);
        OpenLamp = findViewById(R.id.OpenLamp);
        Fan = findViewById(R.id.fans);
        Back = findViewById(R.id.back);
    }
    private void InitAnimation(){
        animation = AnimationUtils.loadAnimation(TmpInterface.this,R.anim.rotate);
        animation.setDuration(1000);
        //animation.setRepeatCount(-1); //无限旋转
        animation.setRepeatMode(1);
        animation.setFillAfter(true);
//            CycleInterpolator interpolator = new CycleInterpolator(1);
//            animation.setInterpolator(interpolator);
    }
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        MenuInflater inflater = getMenuInflater();
//        inflater.inflate(R.menu.test_menu, menu);
//        return super.onCreateOptionsMenu(menu);
//    }
    //对Menu中菜单中子项进行控制
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                Intent intent = new Intent(TmpInterface.this,ChooseInterface.class);
                startActivity(intent);
                break;

        }
        return super.onOptionsItemSelected(item);
    }
}

湿度界面

效果如下:
此界面比较简单,一个RecyclerView控件,然后一个Button跳转到地图界面,关于地图界面请参考前面文章百度地图跳转链接
Android——一个简单的智能家居系统_第7张图片
看一下布局文件代码:


    
        
        
        
        
        
        
        
        
        


    
    
        
        
    
    

        
            
            
            
    
    
        
           
            
         
    
    
    
    
    

java部分:

public class HumInterface extends AppCompatActivity {
    private RecyclerView MyRecycler;
    private MyRecyclerView Adapter;
    private Button ToMap;
    private List list = new ArrayList<>();

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

        MyRecycler = findViewById(R.id.MyRecycler);
        ToMap = findViewById(R.id.ToMap);

        LinearLayoutManager manager = new LinearLayoutManager(HumInterface.this);
        MyRecycler.setLayoutManager(manager);

        Adapter = new MyRecyclerView(list);
        MyRecycler.setAdapter(Adapter);
        ListData();
        SetTitle();

        ToMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(HumInterface.this,Map.class);
                startActivity(intent);
            }
        });

    }
    private void ListData(){
        String[] GetWeatherData = {"日出","日落","06:31","18:38","降雨概率","湿度","50%","96%","风向","体感温度","北","6℃","降雨量","气压","5.8mm","1016百帕","能见度","紫外线指数","8.1Km","0"};
        for (int i = 0; i < 10 ; i=i+2) {
            for(int j = 0; j < 1; j++){
                WeatherData data = new WeatherData(GetWeatherData[i],GetWeatherData[i+1]);
                list.add(data);
            }

        }
    }
    //对标题栏返回按钮进行显示
    private void SetTitle(){
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
    }
    //对返回按钮进行操作
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                Intent intent = new Intent(HumInterface.this,ChooseInterface.class);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

烟雾传感器界面

此界面与上面的界面雷同,因为实在不知道构造一个什么界面了,数据均为随机获取
Android——一个简单的智能家居系统_第8张图片
看一下布局代码:





    
    

    

        
        
        
        

        

    
    

 

    
    
    

    
    
    
    
    





    
    
    


    
    
    
    



    

        
        
        
    
    
    
        
    
    
 
     


     

 

    
    
    
        


    




java部分:
讲一下灯泡灭和亮那部分,其实就是在布局的时候两张图片放在同一个位置,一开始亮的图片先设置为不可见,然后通过滑动Switch判断是否切换图片,切换图片的过程就是,设置两张图片的setVisibility属性。

   ShutLamp.setVisibility(View.INVISIBLE);
   OpenLamp.setVisibility(View.VISIBLE);
public class MainActivity extends AppCompatActivity {
    private Switch LampSwitch,FansSwitch;
    private ImageView OpenLamp,ShutLamp,Fans;
    private SeekBar MaxSeekBar,MinSeekBar;
    private TextView MaxTmpValue,MinTmpValue,TmpValue,HumVale,SmokeTotal,InfraredTotal;
    private Animation animation;
    private int MaxValue;
    private int MinValue;
    private static  int RandomInfrared;
    private static  int RandomSmoke;
    private static  int RandomHumValue;
    private static int RandomMaxTmpValue ;  //-100-100
   // private  static int RandomMinTmpValue = 20 - (int)(Math.random()*101);       //-80 --- 0
    //private static Boolean BooleanFans = false;  //用于判断是否开启风扇

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

        InitView();
        InitAnimation();
        //FirstDefaultExecute();
        Delay();
        SetTitle();
        //灯的开关
        LampSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (LampSwitch.isChecked())
                {
                  ShutLamp.setVisibility(View.INVISIBLE);
                  OpenLamp.setVisibility(View.VISIBLE);

                // OpenLamp.setImageDrawable(getResources().getDrawable(R.drawable.dengliang));
                }else{
                    //灭
                    OpenLamp.setVisibility(View.INVISIBLE);
                    ShutLamp.setVisibility(View.VISIBLE);
                   // ShutLamp.setBackgroundDrawable(getResources().getDrawable(R.drawable.mie));
                }
            }
        });

        //风扇开关
        FansSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (FansSwitch.isChecked()){
                    Fans.startAnimation(animation);
                }else {  Fans.clearAnimation();

                }
            }
        });
        //温度最大值滑动条
        MaxSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                MaxValue = progress;
                MaxTmpValue.setText(MaxValue+"");
                Delay();
                if (RandomMaxTmpValue > MaxValue){
                    Fans.startAnimation(animation);
                    FansSwitch.setChecked(true);
                    ShutLamp.setVisibility(View.VISIBLE);
                    OpenLamp.setVisibility(View.INVISIBLE);
                    LampSwitch.setChecked(false);
                }else if (RandomMaxTmpValue < MinValue){
                    Fans.clearAnimation();
                    FansSwitch.setChecked(false);
                    ShutLamp.setVisibility(View.INVISIBLE);
                    OpenLamp.setVisibility(View.VISIBLE);
                    LampSwitch.setChecked(true);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //温度最小值滑动条
        MinSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                MinValue = progress * (-1);
                MinTmpValue.setText(MinValue+"");
                Delay();
                if (RandomMaxTmpValue < MinValue ){
                    Fans.clearAnimation();
                    FansSwitch.setChecked(false);
                    ShutLamp.setVisibility(View.INVISIBLE);
                    OpenLamp.setVisibility(View.VISIBLE);
                    LampSwitch.setChecked(true);
                }else if (RandomMaxTmpValue > MaxValue){
                    Fans.startAnimation(animation);
                    FansSwitch.setChecked(true);
                    ShutLamp.setVisibility(View.VISIBLE);
                    OpenLamp.setVisibility(View.INVISIBLE);
                    LampSwitch.setChecked(false);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
//        //String StringTmpValue = TmpValue.getText().toString();  //当前温度值 -- string
//        String StringMinTmpValue = MinTmpValue.getText().toString();  //温度下限值
//        String StringMaxTmpValue = MaxTmpValue.getText().toString();  //温度上限值
//       // int StringToIntTmpValue = Integer.parseInt(StringTmpValue);   //当前温度值--int
//        int StringToIntTmpMinValue = Integer.parseInt(StringMinTmpValue); //温度下限值
//        int StringToIntTmpMaxValue = Integer.parseInt(StringMaxTmpValue);  //温度上限值
//        //设获取温度区间位0---100之内的随机数
//      //  int RandomTmpValue = (int)(Math.random()*(100+1)); //随机获取当前温度值
//        TmpValue.setText(RandomTmpValue+"");
//        //当前大于额定最高温度,开启风扇
//        if (RandomTmpValue > StringToIntTmpMaxValue){
//            Fans.startAnimation(animation);
//            FansSwitch.setChecked(true);
//        }
//        //当前大于额定最小温度,开启灯泡
//        if (RandomTmpValue < StringToIntTmpMinValue) {
//            Fans.clearAnimation();
//            FansSwitch.setChecked(false);
//            ShutLamp.setVisibility(View.INVISIBLE);
//            OpenLamp.setVisibility(View.VISIBLE);
//            LampSwitch.setChecked(true);
//        }
    }

    private void InitView(){
        LampSwitch = findViewById(R.id.LampSwitch);  //灯泡开关按钮
        FansSwitch = findViewById(R.id.FansSwitch);  //风扇开关按钮
        OpenLamp = findViewById(R.id.OpenLamp);      //灯开的图片
        ShutLamp = findViewById(R.id.ShutLamp);      //灯关的图片
        MaxSeekBar = findViewById(R.id.tmpMax_SeekBar);  //滑动条温度的上限值
        MinSeekBar = findViewById(R.id.tmpMIN_SeekBar);  //滑动条温度的下限值
        MaxTmpValue = findViewById(R.id.MaxSeekBarText);   //温度的上限值
        MinTmpValue = findViewById(R.id.MinSeekBarText);  //温度的下限值
        Fans = findViewById(R.id.fans);     //风扇图片
        TmpValue = findViewById(R.id.TmpValue);  //当前温度值
        HumVale = findViewById(R.id.HumValue);   //当前湿度值
        SmokeTotal = findViewById(R.id.SmokeTotal);  //烟雾传感器总数
        InfraredTotal = findViewById(R.id.InfraredTotal); //红外传感器总数
    }
//      //开启风扇
//       private  void StartRotateFans(){
//       Fans.startAnimation(animation);
//
//        }
//        //关闭风扇
//        private void EndRotateFans(){
//           Fans.clearAnimation();
//
//        }
        private void InitAnimation(){
            animation = AnimationUtils.loadAnimation(MainActivity.this,R.anim.rotate);
            animation.setDuration(1000);
            //animation.setRepeatCount(-1); //无限旋转
            animation.setRepeatMode(1);
            animation.setFillAfter(true);
//            CycleInterpolator interpolator = new CycleInterpolator(1);
//            animation.setInterpolator(interpolator);
        }
        private void Delay(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RandomMaxTmpValue = 50- (int)(Math.random()*(100+1));
                RandomHumValue = (int) (Math.random()*100+1);
                RandomSmoke = (int) (Math.random()*11);
                RandomInfrared = (int) (Math.random()*11);

                TmpValue.setText(RandomMaxTmpValue+"℃");
                HumVale.setText(RandomHumValue+"%");
                SmokeTotal.setText(RandomSmoke+"");
                InfraredTotal.setText(RandomInfrared+"");
            }
        },10); ///每隔0.01秒重新获取随机温度值
    }
    //第一次允许程序,判断温度值是大于0还是小于;
    private void FirstDefaultExecute(){
        RandomMaxTmpValue = 50- (int)(Math.random()*(100+1)); //获取当前温度值
        //开启风扇
        if (RandomMaxTmpValue > 0 ){
            Fans.startAnimation(animation);
            FansSwitch.setChecked(true);
            ShutLamp.setVisibility(View.VISIBLE);
            OpenLamp.setVisibility(View.INVISIBLE);
            LampSwitch.setChecked(false);
        }else if (RandomMaxTmpValue < 0){  //开启灯泡
            Fans.clearAnimation();
            FansSwitch.setChecked(false);
            ShutLamp.setVisibility(View.INVISIBLE);
            OpenLamp.setVisibility(View.VISIBLE);
            LampSwitch.setChecked(true);
        }else{  //等于0时,都不开启
            Fans.clearAnimation();
            FansSwitch.setChecked(false);
            ShutLamp.setVisibility(View.VISIBLE);
            LampSwitch.setChecked(false);
        }
    }
    private void SetTitle() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                Intent intent = new Intent(MainActivity.this,ChooseInterface.class);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}

人体红外传感器界面

先看一下布局效果
Android——一个简单的智能家居系统_第9张图片
代码如下:
布局简单,其中可以动的圈是自定义view,java部分详解


   
   

   
   
   
   
   
   
   

java部分:
将俩部分吧,一个是Handler部分,一个是自定义view部分
Handler部分:实现Handler.Callback接口,主要工作流程是,延迟一会,然后这个进度值,把进度值通过线程方式将这个进度值发过去,然后自定义view就把自己的进度值设置为自己的进度值。
自定义view部分:
主要是先画一个背景圆,然后在上面画一层描边(圆弧),这个是通过进度值的大小来改变的,然后关于在values下创建一个attrs.xml文件(名字不可改),然后设置圆的颜色,大小等。

public class CustomProgressBar extends View {
    private Paint BackgroundPaint;  //底层的画笔
    private Paint BufferPaint;      //上层画笔
    private int BackgroundColor;    //底层的颜色
    private int BufferColor;       //上层的颜色
    private float RingWidth;
    private int Max;
    private int CurrentProgress;
    public CustomProgressBar(Context context) {
        this(context, null);
    }

    public CustomProgressBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomProgressBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        InitAttrs(context, attrs);
        InitPaint();
    }
    private void InitPaint() {
        BackgroundPaint = new Paint();
        BackgroundPaint.setColor(BackgroundColor);
        BackgroundPaint.setStyle(Paint.Style.STROKE);  //描边样式
        BackgroundPaint.setStrokeWidth(RingWidth);
        BackgroundPaint.setAntiAlias(true); //抗锯齿

        /**
         * paint的属性
         * ANTI_ALIAS_FLAG,抗锯齿
         * UNDERLINE_TEXT_FLAG,文字下划线
         * STRIKE_THRU_TEXT_FLAG,文字中间穿过线
         * FAKE_BOLD_TEXT_FLAG,文字粗体
         * VERTICAL_TEXT_FLAG,字体垂直摆放的属性(被隐藏不可见)
         */

        /**
         * Paint.Style.FILL设置只绘制图形内容
         * *Paint.Style.STROKE设置只绘制图形的边
         *Paint.Style.FILL_AND_STROKE设置都绘制
         * */


        /**
         * paint的线帽外形
         * Paint.Cap.BUTT 没有线帽
         * Paint.Cap.ROUND 圆形线帽
         * Paint.Cap.SQUARE 方形线帽
         */

        /**
         * Paint.Join.ROUND 圆角
         * Paint.Join.MITER 锐角(默认值)
         * Paint.Join.BEVEL 直角
         */

        BufferPaint = new Paint();
        BufferPaint.setColor(BufferColor);
        BufferPaint.setStrokeWidth(RingWidth);
        BufferPaint.setStrokeCap(Paint.Cap.ROUND);
        BufferPaint.setAntiAlias(true);
        BufferPaint.setStyle(Paint.Style.STROKE);

    }

    private void InitAttrs(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomProgressBar);
        BackgroundColor = typedArray.getColor(R.styleable.CustomProgressBar_BackgroundColor, Color.GRAY);
        BufferColor = typedArray.getColor(R.styleable.CustomProgressBar_BufferColor, Color.GREEN);
        RingWidth = typedArray.getDimension(R.styleable.CustomProgressBar_RingWidth, 20);
        Max = typedArray.getInteger(R.styleable.CustomProgressBar_ProgressBarMax, 100);
        //资源回收
        typedArray.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int X = getWidth() / 2;
        int Y = getHeight() / 2;
        int Radius = (int) (X - RingWidth / 2);
        // 绘制背景圆
        canvas.drawCircle(X, Y, Radius, BackgroundPaint);
        //绘制圆的大小,Left,Top,Right,Bottom
        RectF rectF = new RectF(X - Radius, Y - Radius, X + Radius, Y + Radius);
        //ovel,开始绘制的角度,结束角度(每一个Progress等于3.6角度),是否经过圆形(因为我们前面设置了描边属性,所以即使设置为true也看不出效果,所以为false);
        canvas.drawArc(rectF, -90, CurrentProgress * 360 / Max, false, BufferPaint);

    }
    public synchronized int getMax() {
        return Max;
    }

    public synchronized void setMax(int max) {
        if (max < 0) {
            throw new IllegalArgumentException("最大进度不能小于0");
        }
        this.Max = max;
    }

    public synchronized int getProgress() {
        return CurrentProgress;
    }

    public synchronized void setProgress(int progress) {
        if (progress < 0) {
            throw new IllegalArgumentException("进度不能小于0");
        }
        if (progress > Max) {
            progress = Max;
        }
        if (progress <= Max) {
            this.CurrentProgress = progress;
            postInvalidate();
        }
    }

    public Paint getBgPaint() {
        return BackgroundPaint;
    }

    public void setBgPaint(Paint bgPaint) {
        this.BackgroundPaint = bgPaint;
    }

    public int getBgColor() {
        return BackgroundColor;
    }

    public void setBgColor(int bgColor) {
        this.BackgroundColor = bgColor;
    }

    public Paint getRingProgressPaint() {
        return BufferPaint;
    }

    public void setRingProgressPaint(Paint ringProgressPaint) {
        this.BufferPaint = ringProgressPaint;
    }

    public int getRingProgressColor() {
        return BufferColor;
    }

    public void setRingProgressColor(int ringProgressColor) {
        this.BufferColor = ringProgressColor;
    }

    public float getRingWidth() {
        return RingWidth;
    }

    public void setRingWidth(float ringWidth) {
        this.RingWidth = ringWidth;
    }
}
public class InfraredInterface extends AppCompatActivity implements  Handler.Callback{

    private CustomProgressBar MyProgressBar;
    private int Progress;
    private Handler handler;
    private TextView TipsWord,InfraredNumber;
    private ImageButton Start;
    private static int num = (int) (Math.random()*(11-1)); //0-10;

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

        SetTitle();
        InitView();

        handler = new Handler(this);
        Start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                Thread.sleep(10);
                                Progress++;
                                handler.sendEmptyMessage(1);
                                if (Progress >= 100) {
                                    test();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            }
        });
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case 1:
                MyProgressBar.setProgress(Progress);
                MyProgressBar.invalidate();
                break;
            default:
                break;
        }
        return false;
    }
    private void test(){
        TipsWord.setText("        探索完毕!");
        InfraredNumber.setText(num+"个");
    }

    private void SetTitle(){
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                Intent intent = new Intent(InfraredInterface.this,ChooseInterface.class);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    private void InitView(){

        MyProgressBar = findViewById(R.id.CustomProgressBar);
        TipsWord = findViewById(R.id.TipsWord);
        InfraredNumber = findViewById(R.id.InfraredNumber);
        Start = findViewById(R.id.Start);
    }

}

你可能感兴趣的:(Android,java,android,android,studio)