用ESP8266+android,制作自己的WIFI小车(Android 软件)

先说一下这篇文章里面的内容:TCP 客户端, 自定义对话框, 自定义按钮, ProgressBar竖直显示, 重力感应传感器,手机返回键新开启界面的问题(返回上次的界面),数据保存

软件的通信是配合

http://www.cnblogs.com/yangfengwu/p/7625608.html用ESP8266+android,制作自己的WIFI小车(ESP8266篇)

软件的第一个界面就一个按钮点击按钮弹出一个自定义的对话框连接的时候连接上

其实一开始想多加一些功能,,不过后来想了想复杂了反而不利于学习.........我会从一开始做到结束都写清楚,如果有大神看到哪地方不合理请指教哈,,,,,

好现在开始做APP

一路Next就行...

您会发现自己的按钮是圆边的

其实是自己自定义了一些参数

新建一个文件夹存储咱们自定义的一些东西

对了为什么名字是drawable

其实是官方提供的,,

http://www.android-doc.com/guide/topics/resources/drawable-resource.html#StateList

然后呢各个参数后面都有具体解释

有些小伙伴一看....英文的............大哥下一个有道翻译或者别的翻译软件翻译一下...................

可以自己搜索自己想要的

好像这些外形啦背景什么的都在

授人予鱼,也要授人予渔;

首先定义一下外形

方形

然后呢描一下边框,,,显得是一个按钮

其实可以官方解释

然后定义一下按钮现在显示的颜色

好现在让它的四个角变成圆角,,,对于我这个学机械的而言在solidworks里面应该叫做倒角,,,,有没有学机械的看到这篇文章哈...

记得曾经遇到一个人和我正好相反,,我是报的机械专业,自学的电气,,,,,,而另一个人是报的电气却喜欢机械........兴趣.........

好啦

拖一个按钮过来,放到中心.....您也可以在布局文件里面自己写哈......我是怎样方便怎样弄,,我用的是相对布局

保存一下现在看效果

好现在再定义一个按钮按下时的外表文件

privateOnTouchListener buttonconnect1Touch =newOnTouchListener() {

@Overridepublicboolean onTouch(View v, MotionEventevent) {//TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN) {

buttonconnect1.setBackgroundResource(R.drawable.buttondown);

}if(event.getAction()==MotionEvent.ACTION_UP) {

buttonconnect1.setBackgroundResource(R.drawable.butonup);

}returnfalse;

}

};

package com.wificardemo;

import android.app.Activity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.MotionEvent;

import android.view.View;

import android.view.View.OnTouchListener;

import android.widget.Button;publicclassMainActivity extends Activity {

Button buttonconnect1;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

buttonconnect1= (Button) findViewById(R.id.button11);//获取按钮buttonconnect1.setOnTouchListener(buttonconnect1Touch);//按钮的触摸事件}privateOnTouchListener buttonconnect1Touch =newOnTouchListener() {

@Overridepublicboolean onTouch(View v, MotionEventevent) {//TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN) {

buttonconnect1.setBackgroundResource(R.drawable.buttondown);

}if(event.getAction()==MotionEvent.ACTION_UP) {

buttonconnect1.setBackgroundResource(R.drawable.butonup);

}returnfalse;

}

};

@Overridepublicboolean onCreateOptionsMenu(Menu menu) {//Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);returntrue;

}

@Overridepublicboolean onOptionsItemSelected(MenuItem item) {//Handle action bar item clicks here. The action bar will//automatically handle clicks on the Home/Up button, so long//as you specify a parent activity in AndroidManifest.xml.intid =item.getItemId();if(id ==R.id.action_settings) {returntrue;

}returnsuper.onOptionsItemSelected(item);

}

}

现在编译一下运行到手机看一下

我是直接用的自己的手机,,没有仿真,,现在我的电脑用仿真可是不得了......

平时的状态                          按下后

自己看着改改大小和显示

咱们现在要做的是

其实这个是自己自定义的一个界面

对了设置一下主题风格...

感觉这种风格挺好的

图片可以在我源码里面找,也可以自己弄自己的

对了,,,,位置还有名字什么的自己看着修改哈

整体界面呢,,,

   

android:background="@android:color/white"android:id="@+id/textView22"android:layout_width="wrap_content"android:layout_height="2dip"android:layout_alignParentLeft="true"android:layout_alignParentRight="true"android:layout_below="@+id/imageView21"android:layout_marginTop="15dp"/>   

android:id="@+id/textView21"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="8dp"android:layout_marginLeft="19dp"android:layout_toRightOf="@+id/imageView21"android:text="连接"android:textAppearance="?android:attr/textAppearanceLarge"android:textColor="@android:color/white"/>   

android:id="@+id/textView23"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_below="@+id/textView22"android:layout_marginTop="23dp"android:text="IP地址:"/>   

android:id="@+id/editText21"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBaseline="@+id/textView23"android:layout_alignBottom="@+id/textView23"android:layout_alignLeft="@+id/textView21"android:ems="10"android:text="192.168.4.1"/>   

android:id="@+id/imageView21"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:layout_marginTop="14dp"android:src="@drawable/image1"/>   

android:id="@+id/textView24"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBaseline="@+id/editText22"android:layout_alignBottom="@+id/editText22"android:layout_alignParentLeft="true"android:text="端口号:"/>   

android:id="@+id/editText22"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/editText21"android:layout_below="@+id/editText21"android:layout_marginTop="10dp"android:ems="10"android:text="8080"/>   

android:id="@+id/button21"android:layout_width="80dp"android:layout_height="40dp"android:layout_alignParentRight="true"android:layout_below="@+id/editText22"android:layout_marginRight="10dp"android:background="@drawable/butonup"android:text="连接"/>   

android:id="@+id/Button22"android:layout_width="80dp"android:layout_height="40dp"android:layout_alignBottom="@+id/button21"android:layout_alignTop="@+id/button21"android:layout_marginLeft="10dp"android:background="@drawable/butonup"android:text="取消"/>   

android:id="@+id/progressBar21"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignTop="@+id/textView23"android:layout_centerHorizontal="true"/>

好了现在点击主界面的按钮把这个界面当做提示框显示出来

package com.wificardemo;

import android.app.Activity;

import android.app.AlertDialog;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.MotionEvent;

import android.view.View;

import android.view.View.OnTouchListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ProgressBar;

