易安卓如何用蓝牙发送生活中十六进制有哪些的hex数据?

安卓开发中如何将一下一串信息,转变成16进制信息?_百度知道
安卓开发中如何将一下一串信息,转变成16进制信息?
7E 00 0E 90 00 12 4B 00 01 F6 96 0F 00 00 02 01 18 5B
答题抽奖
首次认真答题后
即可获得3次抽奖机会,100%中奖。
参考这个:public class Test {
public static void main(String[] args) {
byte[] b = HexString2Bytes(&AA020155&);
String s = Bytes2HexString(b);
System.out.println(s);
* 将两个ASCII字符合成一个字节;
* 如:&EF&--& 0xEF
* @param src0 byte
* @param src1 byte
* @return byte
public static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode(&0x& + new String(new byte[]{src0})).byteValue();
_b0 = (byte)(_b0 && 4);
byte _b1 = Byte.decode(&0x& + new String(new byte[]{src1})).byteValue();
byte ret = (byte)(_b0 ^ _b1);
* 将指定字符串src,以每两个字符分割转换为16进制形式
* 如:&2B44EFD9& –& byte[]{0x2B, 0×44, 0xEF, 0xD9}
* @param src String
* @return byte[]
public static byte[] HexString2Bytes(String src){
byte[] ret = new byte[src.length()/2];
byte[] tmp = src.getBytes();
for(int i=0; i& tmp.length/2; i++){
ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]);
* 将指定byte数组以16进制的形式打印到控制台
* @param hint String
* @param b byte[]
* @return void
public static void printHexString(String hint, byte[] b) {
System.out.print(hint);
for (int i = 0; i & b. i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' +
System.out.print(hex.toUpperCase() + & &);
System.out.println(&&);
* @param b byte[]
* @return String
public static String Bytes2HexString(byte[] b) {
String ret = &&;
for (int i = 0; i & b. i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' +
ret += hex.toUpperCase();
采纳率:51%
对不起,我不懂这方面的内容。
为您推荐:
其他类似问题
安卓的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。易语言 e4a(易安卓) 使用蓝牙或其他方式由e4a发送指定文本到易语言程序 e4a可换成其他开发方式_百度知道
易语言 e4a(易安卓) 使用蓝牙或其他方式由e4a发送指定文本到易语言程序 e4a可换成其他开发方式
易语言 e4a(易安卓) 使用蓝牙或其他方式由e4a发送指定文本到易语言程序
可以使用例如蓝牙usb等
只需要方法或者模块即可
e4a可以替换成其他android开发方式(包含例如蓝牙芯片发送指令之类)
另外可以让蓝牙usb自动在电脑上安装程序的东西有没有
答题抽奖
首次认真答题后
即可获得3次抽奖机会,100%中奖。
用客户端 发送 接收 都可以 通过局网 或者外网(需要放射端口)蓝牙如果是台式机需要外置蓝牙接收器笔记本好多有蓝牙功能 可以直接使用
人民币的话联系
tcp方式通讯
再见,tcp需要网络吧?
要不就通过串口
只能通过网络
那如果用蓝牙芯片对蓝牙usb发送呢?
为您推荐:
其他类似问题
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。android 怎么通过蓝牙向一个硬件发送AT指令_百度知道
android 怎么通过蓝牙向一个硬件发送AT指令
答题抽奖
首次认真答题后
即可获得3次抽奖机会,100%中奖。
将16进制的字符串转换成bytes,通过hexstring2bytes转换而不能直接用getbytes String string = &F392C310D&;mmOutStream.write(string.getBytes());读取inputsteam中的?
Log.d(&example&, &do read&); 不执行,完整代码如下:?
/** * This thread runs during a connection with a remote device. It handles all * incoming and outgoing transmissions. */private class ConnectedThread extends Thread {
private final BluetoothSocket mmS
private final InputStream mmInS
private final OutputStream mmOutS
public ConnectedThread(BluetoothSocket socket, String socketType) {
Log.d(TAG, &create ConnectedThread: & + socketType);
mmSocket =
InputStream tmpIn =
OutputStream tmpOut =
// Get the BluetoothSocket input and output streams
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, &temp sockets not created&, e);
mmInStream = tmpIn;
mmOutStream = tmpO
public void run() {
Log.i(TAG, &BEGIN mConnectedThread&);
byte[] buffer = new byte[1024];
// Keep listening to the InputStream while connected
while (true) {
Log.d(&example&, &do read&);
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes,
-1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, &disconnected&, e);
connectionLost();
// Start the service over to restart listening mode
BluetoothChatService.this.start();
* Write to the connected OutStream.
* @param buffer
The bytes to write
public void write(byte[] buffer) {
String string = &F392C310D&;
mmOutStream.write(string.getBytes());
// Share the sent message back to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1,
buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, &Exception during write&, e);
public void cancel() {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, &close() of connect socket failed&, e);
百度知道合伙人官方认证企业
主营:培训【Python+人工智能,Java大数据,HTML5】
通过BluetoothSocket的OutputStream发送过去后,InputStream获取不到数据...代码用的android自带的蓝牙例子.这样发送指令后?12String string = &F392C310D&;mmOutStream.write(string.getBytes());读取inputsteam中的?1Log.d(&example&, &do read&);不执行,完整代码如下:?7787980/**&* This thread runs during a connection with a remote device. It handles all&* incoming and outgoing transmissions.&*/private class ConnectedThread extends Thread {&&&&private final BluetoothSocket mmS&&&&private final InputStream mmInS&&&&private final OutputStream mmOutS&&&&&public ConnectedThread(BluetoothSocket socket, String socketType) {&&&&&&&&Log.d(TAG, &create ConnectedThread: & + socketType);&&&&&&&&mmSocket =&&&&&&&&InputStream tmpIn =&&&&&&&&OutputStream tmpOut =&&&&&&&&&// 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 = tmpO&&&&}&&&&&public void run() {&&&&&&&&Log.i(TAG, &BEGIN mConnectedThread&);&&&&&&&&byte[] buffer = new byte[1024];&&&&&&&&&&&&&&&&&// Keep listening to the InputStream while connected&&&&&&&&while (true) {&&&&&&&&&&&&Log.d(&example&, &do read&);&&&&&&&&&&&&try {&&&&&&&&&&&&&&&&// Read from the InputStream&&&&&&&&&&&&&&&&bytes = mmInStream.read(buffer);&&&&&&&&&&&&&&&&&// Send the obtained bytes to the UI Activity&&&&&&&&&&&&&&&&mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes,&&&&&&&&&&&&&&&&&&&&&&&&-1, buffer).sendToTarget();&&&&&&&&&&&&} catch (IOException e) {&&&&&&&&&&&&&&&&Log.e(TAG, &disconnected&, e);&&&&&&&&&&&&&&&&connectionLost();&&&&&&&&&&&&&&&&// Start the service over to restart listening mode&&&&&&&&&&&&&&&&BluetoothChatService.this.start();&&&&&&&&&&&&&&&&&&&&&&&&&&&&}&&&&&&&&}&&&&}&&&&&/**&&&&&* Write to the connected OutStream.&&&&&* &&&&&* @param buffer&&&&&*&&&&&&&&&&& The bytes to write&&&&&*/&&&&public void write(byte[] buffer) {&&&&&&&&&String string = &F392C310D&;&&&&&&&&try {&&&&&&&&&&&&mmOutStream.write(string.getBytes());&&&&&&&&&&&&&// Share the sent message back to the UI Activity&&&&&&&&&&&&mHandler.obtainMessage(BluetoothChat.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);&&&&&&&&}&&&&}}0收藏(0)&
为您推荐:
其他类似问题
您可能关注的内容
at指令的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。欢迎转载,但请注明出处!谢谢。
  最近公司在做一个蓝牙串口通讯的App,有一个固定的蓝牙设备,需要实现手机连接相互交换数据。以前没怎么做过蓝牙开发,故查看Android App Guide的蓝牙篇,发现有个chat示例,故此做了点研究。在研究的基础上进行了此App的实现。
  1、App特点:
    1.1 App中同时存在服务器与客户端,任意手机可以作为服务器或者客户端;
    1.2 客户端可以进行蓝牙环境扫描;
    1.3 诸多异常处理&&均未做,O(&_&)O。demo了,主要学习的是蓝牙技术嘛。
  2、实现过程中的总结:
    2.1 蓝牙串口通讯,谷歌给出了一个固定UUID:&0-805F9B34FB,大多数蓝牙串口设备使用此UUID作为连接用UUID,此UUID在BluetoothDevice的createRfcommSocketToServiceRecord方法中有提到。具体可以看api doc。
  3、具体实现代码:
    3.1 客户端服务器选择页:MainActivity。此页仅进行客户端与服务器端选择使用。
      3.1.1 Activity:
      
1 package org.fiu.
3 import org.fiu.bluetoothchatdemos.R;
5 import android.content.I
6 import android.os.B
7 import android.support.v7.app.ActionBarA
8 import android.view.M
9 import android.view.MenuI
10 import android.view.V
12 public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
* 建立服务器
* @param view
public void btn_server(View view) {
startActivity(new Intent(this, ServerActivity.class));
* 建立客户端
* @param view
public void btn_client(View view) {
startActivity(new Intent(this, ClientActivity.class));
public boolean onCreateOptionsMenu(Menu menu) {
// I this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
return super.onOptionsItemSelected(item);
      3.1.2 layout:
1 &LinearLayout 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:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="org.fiu.bluetoothdemos.MainActivity" &
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="btn_server"
android:text="开启服务器" /&
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="btn_client"
android:text="开启客户端" /&
24 &/LinearLayout&
    3.2 服务器端代码:
      3.2.1 服务器页面:点击进入服务器页面后,直接使用上面所说UUID进行服务器建立,等待客户端连接工作。拥有一个消息显示框和发送EditText,可以与客户端进行交互。内部拥有一个BluetoothServer管理类,这个类主要管理了服务器的蓝牙操作。
      
1 package org.fiu.
3 import java.util.ArrayL
4 import java.util.L
5 import java.util.T
6 import java.util.TimerT
8 import org.fiu.bluetoothchatdemos.R;
10 import android.app.A
11 import android.os.B
12 import android.view.V
13 import android.view.ViewG
14 import android.widget.AbsListV
15 import android.widget.BaseA
16 import android.widget.EditT
17 import android.widget.ListV
18 import android.widget.TextV
* @author c
26 public class ServerActivity extends Activity {
private EditText et_
private BluetoothS
private List&String& msgs = new ArrayList&String&();
private TimerTask task = new TimerTask() {
public void run() {
synchronized (msgs) {
msgs = server.getMsgs();
runOnUiThread(new Runnable() {
public void run() {
msgAdapter.notifyDataSetChanged();
private MyAdapter msgA
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
et_msg = (EditText) findViewById(R.id.et_msg);
server = new BluetoothServer(this);
server.start();
ListView lv_msg = (ListView) findViewById(R.id.lv_msg);
msgAdapter = new MyAdapter();
lv_msg.setAdapter(msgAdapter);
Timer timer = new Timer();
timer.schedule(task, 0, 1000);
public class MyAdapter extends BaseAdapter {
public int getCount() {
// TODO Auto-generated method stub
return msgs.size();
public Object getItem(int position) {
return msgs.get(position);
public long getItemId(int position) {
// TODO Auto-generated method stub
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv = null;
if (convertView != null) {
tv = (TextView) convertV
tv = new TextView(ServerActivity.this);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT,
AbsListView.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
tv.setTag(msgs.get(position));
tv.setText(msgs.get(position));
* @param view
public void btn_send(View view) {
String msg = et_msg.getText().toString().trim();
send(msg);
* 发送消息到客户端
* @param msg
private void send(String msg) {
server.send(msg);
synchronized (msgs) {
msgs.add("服务器发送:" + msg);
      3.2.2 服务器页面layout
      
1 &?xml version="1.0" encoding="utf-8"?&
2 &LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="vertical" &
&LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:orientation="horizontal" &
android:id="@+id/et_msg"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:hint="chatMessage" /&
android:layout_width="20dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="btn_send"
android:text="send" /&
&/LinearLayout&
android:id="@+id/lv_msg"
android:layout_width="match_parent"
android:layout_height="match_parent" &
&/ListView&
35 &/LinearLayout&
      3.2.3 服务器蓝牙管理类
      
1 package org.fiu.
3 import java.io.IOE
4 import java.io.InputS
5 import java.util.ArrayL
6 import java.util.L
7 import java.util.UUID;
9 import android.bluetooth.BluetoothA
10 import android.bluetooth.BluetoothServerS
11 import android.bluetooth.BluetoothS
12 import android.content.C
13 import android.os.H
14 import android.os.L
15 import android.os.M
16 import android.util.L
17 import android.widget.T
* 蓝牙服务器
* @author weizh
25 public class BluetoothServer {
* 消息集合
private List&String& listMsg = new ArrayList&String&();
* 是否工作中
private boolean isWorking = false;
* bluetooth name
private String name = "FIUBluetoothServer";
* spp well-known UUID
public static final UUID MY_UUID = UUID
.fromString("0-805F9B34FB");
private static final String TAG = "BluetoothServer";
* 蓝牙服务器socket
private BluetoothServerSocket bluetoothServerS
* 客户端socket
private BluetoothSocket mClientS
public BluetoothServer(Context context) {
this.context =
* 开启服务器
public void start() {
* 开始监听
private void listen() {
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
// 判断是否有蓝牙设备
if (!BluetoothUtils.checkBluetoothExists()) {
throw new RuntimeException("bluetooth module not exists.");
// 打开设备
if (!BluetoothUtils.openBluetoothDevice()) {
if (bluetoothServerSocket == null) {
bluetoothServerSocket = BluetoothAdapter
.getDefaultAdapter()
.listenUsingRfcommWithServiceRecord(name,
isWorking = true;
while (isWorking) {
mClientSocket = bluetoothServerSocket.accept();
Log.i(TAG, "客户端已连接:"
+ mClientSocket.getRemoteDevice().getName());
myHandler.sendEmptyMessage(0x01);
new ClientWorkingThread(mClientSocket).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}).start();
private Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
Toast.makeText(context,
"客户端已连接:" + mClientSocket.getRemoteDevice().getName(), 0)
public void stop() {
isWorking = false;
if (bluetoothServerSocket != null) {
bluetoothServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
bluetoothServerSocket = null;
if (mClientSocket != null) {
mClientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
mClientSocket = null;
* 客户端socket工作类
* @author weizh
private class ClientWorkingThread extends Thread {
* 客户端socket
private BluetoothSocket mClientS
public ClientWorkingThread(BluetoothSocket clientSocket) {
this.mClientSocket = clientS
public void run() {
InputStream inputStream = mClientSocket.getInputStream();// 输入流
// 从输入流中取出数据,插入消息条中
byte[] buffer = new byte[1024];
while (isWorking) {
int read = inputStream.read(buffer);
if (read != -1) {
// 判断是否取得的消息填充满了buffer,未到字符串结尾符;如果不是,证明读取到了一条信息,并且信息是完整的,这个完整的前提是不能粘包,不粘包可以使用flush进行处理。
StringBuilder sb = new StringBuilder();
if (read & buffer.length) {
String msg = new String(buffer, 0, read);
sb.append(msg);
byte[] tempBytes = new byte[1024 * 4];
while (read == buffer.length
&& buffer[read - 1] != 0x7f) {
read = inputStream.read(buffer);
String msg = new String(buffer, 0, read);
sb.append(msg);
Log.i(TAG, "服务器收到:" + sb.toString());
synchronized (listMsg) {
listMsg.add("客户端发送:" + sb.toString());
// Thread.sleep(300);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 工作完毕,关闭socket
mClientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
* 返回listMsg
public List&String& getMsgs() {
synchronized (listMsg) {
return listM
* 发送消息
* @param msg
public void send(String msg) {
if (mClientSocket != null) {
mClientSocket.getOutputStream().write(msg.getBytes());
mClientSocket.getOutputStream().flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
     3.3 客户端页面:客户端除了具有消息框和发送消息框外,加载后首先可以进行蓝牙环境扫描,并且和选择。demo中偷了懒,没在选择后停止蓝牙扫描工作等诸多小细节&&
      3.3.1 客户端页面代码:
1 package org.fiu.
3 import java.util.ArrayL
4 import java.util.L
5 import java.util.T
6 import java.util.TimerT
8 import org.fiu.bluetoothchatdemos.R;
9 import org.fiu.bluetoothdemos.ServerActivity.MyA
11 import android.app.A
12 import android.app.AlertD
13 import android.bluetooth.BluetoothA
14 import android.bluetooth.BluetoothD
15 import android.content.BroadcastR
16 import android.content.C
17 import android.content.I
18 import android.content.IntentF
19 import android.os.B
20 import android.util.L
21 import android.view.LayoutI
22 import android.view.V
23 import android.view.View.OnClickL
24 import android.view.ViewG
25 import android.view.ViewGroup.LayoutP
26 import android.widget.AbsListV
27 import android.widget.AbsoluteL
28 import android.widget.AdapterV
29 import android.widget.AdapterView.OnItemClickL
30 import android.widget.ArrayA
31 import android.widget.BaseA
32 import android.widget.EditT
33 import android.widget.LinearL
34 import android.widget.ListV
35 import android.widget.TextV
* @author c
43 public class ClientActivity extends Activity {
* 被发现的设备
private List&BluetoothDevice& discoverDevices = new ArrayList&BluetoothDevice&();
* 蓝牙客户端
private BluetoothClient bluetoothC
public final String TAG = "ClientActivity";
* 搜索对话框
private AlertDialog dlgS
private BaseA
private EditText et_
private List&String& msgs = new ArrayList&String&();
private TimerTask task = new TimerTask() {
public void run() {
synchronized (msgs) {
msgs = bluetoothClient.getMsgs();
runOnUiThread(new Runnable() {
public void run() {
msgAdapter.notifyDataSetChanged();
private MyAdapter msgA
* 设备搜索广播
private BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case BluetoothDevice.ACTION_FOUND:
// 发现设备,添加到列表,刷新列表
discoverDevices.add((BluetoothDevice) intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE));
if (adapter != null) {
adapter.notifyDataSetChanged();
case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
// 开始搜索
Log.i(TAG, "开始搜索设备");
discoverDevices.clear();
// 弹出对话框
if (dlgSearch == null) {
dlgSearch = new AlertDialog.Builder(ClientActivity.this)
.create();
// 自定义对话框
View view = LayoutInflater.from(ClientActivity.this)
.inflate(R.layout.dialog_search, null);
ListView lv_devices = (ListView) view
.findViewById(R.id.lv_devices);
adapter = new DevicesAdapter(ClientActivity.this);
lv_devices.setAdapter(adapter);
lv_devices
.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView&?& parent,
View view, int position, long id) {
// 项点击时,进行连接
BluetoothDevice device = (BluetoothDevice) view
.getTag();
bluetoothClient.connect(device);
dlgSearch.dismiss();
dlgSearch = null;
dlgSearch.setView(view);
dlgSearch.setCancelable(true);// 可以按back键取消
dlgSearch.setCanceledOnTouchOutside(false);// 不可以按空白地方取消
dlgSearch.show();
case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
// 结束搜索
Log.i(TAG, "结束搜索设备");
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
bluetoothClient = new BluetoothClient();
et_msg = (EditText) findViewById(R.id.et_msg);
ListView lv_msg = (ListView) findViewById(R.id.lv_msg);
msgAdapter = new MyAdapter();
lv_msg.setAdapter(msgAdapter);
Timer timer = new Timer();
timer.schedule(task, 0, 1000);
// 搜索蓝牙设备
bluetoothClient.start();
public class MyAdapter extends BaseAdapter {
public int getCount() {
// TODO Auto-generated method stub
return msgs.size();
public Object getItem(int position) {
return msgs.get(position);
public long getItemId(int position) {
// TODO Auto-generated method stub
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv = null;
if (convertView != null) {
tv = (TextView) convertV
tv = new TextView(ClientActivity.this);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT,
AbsListView.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
tv.setTag(msgs.get(position));
tv.setText(msgs.get(position));
protected void onResume() {
super.onResume();
registerReceiver();
private void registerReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
* 设备adapter
* @author c
private class DevicesAdapter extends BaseAdapter {
public DevicesAdapter(Context context) {
this.context =
public int getCount() {
return discoverDevices.size();
public Object getItem(int position) {
// TODO Auto-generated method stub
return discoverDevices.get(position);
public long getItemId(int position) {
// TODO Auto-generated method stub
public View getView(final int position, View convertView,
ViewGroup parent) {
TextView tv = null;
if (convertView != null) {
tv = (TextView) convertV
tv = new TextView(context);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT,
AbsListView.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(params);
tv.setTag(discoverDevices.get(position));
tv.setText(discoverDevices.get(position).getName());
tv.setFocusable(false);
tv.setFocusableInTouchMode(false);
// tv.setOnClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// // 项点击时,进行连接
// bluetoothClient.connect(discoverDevices.get(position));
// dlgSearch.dismiss();
// dlgSearch =
* @param view
public void btn_send(View view) {
String msg = et_msg.getText().toString().trim();
send(msg);
* 发送消息到客户端
* @param msg
private void send(String msg) {
bluetoothClient.send(msg);
synchronized (msgs) {
msgs.add("客户端发送:" + msg);
      3.3.2 客户端页面layout  
1 &?xml version="1.0" encoding="utf-8"?&
2 &LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="vertical" &
&LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:orientation="horizontal" &
android:id="@+id/et_msg"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:hint="chatMessage" /&
android:layout_width="20dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="btn_send"
android:text="send" /&
&/LinearLayout&
android:id="@+id/lv_msg"
android:layout_width="match_parent"
android:layout_height="match_parent" &
&/ListView&
35 &/LinearLayout&
      3.3.3 客户端蓝牙管理类
1 package org.fiu.
3 import java.io.IOE
4 import java.io.InputS
5 import java.io.OutputS
6 import java.util.ArrayL
7 import java.util.L
8 import java.util.UUID;
10 import android.annotation.SuppressL
11 import android.bluetooth.BluetoothA
12 import android.bluetooth.BluetoothD
13 import android.bluetooth.BluetoothS
14 import android.util.L
* 蓝牙服务器
* @author weizh
22 public class BluetoothClient {
private static final String TAG = "BluetoothClient";
* 消息集合
private List&String& listMsg = new ArrayList&String&();
* 是否工作中
private boolean isWorking = false;
* spp well-known UUID
public final UUID uuid = UUID
.fromString("0-805F9B34FB");
* 客户端socket
private BluetoothSocket mClientS
public BluetoothClient() {
* 开启服务器
public void start() {
startDiscovery();
* 开始检查设备
private void startDiscovery() {
if (!BluetoothUtils.checkBluetoothExists()) {
throw new RuntimeException("bluetooth module not exists.");
// 打开设备
if (!BluetoothUtils.openBluetoothDevice()) {
// 开始扫描设备
BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
defaultAdapter.startDiscovery();
OutputStream outputS
private InputStream inputS
public void stop() {
isWorking = false;
if (mClientSocket != null) {
mClientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
mClientSocket = null;
* 客户端socket工作类
* @author weizh
private class ClientWorkingThread extends Thread {
public ClientWorkingThread() {
@SuppressLint("NewApi")
public void run() {
// 从输入流中取出数据,插入消息条中
byte[] buffer = new byte[1024];
while (isWorking) {
int read = inputStream.read(buffer);
if (read != -1) {
// 判断是否取得的消息填充满了buffer,未到字符串结尾符;如果不是,证明读取到了一条信息,并且信息是完整的,这个完整的前提是不能粘包,不粘包可以使用flush进行处理。
StringBuilder sb = new StringBuilder();
if (read & buffer.length) {
String msg = new String(buffer, 0, read);
sb.append(msg);
byte[] tempBytes = new byte[1024 * 4];
while (read == buffer.length
&& buffer[read - 1] != 0x7f) {
read = inputStream.read(buffer);
String msg = new String(buffer, 0, read);
sb.append(msg);
Log.i(TAG, "客户端收到:" + sb.toString());
synchronized (listMsg) {
listMsg.add("服务器发送:" + sb.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 工作完毕,关闭socket
mClientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
* 返回listMsg
public List&String& getMsgs() {
synchronized (listMsg) {
return listM
* 发送消息
* @param msg
public void send(final String msg) {
new Thread(new Runnable() {
public void run() {
if (mClientSocket != null) {
if (outputStream != null) {
byte[] bytes = msg.getBytes();
outputStream.write(bytes);
outputStream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}).start();
* 进行连接
* @param device
@SuppressLint("NewApi")
public void connect(final BluetoothDevice device) {
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
mClientSocket = device
.createRfcommSocketToServiceRecord(BluetoothServer.MY_UUID);
mClientSocket.connect();
isWorking = true;
outputStream = mClientSocket.getOutputStream();
inputStream = mClientSocket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
new ClientWorkingThread().start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i(TAG, "连接失败");
}).start();
      3.4 其它用到的布局和类
        3.4.1 dialog_search
1 &?xml version="1.0" encoding="utf-8"?&
2 &LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" &
&RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="horizontal" &
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="正在搜索&&" /&
&ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" /&
&/RelativeLayout&
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginBottom="2dp"
android:layout_marginTop="2dp"
android:background="@android:color/darker_gray" /&
android:id="@+id/lv_devices"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp" &
&/ListView&
41 &/LinearLayout&
3.5 BluetoothUtils.java:蓝牙帮助类
1 package org.fiu.
3 import java.util.L
4 import java.util.S
6 import android.bluetooth.BluetoothA
7 import android.bluetooth.BluetoothD
* 蓝牙帮助模块
* @author c
15 public class BluetoothUtils {
* 检查蓝牙模块是否存在
public static boolean checkBluetoothExists() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
if (bluetoothAdapter != null) {
return true;
return false;
* 打开蓝牙模块
public static boolean openBluetoothDevice() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
if (!bluetoothAdapter.isEnabled()) {
if (bluetoothAdapter.enable()) {
return true;
return true;
return false;
* 开启蓝牙模块扫描
public static void startDiscovery() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
if (!bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.startDiscovery();
* Convert hex string to byte[] 把为字符串转化为字节数组
* @param hexString
the hex string
* @return byte[]
public static byte[] hexStringToBytes(String hexString) {
hexString = hexString.replaceAll(" ", "");
if (hexString == null || hexString.equals("")) {
return null;
hexString = hexString.toUpperCase(Locale.getDefault());
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i & i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) && 4 | charToByte(hexChars[pos + 1]));
* Convert char to byte
* @param c
* @return byte
private static byte charToByte(char c) {
return (byte) "ABCDEF".indexOf(c);
* 获取已配对的蓝牙设备集合
public static Set&BluetoothDevice& getBondedDevices() {
return BluetoothAdapter.getDefaultAdapter().getBondedDevices();
* 检测当前device是否已经bonded过
* @param device
public static boolean isBonded(BluetoothDevice device) {
if (checkBluetoothExists()) {
// 连接之前先确定是否已经bond过,配对过
Set&BluetoothDevice& bondedDevices = BluetoothAdapter
.getDefaultAdapter().getBondedDevices();
if (bondedDevices != null) {
for (BluetoothDevice bluetoothDevice : bondedDevices) {
if (bluetoothDevice.getAddress()
.equals(device.getAddress())) {
// 该device已经bond过
return true;
return false;
3.6 AndroidManifest.xml:别忘了添加蓝牙权限
1 &?xml version="1.0" encoding="utf-8"?&
2 &manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.fiu.bluetoothchatdemos"
android:versionCode="1"
android:versionName="1.0" &
android:minSdkVersion="8"
android:targetSdkVersion="21" /&
&uses-permission android:name="android.permission.BLUETOOTH" /&
&uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /&
&application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" &
android:name="org.fiu.bluetoothdemos.MainActivity"
android:label="@string/app_name" &
&intent-filter&
&action android:name="android.intent.action.MAIN" /&
&category android:name="android.intent.category.LAUNCHER" /&
&/intent-filter&
&/activity&
&activity android:name="org.fiu.bluetoothdemos.ServerActivity" /&
&activity android:name="org.fiu.bluetoothdemos.ClientActivity" /&
&/application&
32 &/manifest&
    好了,此文章及至这里,如果有问题,欢迎留言。
    整包资源:
阅读(...) 评论()

我要回帖

更多关于 十六进制加法计算器 的文章

 

随机推荐