安卓蓝牙接收数据不全

qq_36723356 2017-02-06 07:38:44

public class MainActivity extends Activity {
MyDatabaseHelper dbHelper;
private final static int REQUEST_CONNECT_DEVICE = 1; //宏定义查询设备句柄

private final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB"; //SPP服务UUID号

private InputStream is; //输入流,用来接收蓝牙数据
private EditText edit0; //发送数据输入句柄
private TextView dis; //接收数据显示句柄
private ScrollView sv; //翻页句柄
private String smsg = ""; //显示用数据缓存
private String fmsg = ""; //保存用数据缓存


public String filename = ""; //用来保存存储的文件名
BluetoothDevice _device = null; //蓝牙设备
BluetoothSocket _socket = null; //蓝牙通信socket
boolean _discoveryFinished = false;
boolean bRun = true;
boolean bThread = false;
private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter(); //获取本地蓝牙适配器,即蓝牙设备



/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //设置画面为主画面 main.xml
sv = (ScrollView) findViewById(R.id.ScrollView01); //得到翻页句柄
dis = (TextView) findViewById(R.id.in); //得到数据显示句柄
/* Button search = (Button) findViewById(R.id.Read);
edit0 = (EditText)findViewById(R.id.Edit0); //得到输入框句柄*/

// 创建MyDatabaseHelper对象,指定数据库版本为1,此处使用相对路径即可,
// 数据库文件自动会保存在程序的数据文件夹的databases目录下。
dbHelper = new MyDatabaseHelper(this, "myDict.db4" , 1);


//如果打开本地蓝牙设备不成功,提示信息,结束程序
if (_bluetooth == null) {
Toast.makeText(this, "无法打开手机蓝牙,请确认手机是否有蓝牙功能!", Toast.LENGTH_LONG).show();
finish();
return;
}

// 设置设备可以被搜索
new Thread() {
public void run() {
if (_bluetooth.isEnabled() == false) {
_bluetooth.enable();
}
}
}.start();

}
/****************数据库******************************************/
//插入数据
public void insert(View view){
//获取用户输入
String word = ((EditText)findViewById(R.id.word))
.getText().toString();

//插入生词记录
insertData(dbHelper.getReadableDatabase() , word );
//显示提示信息
Toast.makeText(MainActivity.this, "添加生词成功!" , 8000).show();
}

//查询所有数据
public void search(View view){
Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from dict ",null);

//创建一个Bundle对象
Bundle data = new Bundle();
data.putSerializable("data", converCursorToList(cursor));
//创建一个Intent
Intent intent = new Intent(MainActivity.this
, ResultActivity.class);
intent.putExtras(data);
//启动Activity
startActivity(intent);
Toast.makeText(MainActivity.this, "跳转成功" , 8000).show();
}

protected ArrayList<Map<String , String>> converCursorToList(Cursor cursor)
{
ArrayList<Map<String , String>> result = new ArrayList<Map<String , String>>();
//遍历Cursor结果集
while(cursor.moveToNext())
{
//将结果集中的数据存入ArrayList中
Map<String , String> map = new
HashMap<String , String>();
//取出查询记录中第2列、第3列的值
map.put("word" , cursor.getString(1));
map.put("detail" , cursor.getString(2));
result.add(map);
}
return result;
}
private void insertData(SQLiteDatabase db, String word )
{
//执行插入语句
db.execSQL("insert into dict values(null , ? , ?)"
, new String[]{word });
}