import android.widget.TextView;publicclassMainActivity extends Activity {

Button buttonconnect1;

AlertDialog AlertDialog21;//定义一个提示框View View1;//定义一个view用来获取咱们自定义的界面Button connectbutton21;//连接服务器Button cancelbutton22;//取消按钮ProgressBar progressBar21;//进度条EditText iPEditText;//IP地址EditText portEditText;//端口号TextView titleEditText;//"连接"@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setTheme(android.R.style.Theme);//设置主题风格setContentView(R.layout.activity_main);

buttonconnect1= (Button) findViewById(R.id.button11);//获取按钮buttonconnect1.setOnTouchListener(buttonconnect1Touch);//按钮的触摸事件/**对话框相关**/AlertDialog21=newAlertDialog.Builder (MainActivity.this).create();

View1= View.inflate(MainActivity.this, R.layout.dialog,null);

AlertDialog21.setView(View1);//设置显示内容为自定义的界面connectbutton21 = (Button) View1.findViewById(R.id.button21);//连接服务器按钮cancelbutton22 = (Button) View1.findViewById(R.id.Button22);//取消按钮progressBar21 = (ProgressBar) View1.findViewById(R.id.progressBar21);//进度条progressBar21.setVisibility(-1);//进度条不显示iPEditText = (EditText)View1.findViewById(R.id.editText21);//IP地址portEditText = (EditText)View1.findViewById(R.id.editText22);//端口号titleEditText = (TextView) View1.findViewById(R.id.textView21);//"连接"}/***

* 主界面连接服务器按钮*/privateOnTouchListener buttonconnect1Touch =newOnTouchListener() {

@Overridepublicboolean onTouch(View v, MotionEventevent) {//TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN) {

buttonconnect1.setBackgroundResource(R.drawable.buttondown);

}if(event.getAction()==MotionEvent.ACTION_UP) {

buttonconnect1.setBackgroundResource(R.drawable.butonup);

}returnfalse;

}

};

}

现在呢就缺少显示了...

我们在主按钮的点击事件中调用显示函数

package com.wificardemo;

import android.app.Activity;

import android.app.AlertDialog;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.MotionEvent;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.View.OnTouchListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ProgressBar;

import android.widget.TextView;publicclassMainActivity extends Activity {

Button buttonconnect1;

AlertDialog AlertDialog21;//定义一个提示框View View1;//定义一个view用来获取咱们自定义的界面Button connectbutton21;//连接服务器Button cancelbutton22;//取消按钮ProgressBar progressBar21;//进度条EditText iPEditText;//IP地址EditText portEditText;//端口号TextView titleEditText;//"连接"@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setTheme(android.R.style.Theme);//设置主题风格setContentView(R.layout.activity_main);

buttonconnect1= (Button) findViewById(R.id.button11);//获取按钮buttonconnect1.setOnClickListener(buttonconnect1Click);//按钮点击事件buttonconnect1.setOnTouchListener(buttonconnect1Touch);//按钮的触摸事件/**对话框相关**/AlertDialog21=newAlertDialog.Builder (MainActivity.this).create();

View1= View.inflate(MainActivity.this, R.layout.dialog,null);

AlertDialog21.setView(View1);//设置显示内容为自定义的界面connectbutton21 = (Button) View1.findViewById(R.id.button21);//连接服务器按钮cancelbutton22 = (Button) View1.findViewById(R.id.Button22);//取消按钮progressBar21 = (ProgressBar) View1.findViewById(R.id.progressBar21);//进度条progressBar21.setVisibility(-1);//进度条不显示iPEditText = (EditText)View1.findViewById(R.id.editText21);//IP地址portEditText = (EditText)View1.findViewById(R.id.editText22);//端口号titleEditText = (TextView) View1.findViewById(R.id.textView21);//"连接"}/***

* 主按钮点击事件*/privateOnClickListener buttonconnect1Click =newOnClickListener() {

@OverridepublicvoidonClick(View v) {//TODO Auto-generated method stubAlertDialog21.show();

}

};/***

* 主界面连接服务器按钮背景改变*/privateOnTouchListener buttonconnect1Touch =newOnTouchListener() {

@Overridepublicboolean onTouch(View v, MotionEventevent) {//TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN) {

buttonconnect1.setBackgroundResource(R.drawable.buttondown);

}if(event.getAction()==MotionEvent.ACTION_UP) {

buttonconnect1.setBackgroundResource(R.drawable.butonup);

}returnfalse;

}

};

}

现在安装到手机上看一下---界面还可以

做这个简单的取消事件

连接按钮呢!!我先说一下思路,,,按下连接按钮是启动一个连接任务,然后呢还要启动一个倒计时器(3S),,,控制这个连接任务执行的时间,还要显示进度条,,如果3S内连接上了,,那么在连接的后面关掉进度条,结束这个连接任务,取消定时器,关闭对话框,然后进入控制界面,,如果3S内没有连接上,也关闭连接任务,关掉进度条,同时显示连接失败.

现在的

package com.wificardemo;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.InetAddress;

import java.net.Socket;

import android.app.Activity;

import android.app.AlertDialog;

import android.os.Bundle;

import android.os.CountDownTimer;

import android.renderscript.Mesh.Primitive;

import android.view.Menu;

import android.view.MenuItem;

import android.view.MotionEvent;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.View.OnTouchListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ProgressBar;

