|
BluetoothCar.java
- package com.BluetoothCar.liuviking;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.UnsupportedEncodingException;
- import java.util.UUID;
- import android.app.Activity;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.bluetooth.BluetoothSocket;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.graphics.Color;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.util.Log;
- import android.view.KeyEvent;
- import android.view.Menu;
- import android.view.MenuInflater;
- import android.view.MenuItem;
- import android.view.MotionEvent;
- import android.view.View;
- import android.view.WindowManager;
- import android.view.View.OnTouchListener;
- import android.view.Window;
- import android.view.View.OnClickListener;
- import android.view.inputmethod.EditorInfo;
- import android.widget.ArrayAdapter;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.ImageButton;
- import android.widget.ListView;
- import android.widget.TextView;
- import android.widget.Toast;
- /**
- * 这是主要的活动显示当前聊天会话。
- */
- public class BluetoothCar extends Activity {
- // Debugging
- private static final String TAG = "BluetoothChat";
- private static final boolean D = true;
- //从 BluetoothChatService 处理程序发送的消息类型
- // Message types sent from the BluetoothChatService Handler
- public static final int MESSAGE_STATE_CHANGE = 1;
- public static final int MESSAGE_READ = 2;
- public static final int MESSAGE_WRITE = 3;
- public static final int MESSAGE_DEVICE_NAME = 4;
- public static final int MESSAGE_TOAST = 5;
- private String DEFULT_PRES = "0";
- public static final String PREFS_NAME = "BluetoothCar";
- public static final String DEVICE_NAME = "device_name";
- public static final String TOAST = "toast";
- // Intent request codes意向请求代码
- private static final int REQUEST_CONNECT_DEVICE = 1;
- private static final int REQUEST_ENABLE_BT = 2;
- // Layout Views布局视图
- private TextView mTitle;
- private ListView mConversationView;
- private EditText mOutEditText;
- private Button mSendButton;
- private String up,down,left,right,stop;
- private ImageButton mForward,mBack,mLeft,mRight,mStop;
- // 连接的设备名称
- private String mConnectedDeviceName = null;
- // 对话线程数组适配器
- private ArrayAdapter<String> mConversationArrayAdapter;
- // 本地蓝牙适配器
- private BluetoothAdapter mBluetoothAdapter = null;
- //发送服务
- private BluetoothChatService mChatService = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- if(D) Log.e(TAG, "+++ ON CREATE +++");
-
- // Set up the window layout设置窗口布局
- requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
- setContentView(R.layout.main1);
- getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
- this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
- WindowManager.LayoutParams.FLAG_FULLSCREEN);
-
- // 设置自定义标题
- mTitle = (TextView) findViewById(R.id.title_left_text);
- mTitle.setText(R.string.app_name);
- mTitle = (TextView) findViewById(R.id.title_right_text);
- onShow();//读取配置文件
- // 获取本地蓝牙适配器
- mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- // 如果空适配器那么蓝牙不受支持
- if (mBluetoothAdapter == null) {
- Toast.makeText(this, "蓝牙设备不可用!", Toast.LENGTH_LONG).show();
- finish();
- return;
- }
- Intent serverIntent = new Intent(this, DeviceListActivity.class);
- startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
- }
- @Override
- public void onStart() {
- super.onStart();
- if(D) Log.e(TAG, "++ ON START ++");
- // 如果BT未启动,请求启用它。
- // 然后将调用期间 onActivityResult
- if (!mBluetoothAdapter.isEnabled()) {
- Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
- // 否则,设置聊天会话
- } else {
- if (mChatService == null)
- setupControl();
- }
- }
- @Override
- public synchronized void onResume() {
- super.onResume();
- if(D) Log.e(TAG, "+ ON RESUME +");
- if (mChatService != null) {
-
- //只有当开始是STATE_NONE,表明还没真正连接
- if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
- // 启动蓝牙设备服务
- mChatService.start();
- }
- }
- }
- private void setupControl() {
- // 初始化一个侦听程序,单击事件的发送按钮
-
- mForward = (ImageButton) findViewById(R.id.Forward);
- mForward.setOnTouchListener(new OnTouchListener() {
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- // TODO Auto-generated method stub
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
-
- sendMessage(up);
- break;
- case MotionEvent.ACTION_UP:
-
- sendMessage(stop);
- break;
- }
- return false;
- }
-
- });
- mBack = (ImageButton) findViewById(R.id.Back);
- mBack.setOnTouchListener(new OnTouchListener() {
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- // TODO Auto-generated method stub
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- sendMessage(down);
- break;
- case MotionEvent.ACTION_UP:
- sendMessage(stop);
- break;
- }
- return false;
- }
-
- });
- mLeft = (ImageButton) findViewById(R.id.Left);
- mLeft.setOnTouchListener(new OnTouchListener() {
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- // TODO Auto-generated method stub
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- sendMessage(left);
- break;
- case MotionEvent.ACTION_UP:
- sendMessage(stop);
- break;
- }
- return false;
- }
-
- });
- mRight = (ImageButton) findViewById(R.id.Right);
- mRight.setOnTouchListener(new OnTouchListener() {
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- // TODO Auto-generated method stub
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- sendMessage(right);
- break;
- case MotionEvent.ACTION_UP:
- sendMessage(stop);
- break;
- }
- return false;
- }
-
- });
- mStop = (ImageButton) findViewById(R.id.Stop);
- mStop.setOnTouchListener(new OnTouchListener() {
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- // TODO Auto-generated method stub
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- sendMessage(stop);
- break;
- case MotionEvent.ACTION_UP:
- sendMessage(stop);
- break;
- }
- return false;
- }
-
- });
-
- //初始化执行蓝牙连接 BluetoothChatService
- mChatService = new BluetoothChatService(this, mHandler);
- }
- @Override
- public synchronized void onPause() {
- super.onPause();
- if(D) Log.e(TAG, "- ON PAUSE -");
- }
- @Override
- public void onStop() {
- super.onStop();
- if(D) Log.e(TAG, "-- ON STOP --");
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- //停止蓝牙聊天服务
- if (mChatService != null) mChatService.stop();
- if(D) Log.e(TAG, "--- ON DESTROY ---");
- }
- private void ensureDiscoverable() {
- if(D) Log.d(TAG, "ensure discoverable");
- if (mBluetoothAdapter.getScanMode() !=
- BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
- Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
- discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
- startActivity(discoverableIntent);
- }
- }
- /**
- * 发送数据
- * @param message A string of text to send.
- */
- private void sendMessage(String message) {
- // 检查是否真正连上
- if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
- Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
- return;
- }
- // 检查有什么实际发送
- if (message.length() > 0) {
- // 获取消息字节并写入 BluetoothChatService
- byte[] send = message.getBytes();
- mChatService.write(send);
- }
- }
- //是从该 BluetoothChatService 重新获取信息显示在UI的处理程序
- private final Handler mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MESSAGE_STATE_CHANGE:
- if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
- switch (msg.arg1) {
- case BluetoothChatService.STATE_CONNECTED:
- mTitle.setText(R.string.title_connected_to);
- mTitle.append(mConnectedDeviceName);
- //mConversationArrayAdapter.clear();
- break;
- case BluetoothChatService.STATE_CONNECTING:
- mTitle.setText(R.string.title_connecting);
- break;
- case BluetoothChatService.STATE_LISTEN:
- case BluetoothChatService.STATE_NONE:
- mTitle.setText(R.string.title_not_connected);
- BluetoothAdapter cwjBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
-
- if(cwjBluetoothAdapter == null){
- Toast.makeText(
- BluetoothCar.this,"本机没有找到蓝牙硬件或驱动存在问题",
- Toast.LENGTH_SHORT)
- .show();
- }
- if (!cwjBluetoothAdapter.isEnabled()) {
- Intent TurnOnBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivityForResult(TurnOnBtIntent, REQUEST_ENABLE_BT);
- }
- break;
- }
- break;
- case MESSAGE_WRITE:
-
- break;
- case MESSAGE_READ:
-
- break;
- case MESSAGE_DEVICE_NAME:
- //保存连接设备名称
- mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
- Toast.makeText(getApplicationContext(), "已成功连接到: "
- + mConnectedDeviceName+"可以开始操纵小车了!", Toast.LENGTH_SHORT).show();
- break;
- case MESSAGE_TOAST:
- Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
- Toast.LENGTH_SHORT).show();
- break;
- }
- }
- };
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- if(D) Log.d(TAG, "onActivityResult " + resultCode);
-
- switch (requestCode) {
- case REQUEST_CONNECT_DEVICE:
- if (resultCode == Activity.RESULT_OK) {
- // 获取设备地址
- String address = data.getExtras()
- .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
- Toast.makeText(this, "该设备MAC地址为--->"+address, Toast.LENGTH_SHORT).show();
- //获取设备对象
- BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
- UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
- try {
- device.createRfcommSocketToServiceRecord(uuid);
- } catch (IOException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- // Attempt to connect to the device
- mChatService.connect(device);
- }
- break;
- case REQUEST_ENABLE_BT:
- //当启用蓝牙的请求返回时
- if (resultCode == Activity.RESULT_OK) {
- // 蓝牙现已启用,因此成立聊天会话
- setupControl();
- } else {
- // 用户没有启用蓝牙或发生错误
- Log.d(TAG, "BT not enabled");
- Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
- finish();
- }
- }
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- MenuInflater inflater = getMenuInflater();
- inflater.inflate(R.menu.option_menu, menu);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.scan:
- // 若要查看设备 DeviceListActivity 启动并扫描
- Intent serverIntent = new Intent(this, DeviceListActivity.class);
- startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
- return true;
- case R.id.discoverable:
- // 确保此设备是可被其他人发现
- ensureDiscoverable();
- return true;
- case R.id.config:
- Intent intent = new Intent();
- intent.setClass(BluetoothCar.this,ControlConfig.class);
- BluetoothCar.this.startActivity(intent);
- BluetoothCar.this.finish();
- }
- return false;
- }
- private void onShow() {
- // TODO Auto-generated method stub
- SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
- up=settings.getString("Up", DEFULT_PRES);
- down=settings.getString("Down", DEFULT_PRES);
- left=settings.getString("Left", DEFULT_PRES);
- right=settings.getString("Right", DEFULT_PRES);
- stop=settings.getString("Stop", DEFULT_PRES);
- }
- }
复制代码 BluetoothChatService.java
- package com.BluetoothCar.liuviking;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.UUID;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.bluetooth.BluetoothServerSocket;
- import android.bluetooth.BluetoothSocket;
- import android.content.Context;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.util.Log;
- public class BluetoothChatService {
- // Debugging
- private static final String TAG = "BluetoothCarService";
- private static final boolean D = true;
- // Name for the SDP record when creating server socket
- private static final String NAME = "BluetoothCar";
- // Unique UUID for this application
- private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
- // Member fields
- private final BluetoothAdapter mAdapter;
- private final Handler mHandler;
- private AcceptThread mAcceptThread;
- private ConnectThread mConnectThread;
- private ConnectedThread mConnectedThread;
- private int mState;
- // Constants that indicate the current connection state
- public static final int STATE_NONE = 0; // we're doing nothing
- public static final int STATE_LISTEN = 1; // now listening for incoming connections
- public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
- public static final int STATE_CONNECTED = 3; // now connected to a remote device
- /**
- * Constructor. Prepares a new BluetoothChat session.
- * @param context The UI Activity Context
- * @param handler A Handler to send messages back to the UI Activity
- */
- public BluetoothChatService(Context context, Handler handler) {
- mAdapter = BluetoothAdapter.getDefaultAdapter();
- mState = STATE_NONE;
- mHandler = handler;
- }
- /**
- * Set the current state of the chat connection
- * @param state An integer defining the current connection state
- */
- private synchronized void setState(int state) {
- if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
- mState = state;
- // Give the new state to the Handler so the UI Activity can update
- mHandler.obtainMessage(BluetoothCar.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
- }
- /**
- * Return the current connection state. */
- public synchronized int getState() {
- return mState;
- }
- /**
- * Start the chat service. Specifically start AcceptThread to begin a
- * session in listening (server) mode. Called by the Activity onResume() */
- public synchronized void start() {
- if (D) Log.d(TAG, "start");
- // 取消所有线程意图以创建一个连接
- //if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
- // 取消当前线程来运行一个连接
- // if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
- /*
- // 通过BluetoothServerSocket,开始一个线程
- if (mAcceptThread == null) {
- mAcceptThread = new AcceptThread();
- mAcceptThread.start();
- }*/
- //if(mConnectThread==null)
- // {
- // mConnectThread = new ConnectThread(null);
- // mConnectThread.start();
- // }
- setState(STATE_LISTEN);
- }
- /**
- * Start the ConnectThread to initiate a connection to a remote device.
- * @param device The BluetoothDevice to connect
- */
- public synchronized void connect(BluetoothDevice device) {
- if (D) Log.d(TAG, "connect to: " + device);
- // Cancel any thread attempting to make a connection
- if (mState == STATE_CONNECTING) {
- if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
- }
- // Cancel any thread currently running a connection
- if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
- // Start the thread to connect with the given device
- mConnectThread = new ConnectThread(device);
- mConnectThread.start();
- setState(STATE_CONNECTING);
- }
- /**
- * 开始一个ConnectedThread,开始管理蓝牙连接
- * @param socket The BluetoothSocket on which the connection was made
- * @param device The BluetoothDevice that has been connected
- */
- public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
- if (D) Log.d(TAG, "connected");
- // 取消已完成连接的线程
- if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
- // Cancel any thread currently running a connection
- if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
- // Cancel the accept thread because we only want to connect to one device
- if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
- // 开启连接到服务器线程
- mConnectedThread = new ConnectedThread(socket);
- mConnectedThread.start();
- // 把MAC地址发回 UI Activity
- Message msg = mHandler.obtainMessage(BluetoothCar.MESSAGE_DEVICE_NAME);
- Bundle bundle = new Bundle();
- bundle.putString(BluetoothCar.DEVICE_NAME, device.getName());
- msg.setData(bundle);
- mHandler.sendMessage(msg);
- setState(STATE_CONNECTED);
- }
- /**
- * Stop all threads
- */
- public synchronized void stop() {
- if (D) Log.d(TAG, "stop");
- if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
- if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
- if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
- setState(STATE_NONE);
- }
- /**
- * Write to the ConnectedThread in an unsynchronized manner
- * @param out The bytes to write
- * @see ConnectedThread#write(byte[])
- */
- public void write(byte[] out) {
- // Create temporary object
- ConnectedThread r;
- // Synchronize a copy of the ConnectedThread
- synchronized (this) {
- if (mState != STATE_CONNECTED) return;
- r = mConnectedThread;
- }
- // Perform the write unsynchronized
- r.write(out);
- }
- /**
- * 连接失败时在UI上显示.
- */
- private void connectionFailed() {
- setState(STATE_LISTEN);
- // 失败信息发回Activity
- Message msg = mHandler.obtainMessage(BluetoothCar.MESSAGE_TOAST);
- Bundle bundle = new Bundle();
- bundle.putString(BluetoothCar.TOAST, "无法连接到设备,请确认下位机蓝牙功能是否正常");
- msg.setData(bundle);
- mHandler.sendMessage(msg);
- }
- /**
- * 丢失连接时在UI上显示.
- */
- private void connectionLost() {
- setState(STATE_LISTEN);
- // 失败信息发回Activity
- Message msg = mHandler.obtainMessage(BluetoothCar.MESSAGE_TOAST);
- Bundle bundle = new Bundle();
- bundle.putString(BluetoothCar.TOAST, "与目标设备连接丢失");
- msg.setData(bundle);
- mHandler.sendMessage(msg);
- }
- /**
- * This thread runs while listening for incoming connections. It behaves
- * like a server-side client. It runs until a connection is accepted
- * (or until cancelled).
- */
- private class AcceptThread extends Thread {
- // The local server socket
- private final BluetoothServerSocket mmServerSocket;
- public AcceptThread() {
- BluetoothServerSocket tmp = null;
- // Create a new listening server socket
- try {
- tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
- } catch (IOException e) {
- Log.e(TAG, "listen() failed", e);
- }
- mmServerSocket = tmp;
- }
- public void run() {
- if (D) Log.d(TAG, "BEGIN mAcceptThread" + this);
- setName("AcceptThread");
- BluetoothSocket socket = null;
- // Listen to the server socket if we're not connected
- while (mState != STATE_CONNECTED) {
- try {
- // This is a blocking call and will only return on a
- // successful connection or an exception
- socket=mmServerSocket.accept();
- } catch (IOException e) {
- Log.e(TAG, "accept() failed", e);
- break;
- }
- // 如果连接已经接受
- if (socket != null) {
- synchronized (BluetoothChatService.this) {
- switch (mState) {
- case STATE_LISTEN:
- case STATE_CONNECTING:
- // Situation normal. Start the connected thread.
- connected(socket, socket.getRemoteDevice());
- break;
- case STATE_NONE:
- case STATE_CONNECTED:
- // 如果没有准备好或者无连接,则终止Socket
- try {
- socket.close();
- } catch (IOException e) {
- Log.e(TAG, "Could not close unwanted socket", e);
- }
- break;
- }
- }
- }
- }
- if (D) Log.i(TAG, "END mAcceptThread");
- }
- public void cancel() {
- if (D) Log.d(TAG, "cancel " + this);
- try {
- mmServerSocket.close();
- } catch (IOException e) {
- Log.e(TAG, "close() of server failed", e);
- }
- }
- }
- /**
- * This thread runs while attempting to make an outgoing connection
- * with a device. It runs straight through; the connection either
- * succeeds or fails.
- */
- private class ConnectThread extends Thread {
- private final BluetoothSocket mmSocket;
- private final BluetoothDevice mmDevice;
- public ConnectThread(BluetoothDevice device) {
- mmDevice = device;
- BluetoothSocket tmp = null;
- //通过蓝牙设备从蓝牙连接中获取一个socket
- try {
- tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
- } catch (IOException e) {
- Log.e(TAG, "create() failed", e);
- }
- mmSocket = tmp;
- }
- public void run() {
- Log.i(TAG, "BEGIN mConnectThread");
- setName("连接线程");
- // 当关闭连接后,设备可见性设为不可见
- mAdapter.cancelDiscovery();
- // Make a connection to the BluetoothSocket
- try {
- // This is a blocking call and will only return on a
- // successful connection or an exception
- mmSocket.connect();
- } catch (IOException e) {
- connectionFailed();
- // 关闭Socket
- try {
- mmSocket.close();
- } catch (IOException e2) {
- Log.e(TAG, "unable to close() socket during connection failure", e2);
- }
- // Start the service over to restart listening mode
- BluetoothChatService.this.start();
- return;
- }
- // Reset the ConnectThread because we're done
- synchronized (BluetoothChatService.this) {
- mConnectThread = null;
- }
- // Start the connected thread
- connected(mmSocket, mmDevice);
- }
- public void cancel() {
- try {
- mmSocket.close();
- } catch (IOException e) {
- Log.e(TAG, "close() of connect socket failed", e);
- }
- }
- }
- /**
- * 该线程在取得连接后执行
- * It handles all incoming and outgoing transmissions.
- */
- private class ConnectedThread extends Thread {
- private final BluetoothSocket mmSocket;
- private final InputStream mmInStream;
- private final OutputStream mmOutStream;
- public ConnectedThread(BluetoothSocket socket) {
- Log.d(TAG, "create ConnectedThread");
- mmSocket = socket;
- InputStream tmpIn = null;
- OutputStream tmpOut = null;
- // Get the BluetoothSocket input and output streams
- try {
- tmpIn = socket.getInputStream();
- tmpOut = socket.getOutputStream();
- } catch (IOException e) {
- Log.e(TAG, "temp sockets not created", e);
- }
- mmInStream = tmpIn;
- mmOutStream = tmpOut;
- }
- public void run() {
- Log.i(TAG, "BEGIN mConnectedThread");
- byte[] buffer = new byte[1024];
- int bytes;
- //保持监听
- while (true) {
- try {
- // 从InputStream读取
- bytes = mmInStream.read(buffer);
- // Send the obtained bytes to the UI Activity
- mHandler.obtainMessage(BluetoothCar.MESSAGE_READ, bytes, -1, buffer)
- .sendToTarget();
- } catch (IOException e) {
- Log.e(TAG, "disconnected", e);
- connectionLost();
- break;
- }
- }
- }
- /**
- * Write to the connected OutStream.
- * @param buffer The bytes to write
- */
- public void write(byte[] buffer) {
- try {
- mmOutStream.write(buffer);
- // 把发送的内容在UI上显示
- mHandler.obtainMessage(BluetoothCar.MESSAGE_WRITE, -1, -1, buffer)
- .sendToTarget();
- } catch (IOException e) {
- Log.e(TAG, "Exception during write", e);
- }
- }
- public void cancel() {
- try {
- mmSocket.close();
- } catch (IOException e) {
- Log.e(TAG, "close() of connect socket failed", e);
- }
- }
- }
- }
复制代码 ControlConfig.java
- package com.BluetoothCar.liuviking;
- import android.app.Activity;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.os.Bundle;
- import android.text.TextUtils;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
- public class ControlConfig extends Activity{
- private Button MbuttonOK,MbuttonCancle;
- private EditText MUp,MDown,MLeft,MRight,MStop;
- private String DEFULT_PRES = "0";
- public static final String PREFS_NAME = "BluetoothCar";
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.configforcontrol);
- MbuttonOK=(Button) findViewById(R.id.btnControlOK);
- MbuttonCancle=(Button) findViewById(R.id.btnControlCancel);
- MUp=(EditText) findViewById(R.id.editUp);
- MDown=(EditText) findViewById(R.id.editDown);
- MLeft=(EditText) findViewById(R.id.editLeft);
- MRight=(EditText) findViewById(R.id.editRight);
- MStop=(EditText) findViewById(R.id.editStop);
- onShow();//读取预先的配置
- MbuttonOK.setOnClickListener(new Button.OnClickListener(){
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- onSave();
- Toast.makeText(ControlConfig.this,String.valueOf("控制命令储存成功!"),Toast.LENGTH_SHORT).show();
- Intent intent = new Intent();
- intent.setClass(ControlConfig.this,BluetoothCar.class);
- ControlConfig.this.startActivity(intent);
- ControlConfig.this.finish();
- }
- });
- MbuttonCancle.setOnClickListener(new Button.OnClickListener(){
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- Intent intent = new Intent();
- intent.setClass(ControlConfig.this,BluetoothCar.class);
- ControlConfig.this.startActivity(intent);
- ControlConfig.this.finish();
- }
- });
- }
- private void onSave() {
- // TODO Auto-generated method stub
- if (TextUtils.isEmpty(MUp.getText().toString())) {
- setPreferences("Up",DEFULT_PRES);
- } else {
- String mPreferences = MUp.getText().toString();
- Log.v("a",mPreferences);
- setPreferences("Up",mPreferences);
- }
- if (TextUtils.isEmpty(MDown.getText().toString())) {
- setPreferences("Down",DEFULT_PRES);
- } else {
- String mPreferences = MDown.getText().toString();
- Log.v("b",mPreferences);
- setPreferences("Down",mPreferences);
- }
- if (TextUtils.isEmpty(MLeft.getText().toString())) {
- setPreferences("Left",DEFULT_PRES);
- } else {
- String mPreferences = MLeft.getText().toString();
- Log.v("c",mPreferences);
- setPreferences("Left",mPreferences);
- }
- if (TextUtils.isEmpty(MRight.getText().toString())) {
- setPreferences("Right",DEFULT_PRES);
- } else {
- String mPreferences = MRight.getText().toString();
- Log.v("c",mPreferences);
- setPreferences("Right",mPreferences);
- }
- if (TextUtils.isEmpty(MStop.getText().toString())) {
- setPreferences("Stop",DEFULT_PRES);
- } else {
- String mPreferences = MStop.getText().toString();
- Log.v("4",mPreferences);
- setPreferences("Stop",mPreferences);
- }
- }
- private void setPreferences(String Key,String mPreferences){
- // set preference
- SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
- SharedPreferences.Editor editor = settings.edit();
- editor.putString(Key, mPreferences);
- editor.commit();
- }
- private void onShow() {
- // TODO Auto-generated method stub
- SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
- String mPreferences = settings.getString("Up", DEFULT_PRES);
- //Toast.makeText(Config.this,String.valueOf(mPreferences),Toast.LENGTH_SHORT).show();
- MUp.setText(mPreferences);
- mPreferences = settings.getString("Down", DEFULT_PRES);
- // Toast.makeText(Config.this,String.valueOf(mPreferences),Toast.LENGTH_SHORT).show();
- MDown.setText(mPreferences);
- mPreferences = settings.getString("Left", DEFULT_PRES);
- MLeft.setText(mPreferences);
- mPreferences = settings.getString("Right", DEFULT_PRES);
- MRight.setText(mPreferences);
- mPreferences = settings.getString("Stop", DEFULT_PRES);
- MStop.setText(mPreferences);
- }
- }
复制代码 DeviceListActivity.java
- package com.BluetoothCar.liuviking;
- import java.util.Set;
- import android.app.Activity;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.Window;
- import android.view.View.OnClickListener;
- import android.widget.AdapterView;
- import android.widget.ArrayAdapter;
- import android.widget.Button;
- import android.widget.ListView;
- import android.widget.TextView;
- import android.widget.AdapterView.OnItemClickListener;
- /**
- * 此活动将作为一个对话框出现。 它列出了配对的所有设备和
- * 在区域中的后发现中检测到的设备。 当选择一个设备
- * 通过在的用户设备的 MAC 地址发送回父
- * Activity in the result Intent.。
- */
- public class DeviceListActivity extends Activity {
- // Debugging
- private static final String TAG = "DeviceListActivity";
- private static final boolean D = true;
- // Return Intent extra
- public static String EXTRA_DEVICE_ADDRESS = "device_address";
- // Member fields
- private BluetoothAdapter mBtAdapter;
- private ArrayAdapter<String> mPairedDevicesArrayAdapter;
- private ArrayAdapter<String> mNewDevicesArrayAdapter;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // Setup the window
- requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
- setContentView(R.layout.device_list);
- // Set result CANCELED incase the user backs out
- setResult(Activity.RESULT_CANCELED);
- // Initialize the button to perform device discovery
- Button scanButton = (Button) findViewById(R.id.button_scan);
- scanButton.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- doDiscovery();
- v.setVisibility(View.GONE);
- }
- });
- // 一个Adapter是已配对的,一个是未配对的
- mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
- mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
- // 把已配对设备放到ListView
- ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
- pairedListView.setAdapter(mPairedDevicesArrayAdapter);
- pairedListView.setOnItemClickListener(mDeviceClickListener);
- //把新发现的设备放到 ListView
- ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
- newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
- newDevicesListView.setOnItemClickListener(mDeviceClickListener);
- // Register for broadcasts when a device is discovered
- IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
- this.registerReceiver(mReceiver, filter);
- // Register for broadcasts when discovery has finished
- filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
- this.registerReceiver(mReceiver, filter);
- // Get the local Bluetooth adapter
- mBtAdapter = BluetoothAdapter.getDefaultAdapter();
- // Get a set of currently paired devices
- Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
- // If there are paired devices, add each one to the ArrayAdapter
- if (pairedDevices.size() > 0) {
- findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
- for (BluetoothDevice device : pairedDevices) {
- mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
- }
- } else {
- String noDevices = getResources().getText(R.string.none_paired).toString();
- mPairedDevicesArrayAdapter.add(noDevices);
- }
- }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- // Make sure we're not doing discovery anymore
- if (mBtAdapter != null) {
- mBtAdapter.cancelDiscovery();
- }
- // Unregister broadcast listeners
- this.unregisterReceiver(mReceiver);
- }
- /**
- * Start device discover with the BluetoothAdapter
- */
- private void doDiscovery() {
- if (D) Log.d(TAG, "doDiscovery()");
- // Indicate scanning in the title
- setProgressBarIndeterminateVisibility(true);
- setTitle(R.string.scanning);
- // Turn on sub-title for new devices
- findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
- // If we're already discovering, stop it
- if (mBtAdapter.isDiscovering()) {
- mBtAdapter.cancelDiscovery();
- }
- // Request discover from BluetoothAdapter
- mBtAdapter.startDiscovery();
- }
- // The on-click listener for all devices in the ListViews
- private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
- public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
- // 取消搜索,准备选择设备进行连接
- mBtAdapter.cancelDiscovery();
- // 获取设备的MAC地址
- String info = ((TextView) v).getText().toString();
- String address = info.substring(info.length() - 17);
- // 把MAC address用Intent回传到主Activity
- Intent intent = new Intent();
- intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
- // 结束当前Activity并回传MAC
- setResult(Activity.RESULT_OK, intent);
- finish();
- }
- };
- //BroadcastReceiver监听设备,当设备发现后,重新设置TITLE
- private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- // When discovery finds a device
- if (BluetoothDevice.ACTION_FOUND.equals(action)) {
- // Get the BluetoothDevice object from the Intent
- BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- // If it's already paired, skip it, because it's been listed already
- if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
- mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
- }
- // When discovery is finished, change the Activity title
- } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
- setProgressBarIndeterminateVisibility(false);
- setTitle(R.string.select_device);
- if (mNewDevicesArrayAdapter.getCount() == 0) {
- String noDevices = getResources().getText(R.string.none_found).toString();
- mNewDevicesArrayAdapter.add(noDevices);
- }
- }
- }
- };
- }
复制代码
XML文件
main1.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="@drawable/background"
- >
- <RelativeLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1" >
- <ListView android:id="@+id/in"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:stackFromBottom="true"
- android:transcriptMode="alwaysScroll"
- android:layout_weight="1"
- />
- <TextView android:layout_width="wrap_content"
- android:id="@+id/textView1"
- android:layout_height="wrap_content"
- android:layout_centerHorizontal="true"
- android:textSize="5pt"
- android:text="蓝牙版智能小车控制端 By liuviking"
- >
- </TextView>
- <TextView android:layout_width="wrap_content"
- android:id="@+id/textView2"
- android:layout_height="wrap_content"
- android:layout_centerHorizontal="true"
- android:textSize="6pt"
- android:text="机器人创意工作室www.wifi-robots.com"
- android:layout_below="@+id/textView1"
- >
- </TextView>
- <ImageButton
- android:layout_marginTop="50dip"
- android:layout_centerHorizontal="true"
- android:id="@+id/Forward"
- android:layout_width="35pt"
- android:layout_height="40pt"
- android:scaleType="fitXY"
- android:background="#00000000"
- android:src="@drawable/forward" >
- </ImageButton>
- <ImageButton
- android:layout_below="@+id/Forward"
- android:layout_toLeftOf="@+id/Stop"
- android:id="@+id/Left"
- android:layout_width="40pt"
- android:layout_height="35pt"
- android:background="#00000000"
- android:scaleType="fitXY"
- android:src="@drawable/left" >
- </ImageButton>
- <ImageButton
- android:layout_below="@+id/Forward"
- android:layout_centerHorizontal="true"
- android:id="@+id/Stop"
- android:layout_width="35pt"
- android:layout_height="35pt"
- android:background="#00000000"
- android:scaleType="fitXY"
- android:src="@drawable/stop" >
- </ImageButton>
- <ImageButton
- android:layout_below="@+id/Forward"
- android:layout_toRightOf="@+id/Stop"
- android:id="@+id/Right"
- android:layout_width="40pt"
- android:layout_height="35pt"
- android:background="#00000000"
- android:scaleType="fitXY"
- android:src="@drawable/right" >
- </ImageButton>
- <ImageButton
- android:layout_below="@+id/Stop"
- android:layout_centerHorizontal="true"
- android:id="@+id/Back"
- android:layout_width="35pt"
- android:layout_height="40pt"
- android:background="#00000000"
- android:scaleType="fitXY"
- android:src="@drawable/back" >
- </ImageButton>
- </RelativeLayout>
- </LinearLayout>
复制代码
message.xml
- <?xml version="1.0" encoding="utf-8"?>
- <TextView xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:textSize="18sp"
- android:padding="5dp"
- />
复制代码
device_name.xml
- <?xml version="1.0" encoding="utf-8"?>
- <TextView xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:textSize="18sp"
- android:padding="5dp"
- />
复制代码
device_list.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView android:id="@+id/title_paired_devices"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/title_paired_devices"
- android:visibility="gone"
- android:background="#666"
- android:textColor="#fff"
- android:paddingLeft="5dp"
- />
- <ListView android:id="@+id/paired_devices"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:stackFromBottom="true"
- android:layout_weight="1"
- />
- <TextView android:id="@+id/title_new_devices"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/title_other_devices"
- android:visibility="gone"
- android:background="#666"
- android:textColor="#fff"
- android:paddingLeft="5dp"
- />
- <ListView android:id="@+id/new_devices"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:stackFromBottom="true"
- android:layout_weight="2"
- />
- <Button android:id="@+id/button_scan"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/button_scan"
- />
- </LinearLayout>
复制代码
custom_title.xml
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:gravity="center_vertical"
- >
- <TextView android:id="@+id/title_left_text"
- android:layout_alignParentLeft="true"
- android:ellipsize="end"
- android:singleLine="true"
- style="?android:attr/windowTitleStyle"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_weight="1"
- />
- <TextView android:id="@+id/title_right_text"
- android:layout_alignParentRight="true"
- android:ellipsize="end"
- android:singleLine="true"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:textColor="#fff"
- android:layout_weight="1"
- />
- </RelativeLayout>
复制代码
configforcontrol.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <RelativeLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1" >
- <TextView android:text="上" android:id="@+id/textViewup" android:layout_width="80px" android:layout_height="wrap_content" ></TextView>
- <EditText android:text="" android:id="@+id/editUp" android:layout_width="80px" android:layout_height="wrap_content" android:layout_below="@+id/textViewup"></EditText>
- <TextView android:text="下" android:id="@+id/textViewdown" android:layout_width="80px" android:layout_height="wrap_content" android:layout_toRightOf="@+id/textViewup"></TextView>
- <EditText android:text="" android:id="@+id/editDown" android:layout_width="80px" android:layout_height="wrap_content" android:layout_toRightOf="@+id/editUp" android:layout_below="@+id/textViewdown"></EditText>
- <TextView android:text="左" android:id="@+id/textViewleft" android:layout_width="80px" android:layout_height="wrap_content" android:layout_below="@+id/editUp" ></TextView>
- <EditText android:text="" android:id="@+id/editLeft" android:layout_width="80px" android:layout_height="wrap_content" android:layout_below="@+id/textViewleft"></EditText>
- <TextView android:text="右" android:id="@+id/textViewright" android:layout_width="80px" android:layout_height="wrap_content" android:layout_below="@+id/editDown" android:layout_toRightOf="@+id/textViewleft"></TextView>
- <EditText android:text="" android:id="@+id/editRight" android:layout_width="80px" android:layout_height="wrap_content" android:layout_below="@+id/textViewright" android:layout_toRightOf="@+id/editLeft"></EditText>
- <TextView android:text="停" android:id="@+id/textViewstop" android:layout_width="80px" android:layout_height="wrap_content" android:layout_below="@+id/editRight"></TextView>
- <EditText android:text="" android:id="@+id/editStop" android:layout_width="80px" android:layout_height="wrap_content" android:layout_below="@+id/textViewstop"></EditText>
- <Button android:text="保存" android:id="@+id/btnControlOK" android:layout_width="40pt" android:layout_height="wrap_content" android:layout_below="@+id/editStop"></Button>
- <Button android:text="取消" android:id="@+id/btnControlCancel" android:layout_width="40pt" android:layout_height="wrap_content" android:layout_toRightOf="@+id/btnControlOK" android:layout_below="@+id/editStop"></Button>
- </RelativeLayout>
- </LinearLayout>
复制代码
menu文件夹中,新建菜单xml文件
option_menu.xml
- <?xml version="1.0" encoding="utf-8"?>
- <menu xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:id="@+id/config"
- android:icon="@android:drawable/ic_menu_preferences"
- android:title="@string/config" />
- <item android:id="@+id/scan"
- android:icon="@android:drawable/ic_menu_search"
- android:title="@string/connect" />
- <item android:id="@+id/discoverable"
- android:icon="@android:drawable/ic_menu_mylocation"
- android:title="@string/discoverable" />
- </menu>
复制代码
values文件夹中,新建字符资源文件string.xml
string.xml
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="app_name">智能小车控制蓝牙版V2.0 BY liuviking</string>
- <!-- BluetoothChat -->
- <string name="send">发送</string>
- <string name="not_connected">您没有连接到设备,请按菜单键进入设备搜索并连接设备。</string>
- <string name="bt_not_enabled_leaving">蓝牙未被启用.程序退出.</string>
- <string name="title_connecting">正在连接...</string>
- <string name="title_connected_to">已连接: </string>
- <string name="title_not_connected">没有连接</string>
- <!-- DeviceListActivity -->
- <string name="scanning">扫描设备中...</string>
- <string name="select_device">选择一个设备连接</string>
- <string name="none_paired">没有设备已配对</string>
- <string name="none_found">没有找到设备</string>
- <string name="title_paired_devices">已配对设备</string>
- <string name="title_other_devices">其他可用的设备</string>
- <string name="button_scan">扫描设备</string>
- <!-- Options Menu -->
- <string name="connect">连接设备</string>
- <string name="discoverable">使可发现</string>
- <string name="config">指令设置</string>
- </resources>
复制代码 程序用到的图片资源合集:
drawable.rar
(120.72 KB, 下载次数: 713)
|
评分
-
查看全部评分
|