我正在处理我的项目,该项目需要蓝牙作为Android设备和微控制器芯片之间的通信形式。
我已经成功完成了我可以与设备配对并连接并将数据发送到芯片的部分,它工作正常。
我的计划流程如下: 起始页>输入文字/字符串>连接到设备>发送数据。
这里的主要问题是,如果我输入文本/字符串>连接到设备,但在连接后,我决定要在上一页中更改某些内容。所以我点击后退,蓝牙连接停止。它并没有保持联系。
所以我的主要想法是提出蓝牙连接页面,允许我先连接到设备,然后继续输入我的文本/字符串。这样,如果我决定制作另一个活动或标签,我可以轻扫标签并输入我想要的内容,每个标签中都会有一个发送按钮,允许我直接发送数据而无需重新连接。我现在坚持这个。
蓝牙活动:
public class bluetoothtest extends Activity {
/** Called when the activity is first created. */
SharedPreferences sPrefs;
//Variables
final byte ANIMATION_MODE=1;
final byte PICTURE_MODE=2;
final byte TEXT_MODE=3;
int a,b,c,d;
int count = 0, click = 0;
//TextView
TextView btStatus;
//ListView
ListView listViewPaired;
ListView deviceList;
ListView chatList;
//EditText
EditText contentRow1, contentRow2, contentRow3, contentRow4;
//Buttons
Button buttonSearch, buttonConnect;
ToggleButton bluetoothStatus;
//Bluetooth Related
BluetoothSocket socket;
BluetoothDevice bdDevice;
BluetoothClass bdClass;
deviceListAdapter mAdapter;
ChatListAdapter chAdapter;
Context mContext;
private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private readThread readThread = null;
private String BlueToothAddress;
//Array List/Adapter
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
ArrayList<String> arrayListpaired;
ArrayAdapter<String> adapter;
private ArrayList<deviceListItem> list;
private ArrayList<SiriListItem> delist;
//Misc
static HandleSeacrh handleSeacrh;
private ButtonClicked clicked;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//TextView
btStatus = (TextView) findViewById(R.id.btStatus);
//ListView
deviceList = (ListView) findViewById(R.id.deviceList);
chatList = (ListView) findViewById(R.id.chatList);
//EditText
contentRow1 = (EditText) findViewById(R.id.contentRow1);
contentRow2 = (EditText) findViewById(R.id.contentRow2);
contentRow3 = (EditText) findViewById(R.id.contentRow3);
contentRow4 = (EditText) findViewById(R.id.contentRow4);
//Buttons
buttonSearch = (Button) findViewById(R.id.buttonSearch);
buttonConnect = (Button) findViewById(R.id.connectBtn);
bluetoothStatus = (ToggleButton) findViewById(R.id.btStatusBtn);
//Array List/Adapter
list = new ArrayList<deviceListAdapter.deviceListItem>();
delist = new ArrayList<ChatListAdapter.SiriListItem>();
chAdapter = new ChatListAdapter(this, delist);
mAdapter = new deviceListAdapter(this, list);
deviceList.setAdapter(chAdapter);
chatList.setAdapter(mAdapter);
//Misc
clicked = new ButtonClicked();
handleSeacrh = new HandleSeacrh();
deviceList.setOnItemClickListener(mDeviceClickListener);
bluetoothStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bluetoothOnOff();
}
});
//Button Connect OnClickListener
buttonConnect.setOnClickListener(new View.OnClickListener() {
@SuppressLint("NewApi")
@Override
public void onClick(View arg0) {
if (count == 0) {
Toast.makeText(bluetoothtest.this,
"Please connect to a device first.",
Toast.LENGTH_LONG).show();
}
// Need API=14
else if (!socket.isConnected()) {
Toast.makeText(bluetoothtest.this,
"Connecting! Please wait.",
Toast.LENGTH_LONG).show();
}
else {
try {
sendMessageHandle(contentRow1.getText().toString(), contentRow2.getText().toString(), contentRow3.getText().toString(), contentRow4.getText().toString());
//sendMessageHandle(contentRow2.getText().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
sPrefs = getSharedPreferences("storeData", MODE_PRIVATE);
if(((byte) sPrefs.getInt("Mode", 1) == TEXT_MODE)){
contentRow1.setText(sPrefs.getString("firstRow", " "));
contentRow2.setText(sPrefs.getString("secondRow", " "));
contentRow3.setText(sPrefs.getString("thirdRow", " "));
contentRow4.setText(sPrefs.getString("fourthRow", " "));
}
IntentFilter discoveryFilter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
this.registerReceiver(myReceiver, discoveryFilter);
IntentFilter foundFilter = new IntentFilter(
BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(myReceiver, foundFilter);
IntentFilter btState = new IntentFilter(
BluetoothAdapter.ACTION_STATE_CHANGED);
this.registerReceiver(myReceiver, btState);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
buttonSearch.setOnClickListener(clicked);
if(bluetoothAdapter.isEnabled())
{
bluetoothStatus.setChecked(true);
//bluetoothStatus.setBackgroundColor(Color.GREEN);
btStatus.setText("Bluetooth Status: Enabled");
btStatus.setBackgroundColor(Color.GREEN);
}else if(!bluetoothAdapter.isEnabled())
{
bluetoothStatus.setChecked(false);
//bluetoothStatus.setBackgroundColor(Color.RED);
btStatus.setText("Bluetooth Status: Disabled");
btStatus.setBackgroundColor(Color.RED);
}
}
class ButtonClicked implements OnClickListener
{
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonSearch:
//arrayListBluetoothDevices.clear();
startSearching();
break;
default:
break;
}
}
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
// if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
// bluetoothOnOff();
// }
if(BluetoothDevice.ACTION_FOUND.equals(action)){
Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT).show();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED)
{ delist.add(new SiriListItem(device.getName() + "\n" + device.getAddress(), action, action, action, false));
mAdapter.notifyDataSetChanged();
deviceList.setSelection(delist.size() - 1);
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
if (deviceList.getCount() == 0) {
delist.add(new SiriListItem( "Did not find any bluetooth device", action, action, action, false));
mAdapter.notifyDataSetChanged();
deviceList.setSelection(list.size() - 1);
}
buttonSearch.setText("Search again");
}
}
};
private void bluetoothOnOff(){
if(!bluetoothAdapter.isEnabled())
{
bluetoothAdapter.enable();
String text = "Bluetooth Status: Enabled";
bluetoothStatus.setChecked(false);
//bluetoothStatus.setBackgroundColor(Color.GREEN);
btStatus.setText(text);
btStatus.setBackgroundColor(Color.GREEN);
}else if(bluetoothAdapter.isEnabled()){
String text = "Bluetooth Status: Disabled";
bluetoothAdapter.disable();
bluetoothStatus.setChecked(true);
//bluetoothStatus.setBackgroundColor(Color.RED);
btStatus.setText(text);
btStatus.setBackgroundColor(Color.RED);
}
}
class HandleSeacrh extends Handler
{
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 111:
break;
default:
break;
}
}
}
//SharedPreferences sp;
private void sendMessageHandle(String msg, String msg2, String msg3, String msg4) throws InterruptedException {
final byte ANIMATION_MODE=1;
final byte PICTURE_MODE=2;
final byte TEXT_MODE=3;
final int k = 5;
int temp,row;
sPrefs = getSharedPreferences("storeData",MODE_PRIVATE);
byte mode = (byte) sPrefs.getInt("Mode",1);
byte [] pictureData = new byte [129];
if (socket == null) {
Toast.makeText(mContext, "No connection", Toast.LENGTH_SHORT)
.show();
return;
}
try {
OutputStream outputStream = socket.getOutputStream();
if(mode==TEXT_MODE){
//TextMode Signal
outputStream.write(4);
Thread.sleep(500);
//Row 1 Message / Scroll
outputStream.write(0);
if(sPrefs.getBoolean("scrollRow1", false))
{}else
{outputStream.write(6);}
msg.getBytes();
if(msg.getBytes().length > 0)
{a = 1;
outputStream.write(msg.getBytes());
outputStream.write(32);}
//Row 2 Message / Scroll
outputStream.write(1);
if(sPrefs.getBoolean("scrollRow2", false))
{}else
{outputStream.write(6);}
msg2.getBytes();
if(msg2.getBytes().length > 0)
{b = 1;
outputStream.write(msg2.getBytes());
outputStream.write(32);}
//Row 3 Message / Scroll
outputStream.write(2);
if(sPrefs.getBoolean("scrollRow3", false))
{}else
{outputStream.write(6);}
msg3.getBytes();
if(msg3.getBytes().length > 0)
{c = 1;
outputStream.write(msg3.getBytes());
outputStream.write(32);}
//Row 4 Message / Scroll
outputStream.write(3);
if(sPrefs.getBoolean("scrollRow4", false))
{}else
{outputStream.write(6);}
msg4.getBytes();
if(msg4.getBytes().length > 0)
{d = 1;
outputStream.write(msg4.getBytes());
outputStream.write(32);}
//End of Signal Transmission
outputStream.write(k);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(a == 1)
{ a = 0;
list.add(new deviceListItem(msg, false));
}
if(b == 1)
{ b = 0;
list.add(new deviceListItem(msg2, false));
}
if(c == 1)
{ c = 0;
list.add(new deviceListItem(msg3, false));
}
if(d == 1)
{ d = 0;
list.add(new deviceListItem(msg4, false));
}
mAdapter.notifyDataSetChanged();
chatList.setSelection(list.size() - 1);
}
public void cancle() {
try {
socket.close();
} catch (IOException e) {
}
}
private class clientThread extends Thread {
public void run() {
try {
//
bdDevice = bluetoothAdapter.getRemoteDevice(BlueToothAddress);
socket = bdDevice.createRfcommSocketToServiceRecord(UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"));
Message msg2 = new Message();
msg2.obj = "Please wait, connecting to server: "
+ BlueToothAddress;
msg2.what = 0;
LinkDetectedHandler.sendMessage(msg2);
socket.connect();
Log.i("tag", "This is the pairing section");
Message msg = new Message();
msg.obj = "Device connected. Sending message is allowed.";
msg.what = 0;
LinkDetectedHandler.sendMessage(msg);
readThread = new readThread();
readThread.start();
click++;
} catch (IOException e) {
Message msg = new Message();
msg.obj = "Error! Can't connect to device. Please try again.";
msg.what = 0;
LinkDetectedHandler.sendMessage(msg);
click--;
}
}
};
private Handler LinkDetectedHandler = new Handler() {
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), (String) msg.obj,
Toast.LENGTH_SHORT).show();
if (msg.what == 1) {
list.add(new deviceListItem((String) msg.obj,true));
} else {
list.add(new deviceListItem((String) msg.obj, false));
}
mAdapter.notifyDataSetChanged();
chatList.setSelection(list.size() - 4);
}
};
private class readThread extends Thread {
public void run() {
byte[] buffer = new byte[1024];
int bytes;
InputStream mmInStream = null;
String tmp = null;
try {
mmInStream = socket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
try {
// read the data from the inputStream
if ((bytes = mmInStream.read(buffer)) > 0)
{
for (int i = 0; i < bytes; i++) {
tmp = "" + buffer[i];
String st = new String(tmp);
tmp = null;
Message msg = new Message();
msg.obj = st;
msg.what = 1;
}
}
} catch (IOException e) {
try {
mmInStream.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
}
}
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// Cancel discovery because it's costly and we're about to connect
bluetoothAdapter.cancelDiscovery();
System.out.println("Bluetooth Adapter2 = "+bluetoothAdapter.cancelDiscovery());
SiriListItem item = delist.get(arg2);
mAdapter.notifyDataSetChanged();
// When device being clicked
count++;
click = 1;
// Get the device MAC address, which is the last 17 chars in the
// View
String info = item.message;
String address = info.substring(info.length() - 17);
BlueToothAddress = address;
if (click == 1) {
clientThread ct = new clientThread();
ct.start();
}
};
};
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
unregisterReceiver(myReceiver);
super.onDestroy();
}
}
我不确定,什么变量或如何将所需的变量分配到SharedPreferences中以允许我在应用程序上始终保持连接状态。简而言之,当我连接一次时,始终保持联系。我希望有人可以帮助我。
提前致谢。
答案 0 :(得分:0)
SDK中有蓝牙示例。如果您遵循它,您将看到他们正在服务中执行蓝牙操作,并且活动连接到该服务。无论您的程序在何时运行,服务都会保持活动状态。