import android.widget.TextView;publicclassMainActivity extends Activity {

Button buttonconnect1;

AlertDialog AlertDialog21;//定义一个提示框View View1;//定义一个view用来获取咱们自定义的界面Button connectbutton21;//连接服务器Button cancelbutton22;//取消按钮ProgressBar progressBar21;//进度条EditText iPEditText;//IP地址EditText portEditText;//端口号TextView titleEditText;//"连接"String Ipstring="";//记录IP地址intportint=0;//记录端口号boolean ConnectFlage=true;intShowPointSum=0;//显示点的数量,连接中.....(后面的点)Socket socket =null;//定义socketInetAddress ipAddress;

OutputStream outputStream=null;//定义输出流InputStream inputStream=null;//定义输入流@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setTheme(android.R.style.Theme);//设置主题风格setContentView(R.layout.activity_main);

buttonconnect1= (Button) findViewById(R.id.button11);//获取按钮buttonconnect1.setOnClickListener(buttonconnect1Click);//按钮点击事件buttonconnect1.setOnTouchListener(buttonconnect1Touch);//按钮的触摸事件/**对话框相关**/AlertDialog21=newAlertDialog.Builder (MainActivity.this).create();

View1= View.inflate(MainActivity.this, R.layout.dialog,null);

AlertDialog21.setView(View1);//设置显示内容为自定义的界面connectbutton21 = (Button) View1.findViewById(R.id.button21);//连接服务器按钮cancelbutton22 = (Button) View1.findViewById(R.id.Button22);//取消按钮progressBar21 = (ProgressBar) View1.findViewById(R.id.progressBar21);//进度条progressBar21.setVisibility(-1);//进度条不显示iPEditText = (EditText)View1.findViewById(R.id.editText21);//IP地址portEditText = (EditText)View1.findViewById(R.id.editText22);//端口号titleEditText = (TextView) View1.findViewById(R.id.textView21);//"连接"cancelbutton22.setOnClickListener(cancelbutton22Click);//对话框取消事件connectbutton21.setOnClickListener(connectbutton21Click);//对话框连接按钮点击事件}/***

* 对话框连接按钮点击事件*/privateOnClickListener connectbutton21Click =newOnClickListener() {

@OverridepublicvoidonClick(View v) {//TODO Auto-generated method stubIpstring = iPEditText.getText().toString().replace("","");

portint= Integer.valueOf(portEditText.getText().toString().replace("",""));

progressBar21.setVisibility(0);//显示进度条tcpClientCountDownTimer.cancel();

tcpClientCountDownTimer.start();

ConnectFlage=true;

ShowPointSum=0;

ConnectSeverThread connectSeverThread=newConnectSeverThread();

connectSeverThread.start();

}

};/***

*

* @author 连接服务器任务

**/classConnectSeverThread extends Thread

{publicvoidrun()

{while(ConnectFlage)

{try{

ipAddress=InetAddress.getByName(Ipstring);

socket=newSocket(ipAddress, portint);

ConnectFlage=false;

tcpClientCountDownTimer.cancel();

runOnUiThread(newRunnable()

{publicvoidrun()

{

progressBar21.setVisibility(-1);//关闭滚动条AlertDialog21.cancel();//关闭提示框}

});

inputStream= socket.getInputStream();//获取输入流}catch(IOException e)

{//TODO Auto-generated catch blocke.printStackTrace();

}

}

}

}/***

* 对话框取消按钮事件*/privateOnClickListener cancelbutton22Click =newOnClickListener() {

@OverridepublicvoidonClick(View v) {//TODO Auto-generated method stubConnectFlage =false;//取消连接任务tcpClientCountDownTimer.cancel();//结束定时器progressBar21.setVisibility(-1);//关闭滚动条AlertDialog21.cancel();//关闭对话框}

};/***

* 延时3s的定时器*/privateCountDownTimer tcpClientCountDownTimer =newCountDownTimer(3000,200) {

@OverridepublicvoidonTick(longmillisUntilFinished) {//每隔200ms进入if(ConnectFlage)

{    ShowPointSum++;switch(ShowPointSum%9)

{case0:titleEditText.setText("连接中");break;case1:titleEditText.setText("连接中.");break;case2:titleEditText.setText("连接中..");break;case3:titleEditText.setText("连接中...");break;case4:titleEditText.setText("连接中....");break;case5:titleEditText.setText("连接中.....");break;case6:titleEditText.setText("连接中......");break;case7:titleEditText.setText("连接中.......");break;case8:titleEditText.setText("连接中........");break;default:break;

}

}

}

@OverridepublicvoidonFinish() {//3s后进入(没有取消定时器的情况下)if(ConnectFlage)

{    ConnectFlage=false;

progressBar21.setVisibility(-1);//关闭滚动条titleEditText.setText("连接服务器失败!!");

}

tcpClientCountDownTimer.cancel();

}

};/***

* 主按钮点击事件*/privateOnClickListener buttonconnect1Click =newOnClickListener() {

@OverridepublicvoidonClick(View v) {//TODO Auto-generated method stubtitleEditText.setText("连接");

AlertDialog21.show();

}

};/***

* 主界面连接服务器按钮背景改变*/privateOnTouchListener buttonconnect1Touch =newOnTouchListener() {

@Overridepublicboolean onTouch(View v, MotionEventevent) {//TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN) {

buttonconnect1.setBackgroundResource(R.drawable.buttondown);

}if(event.getAction()==MotionEvent.ACTION_UP) {

buttonconnect1.setBackgroundResource(R.drawable.butonup);

}returnfalse;

}

};

}

现在加上权限然后连接WIFI模块测试一下哈

                     

连接模块的无线

然后会发现

对话框消失了

因为咱们自己设置的消失

现在让它连接后打开控制界面

还是先把IP和端口号的信息做成能够保存的吧

咱们就用SharedPreferences

可以看一下这篇文章的介绍

http://blog.csdn.net/baidu_31093133/article/details/51476726##1

得到SharedPreferences对象

然后

那么一开始运行就要检测是不是记录了,,如果记录了就取出来记录的数据然后显示在对应的文本框中

整体的代码

package com.wificardemo;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.InetAddress;

import java.net.Socket;

import android.app.Activity;

import android.app.AlertDialog;

import android.content.SharedPreferences;

import android.os.Bundle;

import android.os.CountDownTimer;

import android.preference.PreferenceManager;

import android.renderscript.Mesh.Primitive;

import android.view.Menu;

import android.view.MenuItem;

import android.view.MotionEvent;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.View.OnTouchListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ProgressBar;

import android.widget.TextView;publicclassMainActivity extends Activity {

Button buttonconnect1;

AlertDialog AlertDialog21;//定义一个提示框View View1;//定义一个view用来获取咱们自定义的界面Button connectbutton21;//连接服务器Button cancelbutton22;//取消按钮ProgressBar progressBar21;//进度条EditText iPEditText;//IP地址EditText portEditText;//端口号TextView titleEditText;//"连接"String Ipstring="";//记录IP地址intportint=0;//记录端口号boolean ConnectFlage=true;intShowPointSum=0;//显示点的数量,连接中.....(后面的点)Socket socket =null;//定义socketInetAddress ipAddress;

OutputStream outputStream=null;//定义输出流InputStream inputStream=null;//定义输入流privateSharedPreferences sharedPreferences;//存储数据privateSharedPreferences.Editor editor;//存储数据@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setTheme(android.R.style.Theme);//设置主题风格setContentView(R.layout.activity_main);

buttonconnect1= (Button) findViewById(R.id.button11);//获取按钮buttonconnect1.setOnClickListener(buttonconnect1Click);//按钮点击事件buttonconnect1.setOnTouchListener(buttonconnect1Touch);//按钮的触摸事件/**对话框相关**/AlertDialog21=newAlertDialog.Builder (MainActivity.this).create();

View1= View.inflate(MainActivity.this, R.layout.dialog,null);

AlertDialog21.setView(View1);//设置显示内容为自定义的界面connectbutton21 = (Button) View1.findViewById(R.id.button21);//连接服务器按钮cancelbutton22 = (Button) View1.findViewById(R.id.Button22);//取消按钮progressBar21 = (ProgressBar) View1.findViewById(R.id.progressBar21);//进度条progressBar21.setVisibility(-1);//进度条不显示iPEditText = (EditText)View1.findViewById(R.id.editText21);//IP地址portEditText = (EditText)View1.findViewById(R.id.editText22);//端口号titleEditText = (TextView) View1.findViewById(R.id.textView21);//"连接"cancelbutton22.setOnClickListener(cancelbutton22Click);//对话框取消事件connectbutton21.setOnClickListener(connectbutton21Click);//对话框连接按钮点击事件sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);

boolean issave= sharedPreferences.getBoolean("save",false);//得到save文件存的值,得不到会返回falseif(issave)

{

String Ipstring= sharedPreferences.getString("Ipstring","192.168.4.1");//取出ip,不存在返回192.168.4.1String portint = sharedPreferences.getString("portint","8080");//取出端口号,不存在返回8080iPEditText.setText(Ipstring);

portEditText.setText(portint);

}

}/***

* 对话框连接按钮点击事件*/privateOnClickListener connectbutton21Click =newOnClickListener() {

@OverridepublicvoidonClick(View v) {//TODO Auto-generated method stubIpstring = iPEditText.getText().toString().replace("","");

portint= Integer.valueOf(portEditText.getText().toString().replace("",""));

progressBar21.setVisibility(0);//显示进度条tcpClientCountDownTimer.cancel();

tcpClientCountDownTimer.start();

ConnectFlage=true;

ShowPointSum=0;

ConnectSeverThread connectSeverThread=newConnectSeverThread();

connectSeverThread.start();

editor=sharedPreferences.edit();

editor.putString("Ipstring", Ipstring);//记录ipeditor.putString("portint", portEditText.getText().toString());//记录端口号editor.putBoolean("save",true);//写入记录标志editor.commit();

}

};/***

*

* @author 连接服务器任务

**/classConnectSeverThread extends Thread

{publicvoidrun()

{while(ConnectFlage)

{try{

ipAddress=InetAddress.getByName(Ipstring);

socket=newSocket(ipAddress, portint);

ConnectFlage=false;

tcpClientCountDownTimer.cancel();

runOnUiThread(newRunnable()

{publicvoidrun()

{

progressBar21.setVisibility(-1);//关闭滚动条AlertDialog21.cancel();//关闭提示框}

});

inputStream= socket.getInputStream();//获取输入流}catch(IOException e)

{//TODO Auto-generated catch blocke.printStackTrace();

}

}

}

}/***

* 对话框取消按钮事件*/privateOnClickListener cancelbutton22Click =newOnClickListener() {

@OverridepublicvoidonClick(View v) {//TODO Auto-generated method stubConnectFlage =false;//取消连接任务tcpClientCountDownTimer.cancel();//结束定时器progressBar21.setVisibility(-1);//关闭滚动条AlertDialog21.cancel();//关闭对话框}

};/***

* 延时3s的定时器*/privateCountDownTimer tcpClientCountDownTimer =newCountDownTimer(3000,200) {

@OverridepublicvoidonTick(longmillisUntilFinished) {//每隔200ms进入if(ConnectFlage)

{    ShowPointSum++;switch(ShowPointSum%9)

{case0:titleEditText.setText("连接中");break;case1:titleEditText.setText("连接中.");break;case2:titleEditText.setText("连接中..");break;case3:titleEditText.setText("连接中...");break;case4:titleEditText.setText("连接中....");break;case5:titleEditText.setText("连接中.....");break;case6:titleEditText.setText("连接中......");break;case7:titleEditText.setText("连接中.......");break;case8:titleEditText.setText("连接中........");break;default:break;

}

}

}

@OverridepublicvoidonFinish() {//3s后进入(没有取消定时器的情况下)if(ConnectFlage)

{    ConnectFlage=false;

progressBar21.setVisibility(-1);//关闭滚动条titleEditText.setText("连接服务器失败!!");

}

tcpClientCountDownTimer.cancel();

}

};/***

* 主按钮点击事件*/privateOnClickListener buttonconnect1Click =newOnClickListener() {

@OverridepublicvoidonClick(View v) {//TODO Auto-generated method stubtitleEditText.setText("连接");

AlertDialog21.show();

}

};/***

* 主界面连接服务器按钮背景改变*/privateOnTouchListener buttonconnect1Touch =newOnTouchListener() {

@Overridepublicboolean onTouch(View v, MotionEventevent) {//TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN) {

buttonconnect1.setBackgroundResource(R.drawable.buttondown);

}if(event.getAction()==MotionEvent.ACTION_UP) {

buttonconnect1.setBackgroundResource(R.drawable.butonup);

}returnfalse;

}

};

}

现在做控制界面

   

android:background="@android:color/background_dark"android:id="@+id/textView31"android:layout_width="wrap_content"android:layout_height="2dp"android:layout_alignParentLeft="true"android:layout_alignParentRight="true"android:layout_centerVertical="true"/>       

android:background="@android:color/transparent"android:layout_marginBottom="20dp"android:id="@+id/imageButton31"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/textView31"android:layout_alignParentLeft="true"android:layout_marginLeft="35dp"android:src="@drawable/qianjin"/>       

android:background="@android:color/transparent"android:layout_marginTop="20dp"android:id="@+id/imageButton32"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/imageButton31"android:layout_below="@+id/textView31"android:src="@drawable/houtui"/>       

android:background="@android:color/transparent"android:id="@+id/imageButton33"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:layout_marginRight="10dp"android:src="@drawable/youzhuan"/>       

android:background="@android:color/transparent"android:id="@+id/imageButton34"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerVertical="true"android:layout_marginRight="30dp"android:layout_toLeftOf="@+id/imageButton33"android:src="@drawable/zuozhuan"/>       

android:id="@+id/checkBox31"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_centerVertical="true"android:text="开重感"/>

这个ProgressBar默认是,,水平的

要改成竖直的其实就是自己写一个外观和变化的文件,然后调用,,,,,就像咱们自定义按钮样式一样

然后呢在里面加上

                                   

android:startColor="#ff9d9e9d"android:centerColor="#ff5a5d5a"android:centerY="0.75"android:endColor="#ff747674"android:angle="270"/>                           

android:clipOrientation="vertical"android:gravity="bottom">                                                         

android:startColor="#ffffd300"android:centerColor="#ffffb600"android:centerX="0.75"android:endColor="#ffffcb00"android:angle="90"/>                       

要问我你怎么知道这样写..百度的,然后从源码里面copy 过来的.........亲们也可以百度哈,,,,,现在我也只是个入门的,只不过善于去用别人的东西,,不过后期我肯定会去学习这些东西代表的含义

现在的控制的界面

布局文件

   

android:background="@android:color/transparent"android:id="@+id/textView31"android:layout_width="wrap_content"android:layout_height="2dp"android:layout_alignParentLeft="true"android:layout_alignParentRight="true"android:layout_centerVertical="true"/>       

android:background="@android:color/transparent"android:layout_marginBottom="20dp"android:id="@+id/imageButton31"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/textView31"android:layout_alignParentLeft="true"android:layout_marginLeft="35dp"android:src="@drawable/qianjin"/>       

android:background="@android:color/transparent"android:layout_marginTop="20dp"android:id="@+id/imageButton32"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/imageButton31"android:layout_below="@+id/textView31"android:src="@drawable/houtui"/>       

android:background="@android:color/transparent"android:id="@+id/imageButton33"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:layout_marginRight="10dp"android:src="@drawable/youzhuan"/>       

android:background="@android:color/transparent"android:id="@+id/imageButton34"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerVertical="true"android:layout_marginRight="30dp"android:layout_toLeftOf="@+id/imageButton33"android:src="@drawable/zuozhuan"/>       

android:id="@+id/checkBox31"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_centerVertical="true"android:text="开重感"/>   

android:id="@+id/textView32"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentTop="true"android:layout_centerHorizontal="true"android:text="速度"/>   

android:id="@+id/progressBar31"style="?android:attr/progressBarStyleHorizontal"android:progressDrawable="@drawable/progress_vertical"android:layout_width="20dip"android:layout_height="wrap_content"android:layout_above="@+id/checkBox31"android:layout_below="@+id/textView32"android:layout_centerHorizontal="true"/>   

android:id="@+id/textView33"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignTop="@+id/progressBar31"android:layout_toRightOf="@+id/progressBar31"android:text="高"/>   

android:id="@+id/textView34"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/checkBox31"android:layout_alignLeft="@+id/textView33"android:text="低"/>   

android:id="@+id/textView35"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/textView33"android:layout_marginTop="20dp"android:layout_toRightOf="@+id/progressBar31"android:text="50"/>

现在连接上以后跳转到这个界面

设置在连接上以后,跳转

对了要在

现在可以试一试

整体还好啦.....只不过中间的那个textview太明显了.....咱在代码中把他设置成透明的

下面开始做控制的代码,那些一看就懂的咱就稍微一说哈,,,

现在看重力传感器,,还是先看,这个,,因为重力传感器的数据要用这个ProgressBar显示

可以下载进去看一下

先把这个也做上

现在把手机的传感器弄上来

这是一个人介绍的感觉挺好的

http://blog.csdn.net/wll995806658/article/details/53993356

现在的程序

package com.wificardemo;

import android.hardware.Sensor;

import android.hardware.SensorEvent;

import android.hardware.SensorEventListener;

import android.hardware.SensorManager;

import android.os.Bundle;

import android.util.Log;

import android.widget.CheckBox;

import android.widget.CompoundButton;

import android.widget.TextView;

import android.widget.CompoundButton.OnCheckedChangeListener;

import android.widget.ProgressBar;publicclassControl extends MainActivity {

ProgressBar progressBar31;//进度条CheckBox  checkBox31;//打开重力传感器SensorManager sensorManager;//新建sensor的管理器Sensor sensor;//传感器floatX_lateral;//X方向角度intSpeed=0;//速度TextView textView35;//显示速度值@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setTheme(android.R.style.Theme);//设置主题风格setContentView(R.layout.control);

progressBar31=(ProgressBar) findViewById(R.id.progressBar31);

progressBar31.setProgress(50);//显示到一半checkBox31=(CheckBox) findViewById(R.id.checkBox31);

checkBox31.setOnCheckedChangeListener(checkBox31Check);

textView35= (TextView) findViewById(R.id.textView35);//速度显示}/***

* 单选框事件*/privateOnCheckedChangeListener checkBox31Check =newOnCheckedChangeListener() {

@OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {//TODO Auto-generated method stubif(isChecked)

{

sensorManager= (SensorManager) getSystemService(SENSOR_SERVICE);//获取手机里面的传感器sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);//选择获取重力传感器//监听函数                        重力传感器对象              工作频率sensorManager.registerListener(mySensorEventListener, sensor,  SensorManager.SENSOR_DELAY_NORMAL);//SENSOR_DELAY_GAME}else{

sensorManager.unregisterListener(mySensorEventListener);//释放传感器}

}

};/**

* 重力传感器监听事件*/SensorEventListener mySensorEventListener=newSensorEventListener() {

@OverridepublicvoidonSensorChanged(SensorEventevent) {//TODO Auto-generated method stubif(event.sensor.getType() ==Sensor.TYPE_ACCELEROMETER)

{X_lateral =event.values[0]+10;//把-10到10的数据变为0-20Speed = (int)((100-(X_lateral*10/2))*2);//变为0-200if(Speed>100) {

Speed=100;

}

textView35.setText(String.valueOf(Speed));//Toast.makeText(controlcar.this, Y_longitudinal+"", 500).show();runOnUiThread(newRunnable() {publicvoidrun()

{

progressBar31.setProgress(Speed);

}

});

}

}

@OverridepublicvoidonAccuracyChanged(Sensor sensor,intaccuracy) {//TODO Auto-generated method stub}

};

}

直接加了一些程序下载到手机旋转手机可以看出效果

对了,,一定要加一个关掉传感器的操作.....因为一旦打开,,您不主动关掉,它就一直运行,,,,,,耗电哈,,耗电,,耗电,,,,

protectedvoidonPause() {

super.onPause();

sensorManager.unregisterListener(mySensorEventListener);

}

package com.wificardemo;

import android.hardware.Sensor;

import android.hardware.SensorEvent;

import android.hardware.SensorEventListener;

import android.hardware.SensorManager;

import android.os.Bundle;

import android.util.Log;

import android.widget.CheckBox;

import android.widget.CompoundButton;

import android.widget.TextView;

import android.widget.CompoundButton.OnCheckedChangeListener;

import android.widget.ProgressBar;

import android.widget.Toast;publicclassControl extends MainActivity {

ProgressBar progressBar31;//进度条CheckBox  checkBox31;//打开重力传感器SensorManager sensorManager;//新建sensor的管理器Sensor sensor;//传感器floatX_lateral;//X方向角度intSpeed=0;//速度TextView textView35;//显示速度值@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setTheme(android.R.style.Theme);//设置主题风格setContentView(R.layout.control);

progressBar31=(ProgressBar) findViewById(R.id.progressBar31);

progressBar31.setProgress(50);//显示到一半checkBox31=(CheckBox) findViewById(R.id.checkBox31);

checkBox31.setOnCheckedChangeListener(checkBox31Check);

textView35= (TextView) findViewById(R.id.textView35);//速度显示}/***

* 单选框事件*/privateOnCheckedChangeListener checkBox31Check =newOnCheckedChangeListener() {

@OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {//TODO Auto-generated method stubif(isChecked)

{

sensorManager= (SensorManager) getSystemService(SENSOR_SERVICE);//获取手机里面的传感器sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);//选择获取重力传感器//监听函数                        重力传感器对象              工作频率sensorManager.registerListener(mySensorEventListener, sensor,  SensorManager.SENSOR_DELAY_NORMAL);//SENSOR_DELAY_GAME}else{

sensorManager.unregisterListener(mySensorEventListener);//释放传感器}

}

};/**

* 重力传感器监听事件*/SensorEventListener mySensorEventListener=newSensorEventListener() {

@OverridepublicvoidonSensorChanged(SensorEventevent) {//TODO Auto-generated method stubif(event.sensor.getType() ==Sensor.TYPE_ACCELEROMETER)

{X_lateral =event.values[0]+10;//把-10到10的数据变为0-20Speed = (int)((100-(X_lateral*10/2))*2);//变为0-200if(Speed>100) {

Speed=100;

}

textView35.setText(String.valueOf(Speed));//Toast.makeText(controlcar.this, Y_longitudinal+"", 500).show();runOnUiThread(newRunnable() {publicvoidrun()

{

progressBar31.setProgress(Speed);

}

});

}else{

sensorManager.unregisterListener(mySensorEventListener);

runOnUiThread(newRunnable() {publicvoidrun()

{

checkBox31.setChecked(false);

Toast.makeText(Control.this,"传感器不存在!!!",500).show();

}

});

}

}

@OverridepublicvoidonAccuracyChanged(Sensor sensor,intaccuracy) {//TODO Auto-generated method stub}

};protectedvoidonPause() {

super.onPause();

sensorManager.unregisterListener(mySensorEventListener);

}

}

现在把按键的事件做上,,,按下咱做成震动一下,,当然也可以自己做成播放声音的

package com.wificardemo;

import android.app.Service;

import android.hardware.Sensor;

import android.hardware.SensorEvent;

import android.hardware.SensorEventListener;

import android.hardware.SensorManager;

import android.os.Bundle;

import android.os.Vibrator;

import android.util.Log;

import android.view.MotionEvent;

import android.view.View;

import android.view.View.OnTouchListener;

import android.widget.CheckBox;

import android.widget.CompoundButton;

import android.widget.ImageButton;

import android.widget.TextView;

import android.widget.CompoundButton.OnCheckedChangeListener;

import android.widget.ProgressBar;

import android.widget.Toast;publicclassControl extends MainActivity {

ProgressBar progressBar31;//进度条CheckBox  checkBox31;//打开重力传感器SensorManager sensorManager;//新建sensor的管理器Sensor sensor;//传感器floatX_lateral;//X方向角度intSpeed=0;//速度TextView textView35;//显示速度值ImageButton imageButton31;//前进ImageButton imageButton32;//后退ImageButton imageButton33;//右转ImageButton imageButton34;//左转boolean forward=false;

boolean back=false;

boolean right=false;

boolean left=false;

Vibrator vibrator;//按钮按下震动@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setTheme(android.R.style.Theme);//设置主题风格setContentView(R.layout.control);

progressBar31=(ProgressBar) findViewById(R.id.progressBar31);

progressBar31.setProgress(50);//显示到一半checkBox31=(CheckBox) findViewById(R.id.checkBox31);

checkBox31.setOnCheckedChangeListener(checkBox31Check);

textView35= (TextView) findViewById(R.id.textView35);//速度显示imageButton31= (ImageButton) findViewById(R.id.imageButton31);//前进imageButton32 = (ImageButton) findViewById(R.id.imageButton32);//后退imageButton33 = (ImageButton) findViewById(R.id.imageButton33);//右转imageButton34 = (ImageButton) findViewById(R.id.imageButton34);//左转imageButton31.setOnTouchListener(imageButton31Touch);//前进imageButton32.setOnTouchListener(imageButton32Touch);//后退imageButton33.setOnTouchListener(imageButton33Touch);//右转imageButton34.setOnTouchListener(imageButton34Touch);//左转vibrator=(Vibrator)getSystemService(Service.VIBRATOR_SERVICE);//震动}/***

* 前进按钮*/privateOnTouchListener imageButton31Touch =newOnTouchListener() {

@Overridepublicboolean onTouch(View v, MotionEventevent) {//TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN) {

forward=true;

back=false;

imageButton31.setImageResource(R.drawable.qianjindown);

vibrator.vibrate(newlong[]{0,20}, -1);//震动}if(event.getAction()==MotionEvent.ACTION_UP) {

forward=false;

imageButton31.setImageResource(R.drawable.qianjin);

}returnfalse;

}

};/***

* 后退按钮*/privateOnTouchListener imageButton32Touch =newOnTouchListener() {

@Overridepublicboolean onTouch(View v, MotionEventevent) {//TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN) {

back=true;

forward=false;

imageButton32.setImageResource(R.drawable.houtuidown);

vibrator.vibrate(newlong[]{0,20}, -1);

}if(event.getAction()==MotionEvent.ACTION_UP) {

back=false;

imageButton32.setImageResource(R.drawable.houtui);

}returnfalse;

}

};/***

* 右转按钮*/privateOnTouchListener imageButton33Touch =newOnTouchListener() {

@Overridepublicboolean onTouch(View v, MotionEventevent) {//TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN) {

right=true;

left=false;

imageButton33.setImageResource(R.drawable.youzhuandown);

vibrator.vibrate(newlong[]{0,20}, -1);

}if(event.getAction()==MotionEvent.ACTION_UP) {

right=false;

imageButton33.setImageResource(R.drawable.youzhuan);

}returnfalse;

}

};/***

* 左转按钮*/privateOnTouchListener imageButton34Touch =newOnTouchListener() {

@Overridepublicboolean onTouch(View v, MotionEventevent) {//TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN) {

left=true;

right=false;

imageButton34.setImageResource(R.drawable.zuozhuandown);

vibrator.vibrate(newlong[]{0,20}, -1);

}if(event.getAction()==MotionEvent.ACTION_UP) {

left=false;

imageButton34.setImageResource(R.drawable.zuozhuan);

}returnfalse;

}

};/***

* 单选框事件*/privateOnCheckedChangeListener checkBox31Check =newOnCheckedChangeListener() {

@OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {//TODO Auto-generated method stubif(isChecked)

{

sensorManager= (SensorManager) getSystemService(SENSOR_SERVICE);//获取手机里面的传感器sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);//选择获取重力传感器//监听函数                        重力传感器对象              工作频率sensorManager.registerListener(mySensorEventListener, sensor,  SensorManager.SENSOR_DELAY_NORMAL);//SENSOR_DELAY_GAME}else{

sensorManager.unregisterListener(mySensorEventListener);//释放传感器}

}

};/**

* 重力传感器监听事件*/SensorEventListener mySensorEventListener=newSensorEventListener() {

@OverridepublicvoidonSensorChanged(SensorEventevent) {//TODO Auto-generated method stubif(event.sensor.getType() ==Sensor.TYPE_ACCELEROMETER)

{

X_lateral=event.values[0]+10;//把-10到10的数据变为0-20Speed = (int)((100-(X_lateral*10/2))*2);//变为0-200if(Speed>100) {

Speed=100;

}

textView35.setText(String.valueOf(Speed));//Toast.makeText(controlcar.this, Y_longitudinal+"", 500).show();runOnUiThread(newRunnable() {publicvoidrun()

{

progressBar31.setProgress(Speed);

}

});

}else{

sensorManager.unregisterListener(mySensorEventListener);

runOnUiThread(newRunnable() {publicvoidrun()

{

checkBox31.setChecked(false);

Toast.makeText(Control.this,"传感器不存在!!!",500).show();

}

});

}

}

