android蓝牙聊天开发(5)简单蓝牙聊天

运行截图:我的设备设置的用户名是:是。可以改的

        

mainActivity:

package com.lmj.bluetoothchat;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;



public class MainActivity extends AppCompatActivity {
    private static final int REQUES_SELECT_BT_CODE = 0x1001;
    // 使能请求码
    private static final int REQUES_BT_ENABLE_CODE = 0x1002;
    private static final String TAG = MainActivity.class.getName();
    private ListView mListView;
    private EditText mET;
    private BluetoothAdapter mBluetoothAdapter;

    private BluetoothDevice mRemoteDevice;

    private ArrayAdapter<String> mAdapter;

    // 聊天内容保存对象
    private ArrayList<String> mChatContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //使用主界面 布局
        setContentView(R.layout.activity_main);

        // UI初始化
        mListView = (ListView) findViewById(R.id.listView1);
        mET = (EditText) findViewById(R.id.editText1);

        mChatContent = new ArrayList<String>();
        // ListView的Adapter
        mAdapter = new ArrayAdapter<String>(this,
                // 项显示布局
                android.R.layout.simple_list_item_1,
                // 显示的数据源
                mChatContent);


        mListView.setAdapter(mAdapter);

        // 打开蓝牙设备
        openBtDevice();
    }

    /**
     * 用户点击发送按钮
     * @param v
     */
    public void onSendClick(View v){
        String msg = mET.getText().toString().trim();
        if(msg.length() <= 0){
            Toast.makeText(this, "消息不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        // 将用户输入的消息添加到ListView中去显示
        mChatContent.add(mBluetoothAdapter.getName() + ":" + msg);
        // 更新ListView显示
        mAdapter.notifyDataSetChanged();
        // 将发送消息任务提交给后台服务
        TaskService.newTask(new Task(mHandler, Task.TASK_SEND_MSG, new Object[]{msg}));
        // 清空输入框
        mET.setText("");
    }

    private boolean openBtDevice(){
        // 获得蓝牙匹配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // 蓝牙设备不被支持
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "Your device is not support Bluetooth!");
            Toast.makeText(this, "该设备没有蓝牙设备", Toast.LENGTH_LONG).show();
            return false;
        }

        // 使能蓝牙设备
        if (!mBluetoothAdapter.isEnabled()) {
            // 隐式Intent
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUES_BT_ENABLE_CODE);
        }else{
            // 如果蓝牙设备已经使能,直接启动后台服务
            startServiceAsServer();
        }
        return true;
    }

    private void startServiceAsServer() {
        // Android异步通信机制Handler,UI线程不能执行耗时操作,应该交给子线程去做,
        // 子线程不允许去更新UI控件,必须要用到Handler机制(AsyncTask)
        TaskService.start(this, mHandler);
        // 向后台服务提交一个任务,作为服务器端监听远程 设备连接
        TaskService.newTask(new Task(mHandler, Task.TASK_START_ACCEPT, null));
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Task.TASK_SEND_MSG:
                    Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case Task.TASK_RECV_MSG:
                    // 获得远程设备发送的消息
                    mChatContent.add(msg.obj.toString());
                    mAdapter.notifyDataSetChanged();
                    break;
                case Task.TASK_GET_REMOTE_STATE:
                    setTitle(msg.obj.toString());
                    break;
                default:
                    break;
            }
        }
    };

    // 当startActivityForResult启动的 画面结束的时候,该方法被回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //
        if(requestCode == REQUES_BT_ENABLE_CODE && resultCode == RESULT_OK){
            // 作为蓝牙服务端启动后台服务
            startServiceAsServer();
        }else if(requestCode == REQUES_SELECT_BT_CODE && resultCode == RESULT_OK){
            mRemoteDevice = data.getParcelableExtra("DEVICE");
            if(mRemoteDevice == null)
                return;
            // 提交连接用户选择的设备对象,自己作为客户端
            TaskService.newTask(new Task(mHandler,Task.TASK_START_CONN_THREAD, new Object[]{mRemoteDevice}));
        }
    }
