目录
1.风扇动画的创建
2.空调动画的创建
3.照明灯动画的实现
我的相应代码如下:
main.java
setting.java
rotate_anim.xml(电风扇)
anim.xml(照明灯)
frame_anim.xml(空调)
1.风扇动画的创建
具体都见图片注释文字
方法一:通过xml文件来实现
(白底的为老师的 黑底的为我自己的代码)
方法二:通过代码来实现
2.空调动画的创建
3.照明灯动画的实现
方法一:通过xml来实现
方法二:通过代码来实现
main.java
package com.example.smartfactory000;import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;import com.example.smartfactory000.tools.CloudHelper;
import com.example.smartfactory000.tools.SmartfactoryApplication;import java.util.Timer;
import java.util.TimerTask;public class MainActivity extends AppCompatActivity {//定义旋转类private Animation rotate;//定义空调的动画// private AnimationDrawable drawable;private TextView tvLightValue,tvTempValue,tvHumiValue;CloudHelper cloudHelper;SmartfactoryApplication smartFactory;private String lightValue,tempValve,humiValue;private Spinner spVentilation,spAc,spLight;//获取云平台传感器当前数据 handle传递数据Handler handler=new Handler (){public void handleMessage(Message msg) {switch (msg.what){case 1:tvLightValue.setText (lightValue+"lx");tvTempValue.setText (tempValve+"℃");tvHumiValue.setText (humiValue+"%RH");break;default:break;}// super.handleMessage ( msg );}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate ( savedInstanceState );setContentView ( R.layout.activity_main );//绑定显示的textviewtvLightValue=findViewById (R.id.tv_light_values);tvTempValue=findViewById (R.id.tv_temp_values);tvHumiValue=findViewById (R.id.tv_humility_values);//绑定刚刚创建的旋转的xml文件 旋转rotate= AnimationUtils.loadAnimation ( MainActivity.this,R.anim.rotate_anim );//通过代码方式来实现动画的旋转/* rotate=new RotateAnimation (0f,360f,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);//创建一个插值器LinearInterpolator lin=new LinearInterpolator ();rotate.setInterpolator ( lin );rotate.setDuration ( 1500 ); //设置转一圈的时间rotate.setRepeatCount ( -1 ); //旋转圈数rotate.setFillAfter ( true ); //指定动画停留在执行完以后的状态 即等他转完了在停下来rotate.setStartOffset ( 10 ); //动画执行前的等待时间为10毫秒*///使用适配器 任务八 通过云平台控制下拉框打开关闭自动Resources res=getResources ();String[] controlStatus=res.getStringArray (R.array.control_statue);spVentilation=findViewById (R.id.sp_ventilation_control);//数组适配器初始化final ArrayAdapter<String> adapter=new ArrayAdapter<> (this, android.R.layout.simple_list_item_1,controlStatus);spVentilation=findViewById (R.id.sp_ventilation_control);spVentilation.setAdapter ( adapter );//监听器spVentilation.setOnItemSelectedListener ( new AdapterView.OnItemSelectedListener () {@Overridepublic void onItemSelected(AdapterView<?> parent, View view, int position, long id) {Context c = getApplicationContext();String address = smartFactory.getServerAddress();String projLabel = smartFactory.getProjectLabel();String controllerId = smartFactory.getTongfConditionId ();String status = spVentilation.getItemAtPosition(position).toString();if (cloudHelper.getToken() != "") {switch (status) {case "打开":cloudHelper.onOff(c, address, projLabel, controllerId, 1);((ImageView)findViewById ( R.id.img_fan )).setAnimation ( rotate );//启动动画 startAnimAnimation((ImageView)findViewById ( R.id.img_fan )).startAnimation ( rotate );break;case "关闭":// cloudHelper.onOff(c, address, projLabel, controllerId, 0);cloudHelper.onOff (c,address,projLabel,controllerId,0);((ImageView)findViewById ( R.id.img_fan )).setAnimation ( rotate );//关闭动画 startAnimAnimation((ImageView)findViewById ( R.id.img_fan )).clearAnimation ();break;case "自动":if (Float.parseFloat(tempValve) > smartFactory.getTempThresholdValues ()) {cloudHelper.onOff(c, address, projLabel, controllerId, 1);((ImageView)findViewById ( R.id.img_fan )).setAnimation ( rotate );//启动动画 startAnimAnimation((ImageView)findViewById ( R.id.img_fan )).startAnimation ( rotate );} else {cloudHelper.onOff(c, address, projLabel, controllerId, 0);((ImageView)findViewById ( R.id.img_fan )).setAnimation ( rotate );//关闭动画 startAnimAnimation((ImageView)findViewById ( R.id.img_fan )).clearAnimation ();}break;default:break;}}}@Override
public void onNothingSelected(AdapterView<?> parent) {}
});//默认时候为关闭spVentilation.setSelection(1, true);//空调的控制spAc=findViewById (R.id.sp_air_control);spAc.setAdapter ( adapter );spAc.setOnItemSelectedListener ( new AdapterView.OnItemSelectedListener () {@Overridepublic void onItemSelected(AdapterView<?> parent, View view, int position, long id) {Context c = getApplicationContext();String address = smartFactory.getServerAddress();String projLabel = smartFactory.getProjectLabel();String controllerId = smartFactory.getAirConditionId ();String status = spAc.getItemAtPosition(position).toString();//绑定动画imagview的id 创建对象ImageView iv=findViewById ( R.id.img_ac );// ImageView.setImageResource(R.drawable.frame_anim);iv.setImageResource ( R.drawable.frame_anim );AnimationDrawable ad=(AnimationDrawable) iv.getDrawable ();if (cloudHelper.getToken() != "") {switch (status) {case "打开":cloudHelper.onOff(c, address, projLabel, controllerId, 1);ad.start ();break;case "关闭":cloudHelper.onOff(c, address, projLabel, controllerId, 0);ad.stop ();//重新设置一张照片iv.setImageResource ( R.drawable.air00 );break;case "自动":if (Float.parseFloat(humiValue) > smartFactory.getHumiThresholdValues ()) {cloudHelper.onOff(c, address, projLabel, controllerId, 1);ad.start ();} else {cloudHelper.onOff(c, address, projLabel, controllerId, 0);ad.stop ();//重新设置一张照片iv.setImageResource ( R.drawable.air00 );}break;default:break;}}}@Overridepublic void onNothingSelected(AdapterView<?> parent) {}});//默认时候为关闭spAc.setSelection(1, true);ImageView imgLight=findViewById ( R.id.img_light );Animator animator= AnimatorInflater.loadAnimator ( this,R.animator.anim );animator.setTarget ( imgLight );animator.addListener ( new AnimatorListenerAdapter () {@Overridepublic void onAnimationEnd(Animator animation) {super.onAnimationEnd ( animation );imgLight.setImageResource ( R.drawable.light);}} );//创建一个ObjectAnimator类/* final ObjectAnimator oa=ObjectAnimator.ofFloat ( imgLight,"alpha",1f,0.5f,1f ).setDuration ( 1500 );//添加一个监听器 监听开始与结束oa.addListener ( new AnimatorListenerAdapter () {@Overridepublic void onAnimationEnd(Animator animation) {super.onAnimationEnd ( animation );imgLight.setImageResource ( R.drawable.light);}} );*/spLight=findViewById (R.id.sp_light_control);spLight.setAdapter ( adapter );spLight.setOnItemSelectedListener ( new AdapterView.OnItemSelectedListener () {@Overridepublic void onItemSelected(AdapterView<?> parent, View view, int position, long id) {Context c = getApplicationContext();String address = smartFactory.getServerAddress();String projLabel = smartFactory.getProjectLabel();String controllerId = smartFactory.getLightControlId ();String status = spLight.getItemAtPosition(position).toString();if (cloudHelper.getToken() != "") {switch (status) {case "打开":cloudHelper.onOff(c, address, projLabel, controllerId, 1);// oa.start ();animator.start ();break;case "关闭":cloudHelper.onOff(c, address, projLabel, controllerId, 0);imgLight.setImageResource ( R.drawable.light_off );break;case "自动":if (Float.parseFloat(lightValue) > smartFactory.getLightThresholdValues ()) {cloudHelper.onOff(c, address, projLabel, controllerId, 1);animator.start ();} else {cloudHelper.onOff(c, address, projLabel, controllerId, 0);imgLight.setImageResource ( R.drawable.light_off );}break;default:break;}}}@Overridepublic void onNothingSelected(AdapterView<?> parent) {}});//默认时候为关闭spLight.setSelection(1, true);//loadCloudData 任务七7.4从云平台获取数据loadCloudData ();}//!!!!原来问题在这里!!!!!//获取云平台数据public void loadCloudData(){// Toast.makeText ( this, "云平台能够登录", Toast.LENGTH_SHORT ).show ();//登录云平台// smartFactory=new SmartfactoryApplication ();smartFactory=(SmartfactoryApplication) getApplication ();cloudHelper=new CloudHelper ();//判断当前保存参数if(smartFactory!=null&&smartFactory.getServerAddress()!=""&&smartFactory.getCloudAccount ()!=""&&smartFactory.getCloudAccountPassword ()!=""){// Toast.makeText ( this, "云平台能够登录", Toast.LENGTH_SHORT ).show ();cloudHelper.signIn (getApplicationContext (),smartFactory.getServerAddress (),smartFactory.getCloudAccount (),smartFactory.getCloudAccountPassword ());}//用定时器每隔五秒钟从云平台获取一次数据 约等于开了一个线程new Timer ().schedule ( new TimerTask () {@Overridepublic void run() {// Toast.makeText (MainActivity.this, "取数据", Toast.LENGTH_SHORT ).show ();//从云平台拿数据if(cloudHelper.getToken ()!=""){//通过getSensor方法获取数据cloudHelper.getSensorData ( getApplicationContext (),smartFactory.getServerAddress (),smartFactory.getProjectLabel (),smartFactory.getLightSensorId (),new CloudHelper.DCallback () {@Overridepublic void trans(String s) {lightValue=s;//日志 方便查看是否获得Log.d("lightValue",s);}});cloudHelper.getSensorData ( getApplicationContext (),smartFactory.getServerAddress (),smartFactory.getProjectLabel (),smartFactory.getTempSensorId (),new CloudHelper.DCallback () {@Overridepublic void trans(String s) {tempValve=s;Log.d ( "tempValue",s );}}/* new CloudHelper.DCallback () {@Overridepublic void trans(String s) {tempValve=s;Log.d("tempValue",s);}}*/);cloudHelper.getSensorData ( getApplicationContext (),smartFactory.getServerAddress (),smartFactory.getProjectLabel (),smartFactory.getHumiSensorId (),new CloudHelper.DCallback () {@Overridepublic void trans(String s) {humiValue=s;Log.d("humiValue",s);}});// boolean b = handler.sendMessage ( 1 );//通过handler发送过去数据handler.sendEmptyMessage ( 1 );}}},0,5000);}//活动条的创建@Overridepublic boolean onCreateOptionsMenu(Menu menu){getMenuInflater ().inflate (R.menu.menu_main_xml,menu);//一个方法吧 我猜return super.onCreateOptionsMenu (menu);}@Overridepublic boolean onOptionsItemSelected(MenuItem menuItem){ //可能就是点击之后做跳转的 具体不太清楚明了这是干啥的switch (menuItem.getItemId ()){case R.id.setting:Intent intent=new Intent (MainActivity.this,SettingActivity.class);//带数据传输过去intent.putExtra ("tempValus",tempValve);intent.putExtra ("humiValue",humiValue);intent.putExtra ("lightValue",lightValue);startActivity (intent);return true;default:return super.onOptionsItemSelected (menuItem);}}}
setting.java
package com.example.smartfactory000;import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;import com.example.smartfactory000.tools.SmartfactoryApplication;
//传感器数据
public class SettingActivity extends AppCompatActivity {private EditText serverAddress;private EditText projectLabel;private EditText cloudAccountPassword;private EditText cloudAccount;private EditText cameraAddress;private EditText tempSensorId;private EditText tempThresholdValves;private EditText humiSensorId;private EditText humiThresholdValves;private EditText lightSensorId;private EditText lightThresholdValues;private EditText bodySensorId;private EditText lightControlId;private EditText tongfSensorId;private EditText airConditionId;private SmartfactoryApplication smartFactory;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate ( savedInstanceState );setContentView ( R.layout.activity_setting );//通过getApplication()方法来得到smartFactory的对象smartFactory=(SmartfactoryApplication) getApplication ();initView ();
// Intent intent=getIntent ();
// String tempValves=intent.getStringExtra ("tempValves");
// TextView textView=(TextView) findViewById (R.id.tv_temp);
// textView.setText (tempValves);
// // TextView.setText=(tempValves);}//按钮点击事件保存//保存数据public void onClickSaved(View view) {smartFactory.setServerAddress (serverAddress.getText ().toString ().trim ());smartFactory.setProjectLabel (projectLabel.getText ().toString ().trim ());smartFactory.setCloudAccount (cloudAccount.getText ().toString ().trim ());smartFactory.setCloudAccountPassword (cloudAccountPassword.getText ().toString ().trim ());smartFactory.setCameraAddress (cameraAddress.getText ().toString ().trim ());smartFactory.setTempSensorId (tempSensorId.getText ().toString ().trim ());// smartFactory.setTempSensorId (tempSensorId.getText ().toString ().trim ());smartFactory.setTempThresholdValues (Float.parseFloat (tempThresholdValves.getText ().toString ().trim ()));smartFactory.setHumiSensorId (humiSensorId.getText ().toString ().trim ());smartFactory.setHumiThresholdValues (Float.parseFloat (humiThresholdValves.getText ().toString ().trim ()));smartFactory.setLightSensorId (lightSensorId.getText ().toString ().trim ());smartFactory.setLightThresholdValues (Float.parseFloat (lightThresholdValues.getText ().toString ().trim ()));smartFactory.setBodySensorId (bodySensorId.getText ().toString ().trim ());smartFactory.setLightControlId ( lightControlId.getText ().toString ().trim ());smartFactory.setTongfConditionId (tongfSensorId.getText ().toString ().trim ());smartFactory.setAirConditionId (airConditionId.getText ().toString ().trim ());if(!CheckInput (smartFactory)){return;}//双重保存 保存又一个在params里面else{SharedPreferences sharePref=getSharedPreferences ("params",MODE_PRIVATE);SharedPreferences.Editor editor=sharePref.edit ();editor.putString ("server_address",smartFactory.getServerAddress ());editor.putString ("project_label",smartFactory.getProjectLabel ());editor.putString ("cloud_account",smartFactory.getCloudAccount ());editor.putString ("cloud_account_password",smartFactory.getCloudAccountPassword ());editor.putString ("camera_address",smartFactory.getCameraAddress ());editor.putString("temp_sensor_id",smartFactory.getTempSensorId ());editor.putFloat ("temp_threshold_valves",smartFactory.getTempThresholdValues ());editor.putString ("humi_sensor_id",smartFactory.getHumiSensorId ());editor.putFloat ("humi_threshold_values",smartFactory.getHumiThresholdValues ());editor.putString("light_sensor_id",smartFactory.getLightSensorId ());editor.putFloat ("light_threshold_values",smartFactory.getLightThresholdValues ());editor.putString ("body_sensor_id",smartFactory.getBodySensorId ());editor.putString ("ight_control_id",smartFactory.getBodySensorId ());editor.putString ("light_control_id",smartFactory.getLightControlId ());editor.putString ("tongt_seneor_id",smartFactory.getTongfConditionId ());editor.putString("aircondition_id",smartFactory.getAirConditionId ());editor.commit ();//保存成功的Toast提示框showToast (R.string.save_params_success);Intent intent=new Intent (this,MainActivity.class);startActivity (intent);}/* Toast showToast= Toast.makeText ( this,"保存成功",Toast.LENGTH_SHORT);showToast.setGravity ( Gravity.CENTER,0,0 );showToast.show ();*/
// //保存数据
// SharedPreferences sharedPref = getSharedPreferences ( "params", MODE_PRIVATE );
// SharedPreferences.Editor editor = sharedPref.edit ();
// editor.putString ( "server_address", serverAddress.getText ().toString () );
// editor.putString ( "project_lable", projectLabel.getText ().toString () );
// editor.putString ( "cloud_account", cloudAccount.getText ().toString () );
// editor.putString ( "cloud_account_passward", cloudAccountPassword.getText ().toString () );
// editor.putString ( "camera_address", cameraAddress.getText ().toString () );
// editor.putString ( "temp_sensor_id", tempSensorId.getText ().toString () );
// editor.putString ( "temp_threshold_values", tempThresholdValves.getText ().toString () );
// editor.putString ( "humi_sensor_id", humiSensorId.getText ().toString () );
// editor.putString ( "humi_threshold_values", humiThresholdValves.getText ().toString () );
// editor.putString ( "light_sensor_id", lightSensorId.getText ().toString () );
// editor.putString ( "light_threshold_values", lightThresholdValues.getText ().toString () );
// editor.putString ( "body_sensor_id", bodySensorId.getText ().toString () );
// editor.putString ( "light_control_id", lightControlId.getText ().toString () );
// editor.putString ( "tongt_seneor_id", tongfSensorId.getText ().toString () );
// editor.putString ( "aircondition_id", airConditionId.getText ().toString () );
// editor.commit (); //确认}//Toast 消息盒子的弹出提示消息 检查有没有输入private boolean CheckInput(SmartfactoryApplication smartFactory){boolean result=true;//当服务器地址为空时if(smartFactory.getServerAddress ().equals ("")){showToast (R.string.server_address_empty);return false;}//当云平台标识为空时if(smartFactory.getProjectLabel ().equals ("")){showToast (R.string.cloud_project_empty);return false;}//当云平台账户为空时if(smartFactory.getCloudAccount ().equals ("")){showToast (R.string.cloud_account_empty);return false;}//当云平台密码为空时if(smartFactory.getCloudAccountPassword ().equals ("")){showToast (R.string.cloud_account_password_empty);return false;}//当摄像头地址为空时if(smartFactory.getCameraAddress ().equals ("")){showToast (R.string.camera_address_empty);return false;}return result;}//消息盒子模板private void showToast(int resId){Toast showToast;showToast=Toast.makeText (this,resId,Toast.LENGTH_SHORT);showToast.setGravity (Gravity.CENTER,0,0);showToast.show ();}private void initView() {serverAddress = (EditText) findViewById ( R.id.et_server_address );projectLabel = (EditText) findViewById ( R.id.et_cloud_project_label );cloudAccount = (EditText) findViewById ( R.id.et_cloud_account );cloudAccountPassword = (EditText) findViewById ( R.id.et_cloud_account_password );cameraAddress = (EditText) findViewById ( R.id.et_camera_address );tempSensorId = (EditText) findViewById ( R.id.et_temp_sensor_values );tempThresholdValves = (EditText) findViewById ( R.id.et_temp_threshold_values );humiSensorId = (EditText) findViewById ( R.id.et_humi_sensor_id );humiThresholdValves = (EditText) findViewById ( R.id.et_humi_threshold_valves );lightSensorId = (EditText) findViewById ( R.id.et_light_sensor_id );lightThresholdValues = (EditText) findViewById ( R.id.et_light_threshold_values );bodySensorId = (EditText) findViewById ( R.id.et_body_sensor_id );lightControlId = (EditText) findViewById ( R.id.et_light_control_id );tongfSensorId = (EditText) findViewById ( R.id.et_tongf_control_id );airConditionId = (EditText) findViewById ( R.id.et_air_control_id );//得到阈值数据Intent intent=getIntent ();Float lightValue=intent.getFloatExtra ("lightValue",1000);Float tempValue=intent.getFloatExtra ("tempValue",25);Float humiValue=intent.getFloatExtra ("humiValues",55);//显示在阈值文本框里面lightThresholdValues.setText ( lightValue.toString () );tempThresholdValves.setText ( tempValue.toString () );humiThresholdValves.setText ( humiValue.toString () );}
}
rotate_anim.xml(电风扇)
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"><rotateandroid:drawable="@drawable/fan"android:fromDegrees="0"android:interpolator="@android:anim/linear_interpolator"android:pivotX="50%"android:pivotY="50%"android:toDegrees="360"android:repeatCount="-1"android:visible="true"android:duration="1500" /></set>
anim.xml(照明灯)
<set xmlns:android="http://schemas.android.com/apk/res/android"><set android:ordering="sequentially"><objectAnimatorandroid:duration="1000"android:propertyName="alpha"android:valueFrom="1"android:valueTo="0"android:valueType="floatType"></objectAnimator><objectAnimatorandroid:duration="1000"android:propertyName="alpha"android:valueFrom="0"android:valueTo="1"android:valueType="floatType"></objectAnimator></set></set>
frame_anim.xml(空调)
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"android:oneshot="false">
<!-- <item android:drawable="@drawable/air00"-->
<!-- android:duration="150"></item>--><item android:drawable="@drawable/air03"android:duration="150"></item><item android:drawable="@drawable/air01"android:duration="150"></item><item android:drawable="@drawable/air02"android:duration="150"></item><item android:drawable="@drawable/air01"android:duration="150"></item></animation-list>