@OverridepublicvoidonAccuracyChanged(Sensor sensor,intaccuracy) {//TODO Auto-generated method stub}

};protectedvoidonPause() {

super.onPause();

sensorManager.unregisterListener(mySensorEventListener);

}

}

现在呢建一个发送任务开始发送数据了......

在前一篇的关于8266的设置

规定的协议

看一下现在的代码

package com.wificardemo;

import java.io.IOException;

import java.nio.ByteBuffer;

import android.app.Service;

import android.content.Intent;

import android.hardware.Sensor;

import android.hardware.SensorEvent;

import android.hardware.SensorEventListener;

import android.hardware.SensorManager;

import android.os.Bundle;

import android.os.Vibrator;

import android.util.Log;

import android.view.MotionEvent;

import android.view.View;

import android.view.View.OnTouchListener;

import android.widget.CheckBox;

import android.widget.CompoundButton;

import android.widget.ImageButton;

import android.widget.TextView;

import android.widget.CompoundButton.OnCheckedChangeListener;

import android.widget.ProgressBar;

import android.widget.Toast;publicclassControl extends MainActivity {

ProgressBar progressBar31;//进度条CheckBox  checkBox31;//打开重力传感器SensorManager sensorManager;//新建sensor的管理器Sensor sensor;//传感器floatX_lateral;//X方向角度intSpeed=0;//速度TextView textView35;//显示速度值ImageButton imageButton31;//前进ImageButton imageButton32;//后退ImageButton imageButton33;//右转ImageButton imageButton34;//左转boolean forward=false;

boolean back=false;

boolean right=false;

boolean left=false;

Vibrator vibrator;//按钮按下震动byte[] sendbyte =newbyte[4];//发送的数据缓存boolean SendDataFlag =true;//发送数据任务控制SendMsgThread sendMsgThread;//发送数据任务boolean stopcar =false;//执行一次发送停车数据Intent intentmain =newIntent();//界面跳转--主界面@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setTheme(android.R.style.Theme);//设置主题风格setContentView(R.layout.control);

progressBar31=(ProgressBar) findViewById(R.id.progressBar31);

progressBar31.setProgress(50);//显示到一半checkBox31=(CheckBox) findViewById(R.id.checkBox31);

checkBox31.setOnCheckedChangeListener(checkBox31Check);

textView35= (TextView) findViewById(R.id.textView35);//速度显示imageButton31= (ImageButton) findViewById(R.id.imageButton31);//前进imageButton32 = (ImageButton) findViewById(R.id.imageButton32);//后退imageButton33 = (ImageButton) findViewById(R.id.imageButton33);//右转imageButton34 = (ImageButton) findViewById(R.id.imageButton34);//左转imageButton31.setOnTouchListener(imageButton31Touch);//前进imageButton32.setOnTouchListener(imageButton32Touch);//后退imageButton33.setOnTouchListener(imageButton33Touch);//右转imageButton34.setOnTouchListener(imageButton34Touch);//左转vibrator=(Vibrator)getSystemService(Service.VIBRATOR_SERVICE);//震动sendMsgThread=newSendMsgThread();

sendMsgThread.start();//启动发送数据任务}/***

* 前进按钮*/privateOnTouchListener imageButton31Touch =newOnTouchListener() {

@Overridepublicboolean onTouch(View v, MotionEventevent) {//TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN) {

forward=true;

back=false;

imageButton31.setImageResource(R.drawable.qianjindown);//改变背景vibrator.vibrate(newlong[]{0,20}, -1);//震动}if(event.getAction()==MotionEvent.ACTION_UP) {

forward=false;

imageButton31.setImageResource(R.drawable.qianjin);//改变背景}returnfalse;

}

};/***

* 后退按钮*/privateOnTouchListener imageButton32Touch =newOnTouchListener() {

@Overridepublicboolean onTouch(View v, MotionEventevent) {//TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN) {

back=true;

forward=false;

imageButton32.setImageResource(R.drawable.houtuidown);//改变背景vibrator.vibrate(newlong[]{0,20}, -1);//震动}if(event.getAction()==MotionEvent.ACTION_UP) {

back=false;

imageButton32.setImageResource(R.drawable.houtui);//改变背景}returnfalse;

}

};/***

* 右转按钮*/privateOnTouchListener imageButton33Touch =newOnTouchListener() {

@Overridepublicboolean onTouch(View v, MotionEventevent) {//TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN) {

right=true;

left=false;

imageButton33.setImageResource(R.drawable.youzhuandown);//改变背景vibrator.vibrate(newlong[]{0,20}, -1);//震动}if(event.getAction()==MotionEvent.ACTION_UP) {

right=false;

imageButton33.setImageResource(R.drawable.youzhuan);//改变背景}returnfalse;

}

};/***

* 左转按钮*/privateOnTouchListener imageButton34Touch =newOnTouchListener() {

@Overridepublicboolean onTouch(View v, MotionEventevent) {//TODO Auto-generated method stubif(event.getAction()==MotionEvent.ACTION_DOWN) {

left=true;

right=false;

imageButton34.setImageResource(R.drawable.zuozhuandown);//改变背景vibrator.vibrate(newlong[]{0,20}, -1);//震动}if(event.getAction()==MotionEvent.ACTION_UP) {

left=false;

imageButton34.setImageResource(R.drawable.zuozhuan);//改变背景}returnfalse;

}

};/**

*左转大于右转大于后退大于前进

*(单个按钮)谁按下执行谁

**/classSendMsgThread extends Thread

{publicvoidrun()

{while(SendDataFlag)

{

sendbyte[0] = (byte)0xaa;

sendbyte[1] = (byte)0x55;if(!checkBox31.isChecked()) {//没有打开重力传感器速度默认50sendbyte[3] =50;

}if(forward) {//前进sendbyte[2] = (byte)0x01;

}if(back) {//后退sendbyte[2] = (byte)0x02;

}if(right) {//右转sendbyte[2] = (byte)0x03;

}if(left) {//左转sendbyte[2] = (byte)0x04;

}if(forward || back || right || left)//有按下的按钮{

stopcar=true;//有过按钮操作netSend(sendbyte);

}else//没有按下的按钮发送一次停车指令{if(stopcar)//有过按钮操作{

stopcar=false;

sendbyte[2] = (byte)0x05;

sendbyte[3] = (byte)0x00;

netSend(sendbyte);

}

}try{

Thread.sleep(100);//延时100ms}catch(InterruptedException e) {//TODO Auto-generated catch blocke.printStackTrace();

}

}

}

}/**

* 发送数据

* @param byt*/privatevoidnetSend(byte[] byt)

{intcrc =0;

ByteBuffer Crcbyte= ByteBuffer.allocate(4);//创建4个字节的  ByteBufferbyte[] sendbyte =newbyte[byt.length +2];//后面加2是原来存储CRCfor(inti =0; i < byt.length; i++)//copy数据{

sendbyte[i]=byt[i];

}

crc= crc16_modbus(byt, byt.length);//计算CRCCrcbyte.putInt(crc);//把int转成byte--默认是转成4个字节的,,所以上面定义了4个字节的↑↑sendbyte[sendbyte.length-2] = Crcbyte.get(3);//低位在前----java看来默认的大端模式存储数据sendbyte[sendbyte.length -1] = Crcbyte.get(2);//高位在后try{

outputStream=socket.getOutputStream();

outputStream.write(sendbyte);

}catch(IOException e)

{

SendDataFlag=false;

socket=null;

runOnUiThread(newRunnable() {

@Overridepublicvoidrun() {//TODO Auto-generated method stubToast.makeText(Control.this,"与服务器断开连接,请重新连接",500).show();

}

});

intentmain.setClass(Control.this, MainActivity.class);//有错误跳转到主界面重新连接Control.this.startActivity(intentmain);

}

}/***

* 单选框事件*/privateOnCheckedChangeListener checkBox31Check =newOnCheckedChangeListener() {

@OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {//TODO Auto-generated method stubif(isChecked)

{

sensorManager= (SensorManager) getSystemService(SENSOR_SERVICE);//获取手机里面的传感器sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);//选择获取重力传感器//监听函数                        重力传感器对象              工作频率sensorManager.registerListener(mySensorEventListener, sensor,  SensorManager.SENSOR_DELAY_NORMAL);//SENSOR_DELAY_GAME}else{

sensorManager.unregisterListener(mySensorEventListener);//释放传感器}

}

};/**

* 重力传感器监听事件*/SensorEventListener mySensorEventListener=newSensorEventListener() {

@OverridepublicvoidonSensorChanged(SensorEventevent) {//TODO Auto-generated method stubif(event.sensor.getType() ==Sensor.TYPE_ACCELEROMETER)

{

X_lateral=event.values[0]+10;//把-10到10的数据变为0-20Speed = (int)((100-(X_lateral*10/2))*2);//变为0-200if(Speed>100) {

Speed=100;

}

sendbyte[3] = (byte)Speed;//得到速度变量textView35.setText(String.valueOf(Speed));//Toast.makeText(controlcar.this, Y_longitudinal+"", 500).show();runOnUiThread(newRunnable() {publicvoidrun()

{

progressBar31.setProgress(Speed);

}

});

}else{

sensorManager.unregisterListener(mySensorEventListener);

runOnUiThread(newRunnable() {publicvoidrun()

{

checkBox31.setChecked(false);

Toast.makeText(Control.this,"传感器不存在!!!",500).show();

}

});

}

}

