用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里面應該叫做倒角,,,,有沒有學機械的看到這篇文章哈...

記得曾經遇到一個人和我正好相反,,我是報的機械專業,自學的電氣,,,,,,而另一個人是報的電氣卻喜歡機械........興趣.........

 

好啦

拖一個按鈕過來,放到中心.....您也可以在布局文件里面自己寫哈......我是怎樣方便怎樣弄,,我用的是相對布局

 

 

保存一下現在看效果

好現在再定義一個按鈕按下時的外表文件

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

 

 

得到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;

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM