android蓝牙遥控车

时间:2021-12-16 17:11:27

写了上一篇的,就一不做,二不休的把今天才完成的自制的蓝牙遥控车吧,


咱分两步走第一部分是Android 方面的,第二是硬件Zigbee方面的。

先说Android方面的,


上源代码吧:

一、Android部分


我的代码运行顺序是先是WelcomActivity,过两秒后然后进入MainActivity,在这里配对成功后进入CMDActivity

1.1、布局方面的代码,为了美观把平常写的UI美化了一下。

1.11、activity_welcome.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:screenOrientation="landscape"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@drawable/hengping"
    tools:context="com.example.hejingzhou.bluetoothtoydemo.WelcomeActivity">

</RelativeLayout><span style="color:#660000;">
</span>

对应的java

<span style="color:#660000;">package com.example.hejingzhou.bluetoothtoydemo;

</span>import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;

public class WelcomeActivity extends AppCompatActivity {

    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        handler = new Handler();
        handler.postDelayed(newRun,3000);
    }
    private Runnable newRun = new Runnable() {
        @Override
        public void run() {
            startActivity(new Intent(WelcomeActivity.this,MainActivity.class));
            finish();
        }
    };
}<span style="color:#660000;">
</span>

//***************//**************//**********//**************//*****************//*****************//****************//******************//****************//

1.12、activity_main


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:screenOrientation="landscape"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@drawable/q2"
    tools:context="com.example.hejingzhou.bluetoothtoydemo.MainActivity">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="允许对外可见"
        android:id="@+id/buttonvisual"
        android:textColor="#820041"
        android:background="@drawable/shape"
        android:layout_marginTop="35dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="搜索其他设备"
        android:id="@+id/buttonsearch"
        android:background="@drawable/shape_2"
        android:textColor="#003e3e"
        android:layout_alignTop="@+id/buttonvisual"
        android:layout_toRightOf="@+id/buttonvisual"
        android:layout_toEndOf="@+id/buttonvisual"
        android:layout_marginLeft="49dp"
        android:layout_marginStart="49dp"/>

    <ImageView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:id="@+id/imageViewExit"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginRight="38dp"
        android:layout_marginEnd="38dp"
        android:src="@drawable/exit"
        android:layout_marginBottom="42dp"/>

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/buttonvisual"
        android:layout_toLeftOf="@+id/imageViewExit"
        android:layout_toStartOf="@+id/imageViewExit"/>

</RelativeLayout>
上边这个布局所用到的
@dimen
写到@drawable文件夹内是针对Button的圆角处理的
详情是这样的
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle" >

<!-- 填充的颜色:这里设置背景透明 -->
<solid android:color="@android:color/transparent" />
<!-- 边框的颜色 :不能和窗口背景色一样-->
<stroke
    android:width="3dp"
    android:color="#930093" />
<!-- 设置按钮的四个角为弧形 -->
<!-- android:radius 弧形的半径 -->
<corners android:radius="5dip" />

<!-- padding:Button里面的文字与Button边界的间隔 -->
<padding
    android:bottom="10dp"
    android:left="10dp"
    android:right="10dp"
    android:top="10dp" />
</shape>


对应的java                                                                                                                                                                                                                                                                                                                        
<span style="color:#660000;">package com.example.hejingzhou.bluetoothtoydemo;