/****************数据库******************************************/
//发送按键响应
public void onSendButtonClicked(View v) {
char a = 0x01;
try {
OutputStream os = _socket.getOutputStream(); //蓝牙连接输出流
os.write(a);
} catch (IOException e) {
}
}
//接收活动结果,响应startActivityForResult()
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE: //连接结果,由DeviceListActivity设置返回
// 响应返回结果
if (resultCode == Activity.RESULT_OK) { //连接成功,由DeviceListActivity设置返回
// MAC地址,由DeviceListActivity设置返回
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// 得到蓝牙设备句柄
_device = _bluetooth.getRemoteDevice(address);

// 用服务号得到socket
try {
_socket = _device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
} catch (IOException e) {
Toast.makeText(this, "连接失败!", Toast.LENGTH_SHORT).show();
}
//连接socket
Button btn = (Button) findViewById(R.id.Button03);
try {
_socket.connect();
Toast.makeText(this, "连接" + _device.getName() + "成功!", Toast.LENGTH_SHORT).show();
btn.setText("断开");
} catch (IOException e) {
try {
Toast.makeText(this, "连接失败!", Toast.LENGTH_SHORT).show();
_socket.close();
_socket = null;
} catch (IOException ee) {
Toast.makeText(this, "连接失败!", Toast.LENGTH_SHORT).show();
}

return;
}

//打开接收线程
try {
is = _socket.getInputStream(); //得到蓝牙数据输入流
} catch (IOException e) {
Toast.makeText(this, "接收数据失败!", Toast.LENGTH_SHORT).show();
return;
}
if (bThread == false) {
ReadThread.start();
bThread = true;
} else {
bRun = true;
}
}
break;
default:
break;
}
}



//接收数据线程
Thread ReadThread = new Thread() {

public void run() {
int num = 0;
byte[] buffer = new byte[1024];
byte[] buffer_new = new byte[1024];
int i = 0;
int n = 0;
bRun = true;
//接收线程
while (true) {
try {
while (is.available() == 0) {
while (bRun == false) {
}
}
while (true) {
num = is.read(buffer); //读入数据
n = 0;
String s0 = new String(buffer, 0, num);

fmsg += s0; //保存收到数据
try
{
Thread.currentThread().sleep(1000);//毫秒
}
catch(Exception e){}


insertData(dbHelper.getReadableDatabase(), s0);
for (i = 0; i < num; i++) {
if ((buffer[i] == 0x0d) && (buffer[i + 1] == 0x0a)) {
buffer_new[n] = 0x0a;
i++;
} else {
buffer_new[n] = buffer[i];
}
n++;
}
String s = new String(buffer_new, 0, n);
smsg += s; //写入接收缓存
if (is.available() == 0) break; //短时间没有数据才跳出进行显示
}
//发送显示消息,进行显示刷新
handler.sendMessage(handler.obtainMessage());
} catch (IOException e) {
}
}
}
};

//消息处理队列
Handler handler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
dis.setText(smsg); //显示数据
sv.scrollTo(0, dis.getMeasuredHeight()); //跳至数据最后一页
}
};

//关闭程序掉用处理部分
public void onDestroy() {
super.onDestroy();
if (_socket != null) //关闭连接socket
try {
_socket.close();
dbHelper.close();
} catch (IOException e) {
}
// _bluetooth.disable(); //关闭蓝牙服务
}


//连接按键响应函数
public void onConnectButtonClicked(View v) {
if (_bluetooth.isEnabled() == false) { //如果蓝牙服务不可用则提示
Toast.makeText(this, " 打开蓝牙中...", Toast.LENGTH_LONG).show();
return;
}


//如未连接设备则打开DeviceListActivity进行设备搜索
Button btn = (Button) findViewById(R.id.Button03);
if (_socket == null) {
Intent serverIntent = new Intent(this, DeviceListActivity.class); //跳转程序设置
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); //设置返回宏定义
} else {
//关闭连接socket
try {

is.close();
_socket.close();
_socket = null;
bRun = false;
btn.setText("连接");
} catch (IOException e) {
}
}
return;
}
}
...全文
429 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_36723356 2017-02-06
  • 打赏
  • 举报
回复
求大神解救
qq_36723356 2017-02-06
  • 打赏
  • 举报
回复
例如我发的是12345,结果收到的是1和2345

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