先說一下這篇文章裏面的內容:TCP 客戶端, 自定義對話框, 自定義按鈕, ProgressBar豎直顯示, 重力感應傳感器,手機返回鍵新開啓界面的問題(返回上次的界面),數據保存html
軟件的通訊是配合java
http://www.cnblogs.com/yangfengwu/p/7625608.html 用ESP8266+android,製做本身的WIFI小車(ESP8266篇)android
軟件的第一個界面就一個按鈕 點擊按鈕彈出一個自定義的對話框 鏈接的時候 鏈接上git
其實一開始想多加一些功能,,不事後來想了想複雜了反而不利於學習.........我會從一開始作到結束都寫清楚,若是有大神看到哪地方不合理請指教哈,,,,,緩存
好如今開始作APP服務器
一路Next就行...app
您會發現本身的按鈕是圓邊的socket
實際上是本身自定義了一些參數tcp
新建一個文件夾存儲我們自定義的一些東西ide
對了爲何名字是drawable
實際上是官方提供的,,
http://www.android-doc.com/guide/topics/resources/drawable-resource.html#StateList
而後呢各個參數後面都有具體解釋
有些小夥伴一看....英文的............大哥下一個有道翻譯或者別的翻譯軟件翻譯一下...................
能夠本身搜索本身想要的
好像這些外形啦背景什麼的都在
授人予魚,也要授人予漁;
首先定義一下外形
方形
而後呢描一下邊框,,,顯得是一個按鈕
其實能夠官方解釋
而後定義一下按鈕如今顯示的顏色
好如今讓它的四個角變成圓角,,,對於我這個學機械的而言在solidworks裏面應該叫作倒角,,,,有沒有學機械的看到這篇文章哈...
記得曾經遇到一我的和我正好相反,,我是報的機械專業,自學的電氣,,,,,,而另外一我的是報的電氣卻喜歡機械........興趣.........
好啦
拖一個按鈕過來,放到中心.....您也能夠在佈局文件裏面本身寫哈......我是怎樣方便怎樣弄,,我用的是相對佈局
保存一下如今看效果
好如今再定義一個按鈕按下時的外表文件
private OnTouchListener buttonconnect1Touch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction()==MotionEvent.ACTION_DOWN) { buttonconnect1.setBackgroundResource(R.drawable.buttondown); } if (event.getAction()==MotionEvent.ACTION_UP) { buttonconnect1.setBackgroundResource(R.drawable.butonup); } return false; } };
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; public class MainActivity extends Activity { Button buttonconnect1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonconnect1 = (Button) findViewById(R.id.button11);//獲取按鈕 buttonconnect1.setOnTouchListener(buttonconnect1Touch);//按鈕的觸摸事件 } private OnTouchListener buttonconnect1Touch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction()==MotionEvent.ACTION_DOWN) { buttonconnect1.setBackgroundResource(R.drawable.buttondown); } if (event.getAction()==MotionEvent.ACTION_UP) { buttonconnect1.setBackgroundResource(R.drawable.butonup); } return false; } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean 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. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
如今編譯一下運行到手機看一下
我是直接用的本身的手機,,沒有仿真,,如今個人電腦用仿真但是不得了......
平時的狀態 按下後
本身看着改改大小和顯示
我們如今要作的是
其實這個是本身自定義的一個界面
對了設置一下主題風格...
感受這種風格挺好的
圖片能夠在我源碼裏面找,也能夠本身弄本身的
對了,,,,位置還有名字什麼的本身看着修改哈
總體界面呢,,,
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView 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" /> <TextView 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" /> <TextView 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地址:" /> <EditText 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" /> <ImageView 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" /> <TextView 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="端口號:" /> <EditText 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" /> <Button 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="鏈接" /> <Button 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="取消" /> <ProgressBar android:id="@+id/progressBar21" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/textView23" android:layout_centerHorizontal="true" /> </RelativeLayout>
好了如今點擊主界面的按鈕把這個界面當作提示框顯示出來
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; public class MainActivity extends Activity { Button buttonconnect1; AlertDialog AlertDialog21;//定義一個提示框 View View1;//定義一個view用來獲取我們自定義的界面 Button connectbutton21;//鏈接服務器 Button cancelbutton22;//取消按鈕 ProgressBar progressBar21;//進度條 EditText iPEditText;//IP地址 EditText portEditText;//端口號 TextView titleEditText;//"鏈接" @Override protected void onCreate(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 = new AlertDialog.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);//"鏈接" } /*** * 主界面鏈接服務器按鈕 */ private OnTouchListener buttonconnect1Touch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction()==MotionEvent.ACTION_DOWN) { buttonconnect1.setBackgroundResource(R.drawable.buttondown); } if (event.getAction()==MotionEvent.ACTION_UP) { buttonconnect1.setBackgroundResource(R.drawable.butonup); } return false; } }; }
如今呢就缺乏顯示了...
咱們在主按鈕的點擊事件中調用顯示函數
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; public class MainActivity extends Activity { Button buttonconnect1; AlertDialog AlertDialog21;//定義一個提示框 View View1;//定義一個view用來獲取我們自定義的界面 Button connectbutton21;//鏈接服務器 Button cancelbutton22;//取消按鈕 ProgressBar progressBar21;//進度條 EditText iPEditText;//IP地址 EditText portEditText;//端口號 TextView titleEditText;//"鏈接" @Override protected void onCreate(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 = new AlertDialog.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);//"鏈接" } /*** * 主按鈕點擊事件 */ private OnClickListener buttonconnect1Click = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub AlertDialog21.show(); } }; /*** * 主界面鏈接服務器按鈕背景改變 */ private OnTouchListener buttonconnect1Touch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction()==MotionEvent.ACTION_DOWN) { buttonconnect1.setBackgroundResource(R.drawable.buttondown); } if (event.getAction()==MotionEvent.ACTION_UP) { buttonconnect1.setBackgroundResource(R.drawable.butonup); } return false; } }; }
如今安裝到手機上看一下---界面還能夠
作這個簡單的取消事件
鏈接按鈕呢!!我先說一下思路,,,按下鏈接按鈕是啓動一個鏈接任務,而後呢還要啓動一個倒計時器(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; public class MainActivity 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地址 int portint=0;//記錄端口號 boolean ConnectFlage=true; int ShowPointSum=0;//顯示點的數量,鏈接中.....(後面的點) Socket socket = null;//定義socket InetAddress ipAddress; OutputStream outputStream=null;//定義輸出流 InputStream inputStream=null;//定義輸入流 @Override protected void onCreate(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 = new AlertDialog.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);//對話框鏈接按鈕點擊事件 } /*** * 對話框鏈接按鈕點擊事件 */ private OnClickListener connectbutton21Click = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Ipstring = iPEditText.getText().toString().replace(" ", ""); portint = Integer.valueOf(portEditText.getText().toString().replace(" ", "")); progressBar21.setVisibility(0);//顯示進度條 tcpClientCountDownTimer.cancel(); tcpClientCountDownTimer.start(); ConnectFlage = true; ShowPointSum = 0; ConnectSeverThread connectSeverThread = new ConnectSeverThread(); connectSeverThread.start(); } }; /*** * * @author 鏈接服務器任務 * */ class ConnectSeverThread extends Thread { public void run() { while(ConnectFlage) { try { ipAddress = InetAddress.getByName(Ipstring); socket = new Socket(ipAddress, portint); ConnectFlage = false; tcpClientCountDownTimer.cancel(); runOnUiThread(new Runnable() { public void run() { progressBar21.setVisibility(-1);//關閉滾動條 AlertDialog21.cancel();//關閉提示框 } }); inputStream = socket.getInputStream();//獲取輸入流 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /*** * 對話框取消按鈕事件 */ private OnClickListener cancelbutton22Click = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub ConnectFlage = false;//取消鏈接任務 tcpClientCountDownTimer.cancel();//結束定時器 progressBar21.setVisibility(-1);//關閉滾動條 AlertDialog21.cancel();//關閉對話框 } }; /*** * 延時3s的定時器 */ private CountDownTimer tcpClientCountDownTimer = new CountDownTimer(3000,200) { @Override public void onTick(long millisUntilFinished) {//每隔200ms進入 if (ConnectFlage) { ShowPointSum ++; switch (ShowPointSum%9) { case 0:titleEditText.setText("鏈接中");break; case 1:titleEditText.setText("鏈接中.");break; case 2:titleEditText.setText("鏈接中..");break; case 3:titleEditText.setText("鏈接中...");break; case 4:titleEditText.setText("鏈接中....");break; case 5:titleEditText.setText("鏈接中.....");break; case 6:titleEditText.setText("鏈接中......");break; case 7:titleEditText.setText("鏈接中.......");break; case 8:titleEditText.setText("鏈接中........");break; default: break; } } } @Override public void onFinish() {//3s後進入(沒有取消定時器的狀況下) if (ConnectFlage) { ConnectFlage = false; progressBar21.setVisibility(-1);//關閉滾動條 titleEditText.setText("鏈接服務器失敗!!"); } tcpClientCountDownTimer.cancel(); } }; /*** * 主按鈕點擊事件 */ private OnClickListener buttonconnect1Click = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub titleEditText.setText("鏈接"); AlertDialog21.show(); } }; /*** * 主界面鏈接服務器按鈕背景改變 */ private OnTouchListener buttonconnect1Touch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction()==MotionEvent.ACTION_DOWN) { buttonconnect1.setBackgroundResource(R.drawable.buttondown); } if (event.getAction()==MotionEvent.ACTION_UP) { buttonconnect1.setBackgroundResource(R.drawable.butonup); } return false; } }; }
如今加上權限而後鏈接WIFI模塊測試一下哈
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.WAKE_LOCK"/> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/> <uses-permission android:name="android.permission.VIBRATE" />
鏈接模塊的無線
而後會發現
對話框消失了
由於我們本身設置的消失
如今讓它鏈接後打開控制界面
仍是先把IP和端口號的信息作成可以保存的吧
我們就用 SharedPreferences
能夠看一下這篇文章的介紹
http://blog.csdn.net/baidu_31093133/article/details/51476726##1
而後
那麼一開始運行就要檢測是否是記錄了,,若是記錄了就取出來記錄的數據而後顯示在對應的文本框中
總體的代碼
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; public class MainActivity 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地址 int portint=0;//記錄端口號 boolean ConnectFlage=true; int ShowPointSum=0;//顯示點的數量,鏈接中.....(後面的點) Socket socket = null;//定義socket InetAddress ipAddress; OutputStream outputStream=null;//定義輸出流 InputStream inputStream=null;//定義輸入流 private SharedPreferences sharedPreferences;//存儲數據 private SharedPreferences.Editor editor;//存儲數據 @Override protected void onCreate(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 = new AlertDialog.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文件存的值,得不到會返回false if (issave) { String Ipstring = sharedPreferences.getString("Ipstring", "192.168.4.1");//取出ip,不存在返回192.168.4.1 String portint = sharedPreferences.getString("portint", "8080");//取出端口號,不存在返回8080 iPEditText.setText(Ipstring); portEditText.setText(portint); } } /*** * 對話框鏈接按鈕點擊事件 */ private OnClickListener connectbutton21Click = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Ipstring = iPEditText.getText().toString().replace(" ", ""); portint = Integer.valueOf(portEditText.getText().toString().replace(" ", "")); progressBar21.setVisibility(0);//顯示進度條 tcpClientCountDownTimer.cancel(); tcpClientCountDownTimer.start(); ConnectFlage = true; ShowPointSum = 0; ConnectSeverThread connectSeverThread = new ConnectSeverThread(); connectSeverThread.start(); editor = sharedPreferences.edit(); editor.putString("Ipstring", Ipstring);//記錄ip editor.putString("portint", portEditText.getText().toString());//記錄端口號 editor.putBoolean("save", true);//寫入記錄標誌 editor.commit(); } }; /*** * * @author 鏈接服務器任務 * */ class ConnectSeverThread extends Thread { public void run() { while(ConnectFlage) { try { ipAddress = InetAddress.getByName(Ipstring); socket = new Socket(ipAddress, portint); ConnectFlage = false; tcpClientCountDownTimer.cancel(); runOnUiThread(new Runnable() { public void run() { progressBar21.setVisibility(-1);//關閉滾動條 AlertDialog21.cancel();//關閉提示框 } }); inputStream = socket.getInputStream();//獲取輸入流 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /*** * 對話框取消按鈕事件 */ private OnClickListener cancelbutton22Click = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub ConnectFlage = false;//取消鏈接任務 tcpClientCountDownTimer.cancel();//結束定時器 progressBar21.setVisibility(-1);//關閉滾動條 AlertDialog21.cancel();//關閉對話框 } }; /*** * 延時3s的定時器 */ private CountDownTimer tcpClientCountDownTimer = new CountDownTimer(3000,200) { @Override public void onTick(long millisUntilFinished) {//每隔200ms進入 if (ConnectFlage) { ShowPointSum ++; switch (ShowPointSum%9) { case 0:titleEditText.setText("鏈接中");break; case 1:titleEditText.setText("鏈接中.");break; case 2:titleEditText.setText("鏈接中..");break; case 3:titleEditText.setText("鏈接中...");break; case 4:titleEditText.setText("鏈接中....");break; case 5:titleEditText.setText("鏈接中.....");break; case 6:titleEditText.setText("鏈接中......");break; case 7:titleEditText.setText("鏈接中.......");break; case 8:titleEditText.setText("鏈接中........");break; default: break; } } } @Override public void onFinish() {//3s後進入(沒有取消定時器的狀況下) if (ConnectFlage) { ConnectFlage = false; progressBar21.setVisibility(-1);//關閉滾動條 titleEditText.setText("鏈接服務器失敗!!"); } tcpClientCountDownTimer.cancel(); } }; /*** * 主按鈕點擊事件 */ private OnClickListener buttonconnect1Click = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub titleEditText.setText("鏈接"); AlertDialog21.show(); } }; /*** * 主界面鏈接服務器按鈕背景改變 */ private OnTouchListener buttonconnect1Touch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction()==MotionEvent.ACTION_DOWN) { buttonconnect1.setBackgroundResource(R.drawable.buttondown); } if (event.getAction()==MotionEvent.ACTION_UP) { buttonconnect1.setBackgroundResource(R.drawable.butonup); } return false; } }; }
如今作控制界面
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView 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" /> <ImageButton 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" /> <ImageButton 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" /> <ImageButton 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" /> <ImageButton 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" /> <CheckBox android:id="@+id/checkBox31" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="開重感" /> </RelativeLayout>
這個ProgressBar默認是,,水平的
要改爲豎直的其實就是本身寫一個外觀和變化的文件,而後調用,,,,,就像我們自定義按鈕樣式同樣
而後呢在裏面加上
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@android:id/background"> <shape> <corners android:radius="5dip" /> <gradient android:startColor="#ff9d9e9d" android:centerColor="#ff5a5d5a" android:centerY="0.75" android:endColor="#ff747674" android:angle="270" /> </shape> </item> <item android:id="@android:id/progress"> <clip android:clipOrientation="vertical" android:gravity = "bottom" > <shape> <corners android:radius="5dip" /> <gradient android:startColor="#ffffd300" android:centerColor="#ffffb600" android:centerX="0.75" android:endColor="#ffffcb00" android:angle="90" /> </shape> </clip> </item> </layer-list>
要問我你怎麼知道這樣寫..百度的,而後從源碼裏面copy 過來的.........親們也能夠百度哈,,,,,如今我也只是個入門的,只不過善於去用別人的東西,,不事後期我確定會去學習這些東西表明的含義
如今的控制的界面
佈局文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView 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" /> <ImageButton 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" /> <ImageButton 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" /> <ImageButton 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" /> <ImageButton 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" /> <CheckBox android:id="@+id/checkBox31" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="開重感" /> <TextView android:id="@+id/textView32" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:text="速度" /> <ProgressBar 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" /> <TextView 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="高" /> <TextView 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="低" /> <TextView 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" /> </RelativeLayout>
如今鏈接上之後跳轉到這個界面
設置在鏈接上之後,跳轉
對了要在
如今能夠試一試
總體還好啦.....只不過中間的那個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; public class Control extends MainActivity { ProgressBar progressBar31;//進度條 CheckBox checkBox31;//打開重力傳感器 SensorManager sensorManager;//新建sensor的管理器 Sensor sensor;//傳感器 float X_lateral;//X方向角度 int Speed=0;//速度 TextView textView35;//顯示速度值 @Override protected void onCreate(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);//速度顯示 } /*** * 單選框事件 */ private OnCheckedChangeListener checkBox31Check = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (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 = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { // TODO Auto-generated method stub if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { X_lateral = event.values[0]+10; //把-10到10的數據變爲0-20 Speed = (int)((100-(X_lateral*10/2))*2);//變爲0-200 if (Speed>100) { Speed = 100; } textView35.setText(String.valueOf(Speed)); //Toast.makeText(controlcar.this, Y_longitudinal+"", 500).show(); runOnUiThread(new Runnable() { public void run() { progressBar31.setProgress(Speed); } }); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } }; }
直接加了一些程序下載到手機旋轉手機能夠看出效果
對了,,必定要加一個關掉傳感器的操做.....由於一旦打開,,您不主動關掉,它就一直運行,,,,,,耗電哈,,耗電,,耗電,,,,
protected void onPause() { 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; public class Control extends MainActivity { ProgressBar progressBar31;//進度條 CheckBox checkBox31;//打開重力傳感器 SensorManager sensorManager;//新建sensor的管理器 Sensor sensor;//傳感器 float X_lateral;//X方向角度 int Speed=0;//速度 TextView textView35;//顯示速度值 @Override protected void onCreate(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);//速度顯示 } /*** * 單選框事件 */ private OnCheckedChangeListener checkBox31Check = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (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 = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { // TODO Auto-generated method stub if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { X_lateral = event.values[0]+10; //把-10到10的數據變爲0-20 Speed = (int)((100-(X_lateral*10/2))*2);//變爲0-200 if (Speed>100) { Speed = 100; } textView35.setText(String.valueOf(Speed)); //Toast.makeText(controlcar.this, Y_longitudinal+"", 500).show(); runOnUiThread(new Runnable() { public void run() { progressBar31.setProgress(Speed); } }); } else { sensorManager.unregisterListener(mySensorEventListener); runOnUiThread(new Runnable() { public void run() { checkBox31.setChecked(false); Toast.makeText(Control.this, "傳感器不存在!!!", 500).show(); } }); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } }; protected void onPause() { 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; public class Control extends MainActivity { ProgressBar progressBar31;//進度條 CheckBox checkBox31;//打開重力傳感器 SensorManager sensorManager;//新建sensor的管理器 Sensor sensor;//傳感器 float X_lateral;//X方向角度 int Speed=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;//按鈕按下震動 @Override protected void onCreate(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);//震動 } /*** * 前進按鈕 */ private OnTouchListener imageButton31Touch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction()==MotionEvent.ACTION_DOWN) { forward = true; back=false; imageButton31.setImageResource(R.drawable.qianjindown); vibrator.vibrate(new long[]{0,20}, -1);//震動 } if (event.getAction()==MotionEvent.ACTION_UP) { forward = false; imageButton31.setImageResource(R.drawable.qianjin); } return false; } }; /*** * 後退按鈕 */ private OnTouchListener imageButton32Touch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction()==MotionEvent.ACTION_DOWN) { back=true; forward=false; imageButton32.setImageResource(R.drawable.houtuidown); vibrator.vibrate(new long[]{0,20}, -1); } if (event.getAction()==MotionEvent.ACTION_UP) { back=false; imageButton32.setImageResource(R.drawable.houtui); } return false; } }; /*** * 右轉按鈕 */ private OnTouchListener imageButton33Touch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction()==MotionEvent.ACTION_DOWN) { right=true; left=false; imageButton33.setImageResource(R.drawable.youzhuandown); vibrator.vibrate(new long[]{0,20}, -1); } if (event.getAction()==MotionEvent.ACTION_UP) { right=false; imageButton33.setImageResource(R.drawable.youzhuan); } return false; } }; /*** * 左轉按鈕 */ private OnTouchListener imageButton34Touch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction()==MotionEvent.ACTION_DOWN) { left=true; right=false; imageButton34.setImageResource(R.drawable.zuozhuandown); vibrator.vibrate(new long[]{0,20}, -1); } if (event.getAction()==MotionEvent.ACTION_UP) { left=false; imageButton34.setImageResource(R.drawable.zuozhuan); } return false; } }; /*** * 單選框事件 */ private OnCheckedChangeListener checkBox31Check = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (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 = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { // TODO Auto-generated method stub if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { X_lateral = event.values[0]+10; //把-10到10的數據變爲0-20 Speed = (int)((100-(X_lateral*10/2))*2);//變爲0-200 if (Speed>100) { Speed = 100; } textView35.setText(String.valueOf(Speed)); //Toast.makeText(controlcar.this, Y_longitudinal+"", 500).show(); runOnUiThread(new Runnable() { public void run() { progressBar31.setProgress(Speed); } }); } else { sensorManager.unregisterListener(mySensorEventListener); runOnUiThread(new Runnable() { public void run() { checkBox31.setChecked(false); Toast.makeText(Control.this, "傳感器不存在!!!", 500).show(); } }); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } }; protected void onPause() { 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; public class Control extends MainActivity { ProgressBar progressBar31;//進度條 CheckBox checkBox31;//打開重力傳感器 SensorManager sensorManager;//新建sensor的管理器 Sensor sensor;//傳感器 float X_lateral;//X方向角度 int Speed=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 = new byte[4];//發送的數據緩存 boolean SendDataFlag = true;//發送數據任務控制 SendMsgThread sendMsgThread;//發送數據任務 boolean stopcar = false;//執行一次發送停車數據 Intent intentmain = new Intent(); //界面跳轉--主界面 @Override protected void onCreate(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 = new SendMsgThread(); sendMsgThread.start();//啓動發送數據任務 } /*** * 前進按鈕 */ private OnTouchListener imageButton31Touch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction()==MotionEvent.ACTION_DOWN) { forward = true; back=false; imageButton31.setImageResource(R.drawable.qianjindown);//改變背景 vibrator.vibrate(new long[]{0,20}, -1);//震動 } if (event.getAction()==MotionEvent.ACTION_UP) { forward = false; imageButton31.setImageResource(R.drawable.qianjin);//改變背景 } return false; } }; /*** * 後退按鈕 */ private OnTouchListener imageButton32Touch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction()==MotionEvent.ACTION_DOWN) { back=true; forward=false; imageButton32.setImageResource(R.drawable.houtuidown);//改變背景 vibrator.vibrate(new long[]{0,20}, -1); //震動 } if (event.getAction()==MotionEvent.ACTION_UP) { back=false; imageButton32.setImageResource(R.drawable.houtui);//改變背景 } return false; } }; /*** * 右轉按鈕 */ private OnTouchListener imageButton33Touch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction()==MotionEvent.ACTION_DOWN) { right=true; left=false; imageButton33.setImageResource(R.drawable.youzhuandown);//改變背景 vibrator.vibrate(new long[]{0,20}, -1); //震動 } if (event.getAction()==MotionEvent.ACTION_UP) { right=false; imageButton33.setImageResource(R.drawable.youzhuan);//改變背景 } return false; } }; /*** * 左轉按鈕 */ private OnTouchListener imageButton34Touch = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction()==MotionEvent.ACTION_DOWN) { left=true; right=false; imageButton34.setImageResource(R.drawable.zuozhuandown);//改變背景 vibrator.vibrate(new long[]{0,20}, -1); //震動 } if (event.getAction()==MotionEvent.ACTION_UP) { left=false; imageButton34.setImageResource(R.drawable.zuozhuan);//改變背景 } return false; } }; /** *左轉大於右轉大於後退大於前進 *(單個按鈕)誰按下執行誰 * */ class SendMsgThread extends Thread { public void run() { while(SendDataFlag) { sendbyte[0] = (byte)0xaa; sendbyte[1] = (byte)0x55; if (!checkBox31.isChecked()) {//沒有打開重力傳感器速度默認50 sendbyte[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 block e.printStackTrace(); } } } } /** * 發送數據 * @param byt */ private void netSend(byte[] byt) { int crc = 0; ByteBuffer Crcbyte = ByteBuffer.allocate(4);//建立4個字節的 ByteBuffer byte[] sendbyte = new byte[byt.length + 2];//後面加2是原來存儲CRC for (int i = 0; i < byt.length; i++)//copy數據 { sendbyte[i] = byt[i]; } crc = crc16_modbus(byt, byt.length);//計算CRC Crcbyte.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(new Runnable() { @Override public void run() { // TODO Auto-generated method stub Toast.makeText(Control.this, "與服務器斷開鏈接,請從新鏈接", 500).show(); } }); intentmain.setClass(Control.this, MainActivity.class);//有錯誤跳轉到主界面從新鏈接 Control.this.startActivity(intentmain); } } /*** * 單選框事件 */ private OnCheckedChangeListener checkBox31Check = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (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 = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { // TODO Auto-generated method stub if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { X_lateral = event.values[0]+10; //把-10到10的數據變爲0-20 Speed = (int)((100-(X_lateral*10/2))*2);//變爲0-200 if (Speed>100) { Speed = 100; } sendbyte[3] = (byte)Speed;//獲得速度變量 textView35.setText(String.valueOf(Speed)); //Toast.makeText(controlcar.this, Y_longitudinal+"", 500).show(); runOnUiThread(new Runnable() { public void run() { progressBar31.setProgress(Speed); } }); } else { sensorManager.unregisterListener(mySensorEventListener); runOnUiThread(new Runnable() { public void run() { checkBox31.setChecked(false); Toast.makeText(Control.this, "傳感器不存在!!!", 500).show(); } }); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } }; /** * CRC檢驗值 * @param modbusdata * @param length * @return CRC檢驗值 */ protected int crc16_modbus(byte[] modbusdata, int length) { int i=0, j=0; int crc = 0; try { for (i = 0; i < length; i++) { crc ^= (modbusdata[i]&(0xff));//注意這裏要&0xff for (j = 0; j < 8; j++) { if ((crc & 0x01) == 1) { crc = (crc >> 1) ; crc = crc ^ 0xa001; } else { crc >>= 1; } } } } catch (Exception e) { } return crc; } /** * CRC校驗正確標誌 * @param modbusdata * @param length * @return 0-failed 1-success */ protected int crc16_flage(byte[] modbusdata, int length) { int Receive_CRC = 0, calculation = 0;//接收到的CRC,計算的CRC Receive_CRC = crc16_modbus(modbusdata, length); calculation = modbusdata[length + 1]; calculation <<= 8; calculation += modbusdata[length]; if (calculation != Receive_CRC) { return 0; } return 1; } protected void onPause() {
SendDataFlag = false; sensorManager.unregisterListener(mySensorEventListener);
super.onPause();
}
}
代碼愈來愈多,,有什麼辦法把之前的摺疊
總體就是程序一開始啓動發送數據任務,,,
發送數據的方式能夠輕鬆的看出來
關於爲何須要&0xff,能夠看這篇文章
http://bbs.csdn.net/topics/260061974
如今呢!!把MainActivity的
改成靜態的,,,,
由於換到了其它界面,,,因此在其它界面這個socket是null
靜態的能夠避免啦..............
固然也能夠在跳轉界面的時候想辦法把socket傳過去.............
如今能夠終於能夠控制車了.....................
算了不演示了,,一口氣寫完
如今在控制界面實現這個功能,按一次提示返回主界面,,2S內連續按就返回
public boolean onKeyDown(int keyCode,KeyEvent event) { 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); } return false; } return false; }
主界面呢按返回鍵
/*** * 手機返回按鈕 */ public boolean onKeyDown(int keyCode,KeyEvent event) { 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(); } return false; } return false; } protected void onPause() { 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/
因此呢
本身還修改了一些地方
/*** * 手機返回按鈕 */ public boolean onKeyDown(int keyCode,KeyEvent event) { 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(); } return false; } return false; }
都判斷了一下是否是空,,,其實對於退出而言感受沒有必要判斷了,,,,,反正都須要註銷,,可是呢我想讓打印的日誌把錯誤降到本身感受
能夠的程度..............
整個啓動退出..............
好了源碼
連接:http://pan.baidu.com/s/1nuFGdlv 密碼:rq9g