//重写onCreateOptionsMenu,并为每个item添加一个监听
    //参考文章https://www.cnblogs.com/linfenghp/p/5464016.html
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
            case R.id.change_name:
                AlertDialog.Builder dlg = new AlertDialog.Builder(this);
                final EditText devNameEdit = new EditText(this);
                dlg.setView(devNameEdit);
                dlg.setTitle("请输入用户名");
                dlg.setPositiveButton("设置", new OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if(devNameEdit.getText().toString().length() != 0)
                            // 设置蓝牙设备名
                            mBluetoothAdapter.setName(devNameEdit.getText().toString());
                    }
                });
                dlg.create();
                dlg.show();
                break;
            case R.id.scann_device:
                // 扫描周围蓝牙设备
                startActivityForResult(new Intent(this, SelectDeviceActivity.class), REQUES_SELECT_BT_CODE);
                break;
        }

        return true;
    }

    @Override
    protected void onDestroy() {
        // 停止服务
       TaskService.stop(this);
        super.onDestroy();
    }
}
SelectDeviceActivity:
package com.lmj.bluetoothchat;

import java.util.ArrayList;
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.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;


public class SelectDeviceActivity extends Activity implements OnClickListener, OnItemClickListener {
	private final String TAG = "MainActivity";
	private static final int REQUEST_ENABLE_CODE = 0x1003;

	private BluetoothAdapter mBluetoothAdapter;
	private Button mScanBtn;
	private ListView mDevList;

	private ArrayAdapter<String> adapter;
	private ArrayList<String> mArrayAdapter = new ArrayList<String>();
	private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 请求显示进度条
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

		setContentView(R.layout.bt_list);

		initView();

		// 打开并查找蓝牙设备
		openAndFindBTDevice();

		// 用来接收到设备查找到的广播和扫描完成的广播
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		// 动态注册广播接收器
		// 用来接收扫描到的设备信息
		registerReceiver(mReceiver, filter);
	}

	private void openAndFindBTDevice(){
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
			Log.e(TAG, "Your device is not support Bluetooth!");
			return;
		}

		if (!mBluetoothAdapter.isEnabled()) {
			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, REQUEST_ENABLE_CODE);
		}else{
			findBTDevice();
		}
	}

	private void initView(){
		mDevList = (ListView) findViewById(R.id.scanDevList);

		mDevList.setOnItemClickListener(this);

		mScanBtn = (Button) findViewById(R.id.scanDevBtn);
		mScanBtn.setOnClickListener(this);

		adapter = new ArrayAdapter<String>(
				this,
				android.R.layout.simple_list_item_1,
				mArrayAdapter);

		mDevList.setAdapter(adapter);
	}

	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			// 扫描到新的蓝牙设备
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				// 获得蓝牙设备对象
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				//防止设备对象添加重复
				if(mDeviceList.contains(device)){
					return;
				}
				mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
				System.out.println(device.getName() + "\n" + device.getAddress());
				mDeviceList.add(device);
				adapter.notifyDataSetChanged();
			}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
				// 扫描完成,关闭显示进度条
				setProgressBarIndeterminateVisibility(false);
			}
		}
	};

	@Override
	public void onClick(View v) {
		if(!mBluetoothAdapter.isDiscovering()){
			mBluetoothAdapter.startDiscovery();
			setProgressBarIndeterminateVisibility(true);
		}
	}

	private void findBTDevice(){
		// 用来保存已经配对的蓝牙设备对象
		Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
		if (pairedDevices.size() > 0) {
			for (BluetoothDevice device : pairedDevices) {
				// 将已经配对设备信息添加到ListView中
				mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
				mDeviceList.add(device);
			}
		}

		adapter.notifyDataSetChanged();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == REQUEST_ENABLE_CODE){
			if(resultCode ==  RESULT_OK){
				System.out.println("设备打开成功");
				findBTDevice();
			}else{
				System.out.println("设备打开失败");
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mReceiver);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		String targetDev = mArrayAdapter.get(arg2);
		System.out.println(targetDev);
		Intent data = new Intent();
		data.putExtra("DEVICE", mDeviceList.get(arg2));
		// 当用于点击某项设备时,将该设备对象返回给调用者(MainActivity)
		setResult(RESULT_OK, data);
		this.finish();
	}

}

Task‘:

package com.lmj.bluetoothchat;

import android.os.Handler;