</span>import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.*;
import android.os.Process;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private Handler handler;

    private Button ButVisual,ButSearchDevice;
    private ImageView imageExit;
    private ListView listView;

    static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
    private UUID uuid;

    private ArrayAdapter<String> adapterDevices;
    private List<String> listDevices = new ArrayList<String>();

    private BluetoothAdapter bluetoothAdapter;

    public static BluetoothSocket socket = null;
    public static BluetoothSocket bluetoothSocket;
    public static AcceptThread acceptThread;

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

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        uuid = UUID.fromString(SPP_UUID);

        findViewById();
        InitBlueTooth();
        click();
    }

    /**
     * 单击监听
     */
    private void click() {
        ButVisual.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent discoverableIntent = new Intent(
                        BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                discoverableIntent.putExtra(
                        BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
                startActivity(discoverableIntent);
            }
        });
        ButSearchDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
                    Toast.makeText(MainActivity.this, "请您打开蓝牙", Toast.LENGTH_SHORT).show();
                    return;
                }
                //setTitle("本设备蓝牙地址" + bluetoothAdapter.getAddress());
                listDevices.clear();
                bluetoothAdapter.startDiscovery();
            }
        });
        imageExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bluetoothSocket != null)
                    try {
                        bluetoothSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                MainActivity.this.finish();
            }
        });
    }

    private void findViewById() {
        ButVisual = (Button)findViewById(R.id.buttonvisual);
        ButSearchDevice = (Button)findViewById(R.id.buttonsearch);
        imageExit = (ImageView)findViewById(R.id.imageViewExit);
        listView = (ListView)findViewById(R.id.listView);

        adapterDevices = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,listDevices);
        listView.setAdapter(adapterDevices);
        listView.setOnItemClickListener(new ItemClickEvent());
    }

    /**
     * 初始化蓝牙
     */
    private void InitBlueTooth(){


        if(bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON)
        {
            //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
            handler = new Handler()
            {
               public void HanMessage(Message message)
               {
                   switch (message.what)
                   {
                       case  0:
                           acceptThread = new AcceptThread();
                           acceptThread.start();//开启线程的时候出错
                   }
               }
            };
                IntentFilter intentFilter = new IntentFilter();
                intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
                intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
                intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
                intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
                registerReceiver(searchDevices, intentFilter);

        } else if(bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF)
        {
            bluetoothAdapter.enable();
            try {
                Thread.sleep(1000);
            }
          /*  try {
                if(bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON)
                {
                    Toast.makeText(MainActivity.this,"已打开蓝牙",Toast.LENGTH_SHORT).show();
                    //\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
                    handler = new Handler()
                    {
                        public void HanMessage(Message message)
                        {
                            switch (message.what)
                            {
                                case  0:
                                    acceptThread = new AcceptThread();
                                    acceptThread.start();//开启线程的时候出错
                            }
                        }
                    };
                    IntentFilter intentFilter = new IntentFilter();
                    intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
                    intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
                    intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
                    intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
                    registerReceiver(searchDevices, intentFilter);
                }else
                {
                    Toast.makeText(MainActivity.this,"蓝牙打开失败,请手动打开",Toast.LENGTH_SHORT).show();
                    return;
                }
            }*/ catch (Exception e) {
                Toast.makeText(MainActivity.this,"STATE_OFF注册错误",Toast.LENGTH_SHORT).show();

            }
            } /*catch (InterruptedException e) {
                e.printStackTrace();

        }*/
    }

    /**
     * 管理蓝牙连接套接口
     */
    private void manageConnectedSocket()
    {
        bluetoothSocket = socket;
        startActivity(new Intent(MainActivity.this,CMDActivity.class));
    }

    /**
     * BroadcastReceiver基类代码,将收到发送的意图sendBroadcast()。
     */
    private BroadcastReceiver searchDevices = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Bundle bundle = intent.getExtras();
            Object[] objectName = bundle.keySet().toArray();

            //显示详细的消息细节
            for(int i = 0;i<objectName.length;i++)
            {
                String keyName = objectName[i].toString();
                Log.e(keyName,String.valueOf(bundle.get(keyName)));
            }
            //搜索到设备时
            if(BluetoothDevice.ACTION_FOUND.equals(action))
            {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String str = device.getName()+"|"+device.getAddress();
                if(listDevices.indexOf(str) == -1 )
                {
                    listDevices.add(str);
                }
                adapterDevices.notifyDataSetChanged();//每次改变就刷新
            }
        }
    };

    @Override
    protected void onDestroy() {
        this.unregisterReceiver(searchDevices);//取消注册量
        super.onDestroy();
        android.os.Process.killProcess(Process.myPid());
        acceptThread.cancel();
        acceptThread.destroy();
    }

    class ItemClickEvent implements AdapterView.OnItemClickListener
    {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String str = listDevices.get(position);
            String[] values = str.split("\\|");
            String address = values[1];
            Log.e("address",values[1]);

            uuid = UUID.fromString(SPP_UUID);
            Log.e("uuid",uuid.toString());
            BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(address);

            Method method;

            try {
                method = bluetoothDevice.getClass().getMethod("createRfcommSocket",new Class[] {int.class});
                bluetoothSocket = (BluetoothSocket)method.invoke(bluetoothDevice,Integer.valueOf(1));
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            bluetoothAdapter.cancelDiscovery();
            try {
                bluetoothSocket.connect();
                startActivity(new Intent(MainActivity.this,CMDActivity.class));
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    class AcceptThread extends Thread
    {
        private final BluetoothServerSocket serverSocket;

        public AcceptThread()
        {
            BluetoothServerSocket tmp = null;
            try {
                Method listenMethod = bluetoothAdapter.getClass().getMethod("listenUsingRfcommOn",new Class[]{int.class});
                tmp = (BluetoothServerSocket)listenMethod.invoke(bluetoothAdapter,Integer.valueOf(1));
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            serverSocket = tmp;
        }

        public void run()
        {
            while(true)
            {
                try {
                    socket = serverSocket.accept();
                } catch (IOException e) {
                    break;
                }
                if(socket != null)
                {
                    manageConnectedSocket();
                    try {
                        serverSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
            Message message = new Message();
            message.what = 0;
            handler.sendMessage(message);
        }
        //将取消监听套接字,导致线程结束
        public void cancel()
        {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}<span style="color:#660000;">
</span>

//***************//**************//**********//**************//*****************//*****************//****************//******************//****************//

                                                                                                                              1.13、activity_cmd.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@drawable/www"
    tools:context="com.example.hejingzhou.bluetoothtoydemo.CMDActivity">

    <ImageButton
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:id="@+id/imageButtonShang"
        android:background="@drawable/shang"
        android:layout_marginLeft="19dp"
        android:layout_marginStart="19dp"
        android:layout_above="@+id/imageButtonYuan"
        android:layout_toRightOf="@+id/imageButtonZuo"
        android:layout_toEndOf="@+id/imageButtonZuo"
        android:layout_marginBottom="25dp"/>

    <ImageButton
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:id="@+id/imageButtonXia"
        android:background="@drawable/xia"
        android:layout_marginTop="25dp"
        android:layout_below="@+id/imageButtonZuo"
        android:layout_alignLeft="@+id/imageButtonYuan"
        android:layout_alignStart="@+id/imageButtonYuan"/>

    <ImageButton
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:id="@+id/imageButtonZuo"
        android:background="@drawable/zuo"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"/>

    <ImageButton
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:id="@+id/imageButtonYou"
        android:background="@drawable/you"
        android:layout_marginLeft="23dp"
        android:layout_marginStart="23dp"
        android:layout_above="@+id/imageButtonXia"
        android:layout_toRightOf="@+id/imageButtonShang"
        android:layout_toEndOf="@+id/imageButtonShang"/>

    <ImageButton
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:id="@+id/imageButtonYuan"
        android:background="@drawable/yuan"
        android:layout_above="@+id/imageButtonXia"
        android:layout_toLeftOf="@+id/imageButtonYou"
        android:layout_toStartOf="@+id/imageButtonYou"/>

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButtondisconnect"
        android:src="@drawable/duankai"
        android:background="#00000000"
        android:layout_marginRight="107dp"
        android:layout_marginEnd="107dp"
        android:layout_alignBottom="@+id/imageButtonXia"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"/>

    <ImageButton
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/imageButtonLight"
        android:src="@drawable/dengpao"
        android:background="#00000000"
        android:layout_marginRight="30dp"
        android:layout_marginEnd="30dp"
        android:layout_alignTop="@+id/imageButtondisconnect"
        android:layout_toLeftOf="@+id/imageButtondisconnect"
        android:layout_toStartOf="@+id/imageButtondisconnect"/>

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButtonBACK"
        android:background="@drawable/fanhui"
        android:layout_marginRight="32dp"
        android:layout_marginEnd="32dp"
        android:layout_alignBottom="@+id/imageButtonLight"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"/>

</RelativeLayout><span style="color:#660000;">
</span>

对应的JAVA

<span style="color:#660000;">package com.example.hejingzhou.bluetoothtoydemo;

</span>import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

public class CMDActivity extends AppCompatActivity {

    public static boolean isRecording = false;
    private ImageButton IBUp;
    private ImageButton IBDown;
    private ImageButton IBLeft;
    private ImageButton IBRight;
    private ImageButton IBYuan;
    private ImageButton IBLight;
    private ImageButton IBDisconnect;
    private ImageButton IBBack;
    private TextView test;

    private OutputStream outputStream = null;
    private Handler handler;
    private ConnectedThread connectedThread;

    private String encodeType = "UTF-8";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cmd);
        findViewById();
        click();
        connectedThread = new ConnectedThread();
        handler = new MyHandler();
        connectedThread.Start();
    }

    private void click() {

        IBBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CMDActivity.this.finish();
            }
        });

        IBDisconnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    MainActivity.bluetoothSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                connectedThread.Stop();
            }
        });

        IBUp.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                    sendMessage("U0#");
                } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
                    sendMessage("U1#");
                }
                return false;
            }
        });
        IBDown.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                    sendMessage("U0#");
                } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
                    sendMessage("U1");
                }
                return false;
            }
        });
        IBLeft.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                    sendMessage("30");
                } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
                    sendMessage("31");
                }
                return false;
            }
        });
        IBRight.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                    sendMessage("40");
                } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
                    sendMessage("41");
                }
                return false;
            }
        });
        /*IBLight.setOnTouchListener(new View.OnTouchListener() {
            boolean isClick = false;
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                    sendMessage("L0#");
                    isClick = true;

                } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
                    sendMessage("L1#");
                }
                return false;
            }
        });*/
        IBLight.setOnClickListener(new View.OnClickListener() {
            int a = 1 ;
            @Override
            public void onClick(View v) {
                if((a%2==0)==false)
                {

                    sendMessage("L0#");
                }else if((a%2==0)==true)

                {
                    sendMessage("L1#");
                }
                a++;
            }
        });

    }

    public void sendMessage(String strCmd) {
        try {
            outputStream = MainActivity.bluetoothSocket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] msgbuffer = null;
        try {
            msgbuffer = strCmd.getBytes(encodeType);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try {
            outputStream.write(msgbuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onDestroy() {
        try {
            MainActivity.bluetoothSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    private void findViewById() {
        IBUp = (ImageButton) findViewById(R.id.imageButtonShang);
        IBDown = (ImageButton) findViewById(R.id.imageButtonXia);
        IBLeft = (ImageButton) findViewById(R.id.imageButtonZuo);
        IBRight = (ImageButton) findViewById(R.id.imageButtonYou);
        IBYuan = (ImageButton) findViewById(R.id.imageButtonYuan);
        IBLight = (ImageButton) findViewById(R.id.imageButtonLight);
        IBBack = (ImageButton)findViewById(R.id.imageButtonBACK);
        IBDisconnect = (ImageButton) findViewById(R.id.imageButtondisconnect);

    }

    /***
     * 连接线程
     */
    class ConnectedThread extends Thread {

        private InputStream inputStream = null;
        private long wait;
        private Thread thread;

        public ConnectedThread() {
            isRecording = false;
            this.wait = 50;
            thread = new Thread(new ReadRunnable());
        }

        public void Stop() {
            isRecording = false;
        }

        public void Start() {
            isRecording = true;
            State state = thread.getState();
            if (state == State.NEW) {
                thread.start();
            } else thread.resume();
        }

        private class ReadRunnable implements Runnable {

            @Override
            public void run() {
                try {
                    inputStream = MainActivity.bluetoothSocket.getInputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                int length = 20;
                byte[] temp = new byte[length];
                if (inputStream != null) {
                    try {
                        int len = inputStream.read(temp, 0, length - 1);
                        if (len > 0) {
                            byte[] bluetoothBuff = new byte[len];
                            System.arraycopy(temp, 0, bluetoothBuff, 0, bluetoothBuff.length);
                            String readstr = new String(bluetoothBuff, encodeType);
                        }
                        Thread.sleep(wait);
                    } catch (IOException e) {
                        handler.sendEmptyMessage(00);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }

        /**
         * sendMessage
         */
        /*public void sendMessage(String strCmd) {
            try {
                outputStream = MainActivity.bluetoothSocket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] msgbuffer = null;
            try {
                msgbuffer = strCmd.getBytes(encodeType);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            try {
                outputStream.write(msgbuffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
    }

    private class MyHandler extends Handler {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case 00:
                    isRecording = false;
                    break;
                case 01:
                    String info = (String) msg.obj;
                    break;
                default:
                    break;
            }
            super.dispatchMessage(msg);
        }
    }

}<span style="color:#660000;">
</span>


//***************//**************//**********//**************//*****************//*****************//****************//******************//****************//

二、Zigbee程序

<span style="color:#009900;">

</span>#include <ioCC2530.h>
#include <string.h>

#define uint unsigned int
#define uchar unsigned char

//定义控制LED灯的端口
#define LED1 P0_6	
#define R1 P2_0
#define In P1_0




//函数声明
void Delayms(uint xms);		//延时函数
void InitLed(void);		//初始化
void InitUart();              //初始化串口
void Uart_Send_String(char *Data,int len);
void Infrared(void);

char Rxdata[3];
uchar RXTXflag = 1; 
char temp; 
uchar  datanumber = 0;

/****************************
//延时函数
*****************************/
void Delayms(uint xms)   //i=xms 即延时i毫秒 (16M晶振时候大约数,32M需要修改,系统不修改默认使用内部16M)
{
 uint i,j;
 for(i=xms;i>0;i--)
   for(j=587;j>0;j--);
} 

/****************************
//初始化程序
*****************************/
void InitLed(void)
{
	P0DIR |= 0x50; //定义为输出  0100 0000
        P2DIR |= 0x01;
        //P0DIR |= 0x20;
	LED1 = 0;       //LED1、2灯熄灭
        R1 = 1;
          
}


//红外控制初始化**********************
void Infrared(void)
{
  P1DIR &= ~0x01;
  P1SEL |= 0x01;
  In = 0;
}

/**************************************************************** 
   串口初始化函数     
***********************************************************/
void InitUart()
{
    CLKCONCMD &= ~0x40; // 设置系统时钟源为 32MHZ晶振
    while(CLKCONSTA & 0x40);                     // 等待晶振稳定 
    CLKCONCMD &= ~0x47;                          // 设置系统主时钟频率为 32MHZ

    PERCFG = 0x00;        //位置1 P0口 
    P0SEL = 0x3c;        //P0_2,P0_3,P0_4,P0_5用作串口,第二功能 
    P2DIR &= ~0XC0;      //P0 优先作为UART0 ,优先级
 
    U0CSR |= 0x80;       //UART 方式 
    U0GCR |= 11;           //U0GCR与U0BAUD配合     
    U0BAUD |= 216;       // 波特率设为115200 
    UTX0IF = 1;          //UART0 TX 中断标志初始置位1  (收发时候)
    U0CSR |= 0X40;        //允许接收 
    IEN0 |= 0x84;       // 开总中断,接收中断    
}

/**************************************************************** 
串口发送字符串函数    
****************************************************************/ 
void Uart_Send_String(char *Data,int len) 
{
 { 
  int j; 
  for(j=0;j<len;j++) 
  { 
    U0DBUF = *Data++; 
    while(UTX0IF == 0); 
    UTX0IF = 0; 
  } 
 }
}
/***************************
//主函数
***************************/
void main(void)
{
  
  InitLed();		//调用初始化函数 
  InitUart();
  Infrared();//初始化红外
  

  
  while(1)
  {
     if(RXTXflag == 1)     //接收状态 
     { 
        if( temp != 0) 
        { 
           if((temp!='#')&&(datanumber<3)) //'#'被定义为结束字符,最多能接收50个字符           
           Rxdata[datanumber++] = temp; 
           else 
           { 
             RXTXflag = 3;                     //进入发送状态 
           }         
            temp  = 0;
         }
      }
      if(RXTXflag == 3)     //检测接收到的数据
      { 
        
        
       if(Rxdata[0]=='L')
       {
        
         switch(Rxdata[1]-48)//很重要,ASICC码转成数字,判断L后面第一个数 
         {
      case 0:
        {
          LED1=1; //点亮
          break;
        }
      case 1:
        {
          LED1=0;
          break;
        }
       }  
      }
      else if(Rxdata[0]=='U')
      {
        switch(Rxdata[1]-48)
        {
        case 0:
          
          R1 = 0;
          break;
        case 1:
        
          R1 = 1;
          break;
        }
      }
       RXTXflag = 1;         
       datanumber = 0;                     //指针归 0
      }   
  ///***************************  
     if(R1!=0)
     {
       if((In == 1)&&(LED1!=1 ))
  {
    LED1 = 1;
  }else if((In == 1) && (LED1==1))
  {
    LED1 = 0;
  }
     }
  
  ///***************************

    }
 

}

/**************************************************************** 
串口接收一个字符: 一旦有数据从串口传至CC2530, 则进入中断,将接收到的数据赋值给变量temp. 
****************************************************************/ 
#pragma vector = URX0_VECTOR 
  __interrupt void UART0_ISR(void) 
 { 
  URX0IF = 0;    // 清中断标志 
  temp = U0DBUF;                           

 
 


因为硬件不够只做了车的前进,和控制LED小灯。。。。。
看效果:

android蓝牙遥控车
三秒后。。。。
android蓝牙遥控车
配对成功后。。。。
android蓝牙遥控车

我自造的小车。。。。。
android蓝牙遥控车

android蓝牙遥控车


android蓝牙遥控车

android蓝牙遥控车
写的有点乱。给你们源代码  

android端:http://download.csdn.net/detail/csdnhejingzhou/9413347
Zigbee端:http://download.csdn.net/detail/csdnhejingzhou/9413322