@OverridepublicvoidonAccuracyChanged(Sensor sensor,intaccuracy) {//TODO Auto-generated method stub}

};/**

* CRC检验值

* @param modbusdata

* @param length

* @return CRC检验值*/protectedintcrc16_modbus(byte[] modbusdata,intlength)

{inti=0, j=0;intcrc =0;try{for(i =0; i < length; i++)

{

crc^= (modbusdata[i]&(0xff));//注意这里要&0xfffor(j =0; j <8; j++)

{if((crc &0x01) ==1)

{

crc= (crc >>1) ;

crc= crc ^0xa001;

}else{

crc>>=1;

}

}

}

}catch(Exception e)

{

}returncrc;

}/**

* CRC校验正确标志

* @param modbusdata

* @param length

* @return 0-failed 1-success*/protectedintcrc16_flage(byte[] modbusdata,intlength)

{intReceive_CRC =0, calculation =0;//接收到的CRC,计算的CRCReceive_CRC=crc16_modbus(modbusdata, length);

calculation= modbusdata[length +1];

calculation<<=8;

calculation+=modbusdata[length];if(calculation !=Receive_CRC)

{return0;

}return1;

}protectedvoidonPause() {

SendDataFlag = false;        sensorManager.unregisterListener(mySensorEventListener);

super.onPause();

}

}

代码越来越多,,有什么办法把以前的折叠

整体就是程序一开始启动发送数据任务,,,

发送数据的方式可以轻松的看出来

关于为什么需要&0xff,可以看这篇文章

http://bbs.csdn.net/topics/260061974

现在呢!!把MainActivity的

改为静态的,,,,

因为换到了其它界面,,,所以在其它界面这个socket是null

静态的可以避免啦..............

当然也可以在跳转界面的时候想办法把socket传过去.............

现在可以终于可以控制车了.....................

算了不演示了,,一口气写完

现在在控制界面实现这个功能,按一次提示返回主界面,,2S内连续按就返回

publicboolean onKeyDown(intkeyCode,KeyEventevent)

{if(keyCode ==KeyEvent.KEYCODE_BACK&&event.getAction() ==KeyEvent.ACTION_DOWN) {//判断间隔时间 大于2秒就退出应用if((System.currentTimeMillis() - exitTime) >2000) {

Toast.makeText(getApplicationContext(),"再按一次返回连接界面",

Toast.LENGTH_SHORT).show();

exitTime=System.currentTimeMillis();

}else{

intentmain.setClass(Control.this, MainActivity.class);//跳转到控制界面Control.this.startActivity(intentmain);

}returnfalse;

}returnfalse;

}