public class Task {
	/**
	 * 请求等待蓝牙连接(作为服务器)
	 */
	public static final int TASK_START_ACCEPT = 1;
	/**
	 * 请求连接远程蓝牙设备(作为客户端)
	 */
	public static final int TASK_START_CONN_THREAD = 2;
	/**
	 * 发送消息任务
	 */
	public static final int TASK_SEND_MSG = 3;
	/**
	 * 获得蓝牙运行状态
	 */
	public static final int TASK_GET_REMOTE_STATE = 4;
	/**
	 * 接收到聊天消息
	 */
	public static final int TASK_RECV_MSG = 5;


	// 任务ID
	private int mTaskID;
	// 任务参数列表
	public Object[] mParams;

	private Handler mH;


	public Task(Handler handler, int taskID, Object[] params){
		this.mH = handler;
		this.mTaskID = taskID;
		this.mParams = params;
	}

	public Handler getHandler(){
		return this.mH;
	}

	public int getTaskID(){
		return mTaskID;
	}
}

TaskService:

package com.lmj.bluetoothchat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.UUID;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class TaskService extends Service {
	private final String TAG = "TaskService";

	private TaskThread mThread;

	private BluetoothAdapter mBluetoothAdapter;
	private AcceptThread mAcceptThread;
	private ConnectThread mConnectThread;

	private boolean isServerMode = true;

	private static Handler mActivityHandler;

	// 任务队列
	private static ArrayList<Task> mTaskList = new ArrayList<Task>();

	/**
	 * 用于被外部组件启动服务
	 *
	 * @param c
	 *            ,上下文对象
	 * @param handler
	 *            ,Activity上的Handler对象,用于更新UI
	 */
	public static void start(Context c, Handler handler) {
		mActivityHandler = handler;
		// 显式启动服务
		Intent intent = new Intent(c, TaskService.class);
		c.startService(intent);
	}

	/**
	 * 关闭服务
	 *
	 * @param c
	 */
	public static void stop(Context c) {
		Intent intent = new Intent(c, TaskService.class);
		c.stopService(intent);
	}

	/**
	 * 提交任务
	 *
	 * @param target
	 *            目标任务
	 */
	public static void newTask(Task target) {
		synchronized (mTaskList) {
			// 将任务添加到任务队列中
			mTaskList.add(target);
		}
	}

	@Override
	public void onCreate() {
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
			Log.e(TAG, "Your device is not support Bluetooth!");
			return;
		}
		// 启动服务线程
		mThread = new TaskThread();
		mThread.start();
		super.onCreate();
	}

	private Handler mServiceHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case Task.TASK_GET_REMOTE_STATE:
					android.os.Message activityMsg = mActivityHandler
							.obtainMessage();
					activityMsg.what = msg.what;
					if (mAcceptThread != null && mAcceptThread.isAlive()) {
						activityMsg.obj = "等待连接...";
					} else if (mCommThread != null && mCommThread.isAlive()) {
						activityMsg.obj = mCommThread.getRemoteName() + "[在线]";
					} else if (mConnectThread != null && mConnectThread.isAlive()) {
						activityMsg.obj = "正在连接:"
								+ mConnectThread.getDevice().getName();
					} else {
						activityMsg.obj = "未知状态";
						// 重新等待连接
						mAcceptThread = new AcceptThread();
						mAcceptThread.start();
						isServerMode = true;
					}

					mActivityHandler.sendMessage(activityMsg);
					break;

				default:
					break;
			}
			super.handleMessage(msg);
		}
	};


	/**
	 * 任务处理线程
	 * @author Micheal
	 *
	 */
	private class TaskThread extends Thread {
		private boolean isRun = true;
		private int mCount = 0;

		/**
		 * 停止 线程
		 */
		public void cancel() {
			isRun = false;
		}

		@Override
		public void run() {
			Task task;
			while (isRun) {
				// 获得第一个任务开始执行
				if (mTaskList.size() > 0) {
					synchronized (mTaskList) {
						task = mTaskList.get(0);
						doTask(task);
					}
				} else {
					try {
						Thread.sleep(200);
						mCount++;
					} catch (InterruptedException e) {
					}
					if (mCount >= 50) {
						mCount = 0;
						android.os.Message handlerMsg = mServiceHandler
								.obtainMessage();
						handlerMsg.what = Task.TASK_GET_REMOTE_STATE;
						mServiceHandler.sendMessage(handlerMsg);
					}
				}
			}
		}

	}

	/**
	 * 任务处理
	 * @param task
	 */
	private void doTask(Task task) {
		switch (task.getTaskID()) {
			case Task.TASK_START_ACCEPT:
				// 作为服务器接收等待客户端线程
				mAcceptThread = new AcceptThread();
				mAcceptThread.start();
				isServerMode = true;
				break;
			case Task.TASK_START_CONN_THREAD:
				if (task.mParams == null || task.mParams.length == 0) {
					break;
				}
				BluetoothDevice remote = (BluetoothDevice) task.mParams[0];
				// 作为客户端去连接远程服务器
				mConnectThread = new ConnectThread(remote);
				mConnectThread.start();
				isServerMode = false;
				break;
			case Task.TASK_SEND_MSG:
				boolean sucess = false;
				if (mCommThread == null || !mCommThread.isAlive()
						|| task.mParams == null || task.mParams.length == 0) {
					Log.e(TAG, "mCommThread or task.mParams null");
				} else {
					sucess = mCommThread.write((String) task.mParams[0]);
				}
				if (!sucess) {
					android.os.Message returnMsg = mActivityHandler.obtainMessage();
					returnMsg.what = Task.TASK_SEND_MSG;
					returnMsg.obj = "消息发送失败";
					mActivityHandler.sendMessage(returnMsg);
				}
				break;
		}
		synchronized (mTaskList) {
			mTaskList.remove(task);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mThread.cancel();
	}

	// UUID号,表示不同的数据协议
	private final String UUID_STR = "00001101-0000-1000-8000-00805F9B34FB";

	/**
	 * 等待客户端连接线程
	 * @author [email protected]
	 */
	private class AcceptThread extends Thread {
		private final BluetoothServerSocket mServerSocket;
		private boolean isCancel = false;

		public AcceptThread() {
			Log.d(TAG, "AcceptThread");
			BluetoothServerSocket tmp = null;
			try {
				tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(
						"Bluetooth_Chat_Room", UUID.fromString(UUID_STR));
			} catch (IOException e) {
			}
			mServerSocket = tmp;
		}

		public void run() {
			BluetoothSocket socket = null;
			while (true) {
				try {
					// 阻塞等待
					socket = mServerSocket.accept();
				} catch (IOException e) {
					if (!isCancel) {
						try {
							mServerSocket.close();
						} catch (IOException e1) {
						}
						// 异常结束时,再次监听
						mAcceptThread = new AcceptThread();
						mAcceptThread.start();
						isServerMode = true;
					}
					break;
				}
				if (socket != null) {
					// 管理已经连接的客户端
					manageConnectedSocket(socket);
					try {
						mServerSocket.close();
					} catch (IOException e) {
					}
					mAcceptThread = null;
					break;
				}
			}
		}

		public void cancel() {
			try {
				Log.d(TAG, "AcceptThread canceled");
				isCancel = true;
				isServerMode = false;
				mServerSocket.close();
				mAcceptThread = null;
				if (mCommThread != null && mCommThread.isAlive()) {
					mCommThread.cancel();
				}
			} catch (IOException e) {
			}
		}
	}

	/**
	 * 作为客户端连接指定的蓝牙设备线程
	 *
	 * @author [email protected]
	 */
	private class ConnectThread extends Thread {
		private final BluetoothSocket mSocket;
		private final BluetoothDevice mDevice;

		public ConnectThread(BluetoothDevice device) {

			Log.d(TAG, "ConnectThread");

			// 服务器监听线程不为空,将其结束掉开始作为客户端
			if (mAcceptThread != null && mAcceptThread.isAlive()) {
				mAcceptThread.cancel();
			}

			// 如果设备已经连接线程存在,则结束它
			if (mCommThread != null && mCommThread.isAlive()) {
				mCommThread.cancel();
			}

			BluetoothSocket tmp = null;
			mDevice = device;
			try {
				tmp = device.createRfcommSocketToServiceRecord(UUID
						.fromString(UUID_STR));
			} catch (IOException e) {
				Log.d(TAG, "createRfcommSocketToServiceRecord error!");
			}

			mSocket = tmp;
		}

		public BluetoothDevice getDevice() {
			return mDevice;
		}

		public void run() {
			// 取消设备扫描
			mBluetoothAdapter.cancelDiscovery();
			try {
				// 连接远程服务器设备
				mSocket.connect();
			} catch (IOException connectException) {
				Log.e(TAG, "Connect server failed");
				try {
					mSocket.close();
				} catch (IOException closeException) {
				}
				// 连接服务器失败,则自己作为服务器监听
				mAcceptThread = new AcceptThread();
				mAcceptThread.start();
				isServerMode = true;
				return;
			} // Do work to manage the connection (in a separate thread)
			manageConnectedSocket(mSocket);
		}

		public void cancel() {
			try {
				mSocket.close();
			} catch (IOException e) {
			}
			mConnectThread = null;
		}
	}

	private ConnectedThread mCommThread;

	private void manageConnectedSocket(BluetoothSocket socket) {
		// 启动子线程来维持连接
		mCommThread = new ConnectedThread(socket);
		mCommThread.start();
	}

	private class ConnectedThread extends Thread {
		private final BluetoothSocket mSocket;
		private final InputStream mInStream;
		private final OutputStream mOutStream;
		private BufferedWriter mBw;

		public ConnectedThread(BluetoothSocket socket) {
			Log.d(TAG, "ConnectedThread");
			mSocket = socket;
			InputStream tmpIn = null;
			OutputStream tmpOut = null;
			try {
				tmpIn = socket.getInputStream();
				tmpOut = socket.getOutputStream();
			} catch (IOException e) {
			}
			mInStream = tmpIn;
			mOutStream = tmpOut;
			// 获得远程设备的输出缓存字符流
			mBw = new BufferedWriter(new PrintWriter(mOutStream));

		}

		public OutputStream getOutputStream() {
			return mOutStream;
		}

		public boolean write(String msg) {
			if (msg == null)
				return false;
			try {
				mBw.write(msg + "\n");
				mBw.flush();
				System.out.println("Write:" + msg);
			} catch (IOException e) {
				return false;
			}
			return true;
		}

		public String getRemoteName() {
			return mSocket.getRemoteDevice().getName();
		}

		public void cancel() {
			try {
				mSocket.close();
			} catch (IOException e) {
			}
			mCommThread = null;
		}

		public void run() {
			// 将上线提示信息写入到远程设备中
			write(mBluetoothAdapter.getName() + "已经上线");
			android.os.Message handlerMsg;
			String buffer = null;

			// 获得远程设备的缓存字符输入流
			BufferedReader br = new BufferedReader(new InputStreamReader(
					mInStream));

			while (true) {
				try {
					// 读取远程设备的一行数据
					buffer = br.readLine();
					System.out.println("收到:" + buffer);
					if (buffer == null)
						continue;

					if (mActivityHandler == null) {
						return;
					}

					buffer = mSocket.getRemoteDevice().getName() + ":" + buffer;
					// 通过Activity更新到UI上
					handlerMsg = mActivityHandler.obtainMessage();
					handlerMsg.what = Task.TASK_RECV_MSG;
					handlerMsg.obj = buffer;
					mActivityHandler.sendMessage(handlerMsg);
				} catch (IOException e) {
					try {
						mSocket.close();
					} catch (IOException e1) {
					}
					mCommThread = null;
					if (isServerMode) {
						// 检查远程设备状态
						handlerMsg = mServiceHandler.obtainMessage();
						handlerMsg.what = Task.TASK_GET_REMOTE_STATE;
						mServiceHandler.sendMessage(handlerMsg);
						// 重新启动服务端连接线程
						mAcceptThread = new AcceptThread();
						mAcceptThread.start();
					}
					break;
				}
			}
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
}

界面布局:

main—activity:

<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"
   >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/editText1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

    </ListView>

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:onClick="onSendClick"
        android:text="Send" />

</RelativeLayout>

menu/main:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/scann_device"
        android:orderInCategory="100"
        android:title="扫描周围设备"/>


    <item
        android:id="@+id/change_name"
        android:orderInCategory="100"
        android:title="修改用户名"/>
</menu>

bt——list

<?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"
    android:orientation="vertical" >

    <Button
        android:id="@+id/scanDevBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onScannClick"
        android:text="Scann bt devices" />

    <ListView
        android:id="@+id/scanDevList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

猜你喜欢

转载自blog.csdn.net/qq_41063141/article/details/84938101