主界面呢按返回键

/***

* 手机返回按钮*/publicboolean onKeyDown(intkeyCode,KeyEventevent)

{if(keyCode == KeyEvent.KEYCODE_BACK &&event.getAction() ==KeyEvent.ACTION_DOWN) {//判断间隔时间 大于2秒就退出应用if((System.currentTimeMillis() - exitTime) >2000)

{

Toast.makeText(getApplicationContext(),"再按一次退出程序",Toast.LENGTH_SHORT).show();

exitTime=System.currentTimeMillis();

}else{try{socket.close();}catch(IOException e) {e.printStackTrace();}try{outputStream.close();}catch(IOException e) {e.printStackTrace();}try{inputStream.close();}catch(IOException e) {e.printStackTrace();}

MainActivity.this.finish();

}returnfalse;

}returnfalse;

}protectedvoidonPause() {

super.onPause();

MainActivity.this.finish();

}

虽然实现了,但是自己还是有疑问,,,这里就不说了,,等着再整理成一篇文章(关于Activity加载问题)

现在呢还需要加一个功能,,判断Socket是否断开,,,控制界面跳转到连接界面后,,点击主界面的主按钮如果判断socket还在连接着,就直接跳转到控制界面,,,咱们是利用的接收数据判断

自己看的这篇文章

http://blog.csdn.net/HelloMyPeople/article/details/51906460?locationNum=11&fps=1

修改一下程序,........说一下自己遇到的问题以及解决方法(关于Activity加载问题,还有一下细节问题)---上面的程序有bug.....每次都是重新点击连接.....因为

否则可以看一看打印的日志

所以导致了每回连接的时候,即使一开始连接上了还是会重新连接

改成这样

好了......关于现在的错误搜索了一下没得到想要的结果,,有人说是Android本身的.....

为了不出现意外我在所有的sensorManager.unregisterListener(mySensorEventListener);都加了先判断sensorManager是不是null

还有下面

下面说一下activity的launchMode     加载模式

大家有没有遇到过,多个界面的时候退出的时候不是返回到以前的界面就是又重新加载现在的界面

现在说一下问题所在

界面加载的时候默认

就咱现在的而言不设置加载方式

先是A打开B,,,因为B是standard模式,,,所以现在是    AB

然后从B加载A因为A是standard模式 所以现在是  ABA,,,,,,

假设没有错误令ABA前头的AB销毁的话,,那么按下手机的返回键 会依次显示B,,然后 A,然后才退出程序

我现在想

先是A打开B,,,因为B是standard模式,,,所以现在是    AB

然后从B加载A因为A是standard模式 所以现在是  ABA

我想在A按返回键的时候退出程序那么可以选择一种方案

把A设置成

如果A是这种模式咱在走一走

A打开B           AB

B打开A           因为B在A前头所以把B给销毁了,这种方式不会创建新的实例,,,所以只剩下A

然后按下返回键----注销A  程序会退出

网上呢!还有一些方式,,比如存储所有的Activity,退出的时候把所有的Activity销毁,,然后退出,,,,,

感觉还是知道为什么会这样自己才会有更好的理解,,才会想出自己的办法

感谢这位博主..写出这篇这么好的文章

http://blog.163.com/w_z_w_z_w/blog/static/21995700720139131355207/

所以呢

自己还修改了一些地方

/***

* 手机返回按钮*/publicboolean onKeyDown(intkeyCode,KeyEventevent)

{if(keyCode == KeyEvent.KEYCODE_BACK &&event.getAction() ==KeyEvent.ACTION_DOWN) {//判断间隔时间 大于2秒就退出应用if((System.currentTimeMillis() - exitTime) >2000)

{

Toast.makeText(getApplicationContext(),"再按一次退出程序",Toast.LENGTH_SHORT).show();

exitTime=System.currentTimeMillis();

}else{try{if(socket!=null)

{

socket.close();

}

}catch(IOException e)

{

e.printStackTrace();

}try{if(outputStream!=null)

{

outputStream.close();

}

}catch(IOException e)

{

e.printStackTrace();

}try{if(inputStream!=null)

{

inputStream.close();

}

}catch(IOException e)

{

e.printStackTrace();

}

MainActivity.this.finish();

}returnfalse;

}returnfalse;

}

都判断了一下是不是空,,,其实对于退出而言感觉没有必要判断了,,,,,反正都需要注销,,但是呢我想让打印的日志把错误降到自己感觉

可以的程度..............

整个启动退出..............

好了源码

链接:http://pan.baidu.com/s/1nuFGdlv密码:rq9g

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,458评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,454评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,171评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,062评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,440评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,661评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,906评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,609评论 0 200
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,379评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,600评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,085评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,409评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,072评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,088评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,860评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,704评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,608评论 2 270

推荐阅读更多精彩内容