一、例程简介
1、应用界面图(主界面、设置界面)
2、实现功能:
(1)打开应用,显示主界面,检测蓝牙功能是否打开,否则询问打开;
(2)打开蓝牙功能后,点击“连接设备:”下的按钮选择已匹配的蓝牙设备进行连接;
(3)若蓝牙设备未匹配,可点击旁边的 […] 按钮打开系统蓝牙设置界面,进行蓝牙匹配;
(4)点击中央的上、下、左、右和中间按钮,可发送不同的蓝牙字符串消息;
(5)蓝牙消息内容可通过点击 [设置] 按钮在设置界面中设置,设置的数据重启应用后依然有效;
(6)其中,中间按钮具有长按按下、长按释放和点击三种不同效果;
(7)本应用还附带来电监听功能,有来电时,会自动发送蓝牙消息;
(8)点击 [退出] 按钮,关闭蓝牙连接,并且关闭安卓设备蓝牙功能。
二、工程目录
三、主界面代码
MainActivity.java
package com.example.z.buletoothdemo;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
public final static String TAG = "MainActivity";
private Button bdevice;
private EditText emessage;
private Button btmid;
private BluetoothAdapter ba;
private ArrayList lname = new ArrayList<>();
private ArrayList laddress = new ArrayList<>();
private String sdname;
private String sdaddress;
private BluetoothSocket bsocket = null;
private OutputStream ostream = null;
private InputStream istream = null;
private static final UUID SerialPort_UUID = UUID.fromString(
"00001101-0000-1000-8000-00805F9B34FB");
private Handler hd;
private ReceiveThread rt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bdevice = (Button) findViewById(R.id.btn_dev_name);
emessage = (EditText) findViewById(R.id.et_message);
btmid = (Button)findViewById(R.id.btn_mid);
btmid.setOnTouchListener(new MidOnTouchListener());
ba = BluetoothAdapter.getDefaultAdapter();
hd = new Handler() {
public void handleMessage(Message msg)
{
super.handleMessage(msg);
if(msg.what == 111) {
SharedPreferences preferences = getSharedPreferences(
"messages", MODE_PRIVATE);
String ms = preferences.getString("msg_mlg", "5");
SendStr(ms);
}else if(msg.what == 112) {
emessage.setText(Arrays.toString((byte[])msg.obj));
emessage.setEnabled(true);
}
}
};
// When "Device does not support Bluetooth"
if (ba == null) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.dev_nsup_bt),
Toast.LENGTH_SHORT).show();
}
// When Bluetooth hasn't opened, enable it
if (!ba.isEnabled()) {
Intent turnOn = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
}
}
// Function to send Bluetooth message
public void SendStr(String str) {
byte[] bf = new byte[33];
bf = str.getBytes();
if((!str.equals("")) && (bsocket!=null)) {
try {
ostream = bsocket.getOutputStream();
ostream.write(bf);
ostream.write('\0'); // Send an ending sign
} catch (IOException e) {
e.printStackTrace();
}
try {
if (ostream != null) {
ostream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
emessage.setText("");
}
}
// Thread to receive Bluetooth message
public class ReceiveThread extends Thread {
BluetoothSocket tsocket;
public ReceiveThread(BluetoothSocket socket) {
this.tsocket = socket;
InputStream tistream = null;
try {
tistream = socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
istream = tistream;
}
@Override
public void run() {
byte[] buffer = new byte[32];
String str;
// Keep on receiving
while (true) {
try {
istream.read(buffer);
str = new String(buffer,"UTF-8");
buffer = new byte[32];
Message msg = hd.obtainMessage(112,str);
hd.sendMessage(msg);
} catch (IOException e) {
try {
if (istream != null) {
istream.close();
}
break;
} catch (IOException e1) {
e1.printStackTrace();
}
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// Listener to catch the RINGING STATE
class MyPhoneStateListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
Log.i(TAG, "in coming number:" + incomingNumber);
if(state == TelephonyManager.CALL_STATE_RINGING) {
SharedPreferences preferences = getSharedPreferences(
"messages", MODE_PRIVATE);
String ms = preferences.getString("msg_ring", "0");
SendStr(ms);
}
super.onCallStateChanged(state, incomingNumber);
}
}
// Function of the ChooseDev Button
public void ChooseDevOnClick(View Source) {
Set sdevices;
// Clear data of scanning
lname.clear();
laddress.clear();
// Get data of boned devices
sdevices = ba.getBondedDevices();
if (sdevices.size() > 0) {
for (BluetoothDevice btd : sdevices) {
lname.add(btd.getName());
laddress.add(btd.getAddress());
System.out.println(btd.getName() + btd.getAddress());
}
}
// Prepare data for the list of Bluetooth devices
int size = lname.size();
final String[] snames = new String[size];
final String[] saddresses = new String[size];
for (int i = 0; i < size; i++) {
snames[i] = lname.get(i);
saddresses[i] = laddress.get(i);
}
// Buld AlertDialog of the list of Bluetooth devices
AlertDialog.Builder ab = new AlertDialog.Builder(MainActivity.this);
ab.setTitle(getResources().getString(R.string.choose_bt_dev));
ab.setItems(snames, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The name and address of the chosen device
sdname = snames[which];
sdaddress = saddresses[which];
// Connect to chosen device
BluetoothDevice device = ba.getRemoteDevice(sdaddress);
try {
bsocket = device.createRfcommSocketToServiceRecord(
SerialPort_UUID);
ba.cancelDiscovery();
bsocket.connect();
// Set a phone state listener
TelephonyManager tm = (TelephonyManager)getSystemService(
Context.TELEPHONY_SERVICE);
tm.listen(new MyPhoneStateListener(),
PhoneStateListener.LISTEN_CALL_STATE);
// Start a thread to receive bluetooth message
rt = new ReceiveThread(bsocket);
rt.start();
} catch (IOException e) {
// Set fail message
sdname = getResources().getString(R.string.con_fail);
try {
bsocket.close();
bsocket = null;
} catch (IOException e2) {
e2.printStackTrace();
}
e.printStackTrace();
}
// Show result of connection
bdevice.setText(sdname);
}
});
// Pop the list AlertDialog
ab.create().show();
}
// Function of the Exit Button
public void ExitOnClick(View Source) {
if(bsocket != null)
try {
bsocket.close();
}catch (IOException e) {
e.printStackTrace();
}
// Close Bluetooth
ba.disable();
MainActivity.this.finish();
}
// OnTouchListener for Mid Button
class MidOnTouchListener implements View.OnTouchListener {
private int long_pressed = 0;
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
// Thread to test long pressed
Thread t = new Thread() {
@Override
public void run() {
super.run();
try {
Thread.sleep(250);
}catch (InterruptedException e)
{
e.printStackTrace();
}
// test flag
if(long_pressed == 0) {
long_pressed = 1; // Set flag
hd.sendEmptyMessage(111); // Do long-pressed-action
}else {
long_pressed = 0;
}
}
};
t.start();
}
if(event.getAction() == MotionEvent.ACTION_UP){
if(long_pressed == 0) { // Flag not set, do click-action
long_pressed = -1;
SharedPreferences preferences = getSharedPreferences(
"messages", MODE_PRIVATE);
String ms = preferences.getString("msg_msh", "0");
SendStr(ms);
}else if(long_pressed == 1) { // Long pressed end
SharedPreferences preferences = getSharedPreferences(
"messages", MODE_PRIVATE);
String ms = preferences.getString("msg_mup", "6");
SendStr(ms);
long_pressed = 0;
}
}
return false;
}
}
// Function of Up Button
public void UpOnClick(View Source) {
SharedPreferences preferences = getSharedPreferences(
"messages", MODE_PRIVATE);
String ms = preferences.getString("msg_up", "1");
SendStr(ms);
}
// Function of Down Button
public void DownOnClick(View Source) {
SharedPreferences preferences = getSharedPreferences(
"messages", MODE_PRIVATE);
String ms = preferences.getString("msg_down", "3");
SendStr(ms);
}
// Function of Left Button
public void LeftOnClick(View Source) {
SharedPreferences preferences = getSharedPreferences(
"messages", MODE_PRIVATE);
String ms = preferences.getString("msg_left", "4");
SendStr(ms);
}
// Function of Right Button
public void RightOnClick(View Source) {
SharedPreferences preferences = getSharedPreferences(
"messages", MODE_PRIVATE);
String ms = preferences.getString("msg_right", "2");
SendStr(ms);
}
// Function of Send Button
public void BtnSendOnClick(View Source) {
String str = emessage.getText().toString();
SendStr(str);
}
// When "…" Button clicked, open system activity to Bluetooth settings
public void SearchOnClick(View Source) {
startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
}
// When Settings Button clicked, open SettingsActivity
public void SettingsOnClick(View Source) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
}
SettingsActivity.java
package com.example.z.buletoothdemo;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
/**
* Created by Z on 2016/5/26.
*/
public class SettingsActivity extends AppCompatActivity {
private EditText etup;
private EditText etdown;
private EditText etleft;
private EditText etright;
private EditText etmsh;
private EditText etmlg;
private EditText etmup;
private EditText etring;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
etup = (EditText)findViewById(R.id.et_up);
etdown = (EditText)findViewById(R.id.et_down);
etleft = (EditText)findViewById(R.id.et_left);
etright = (EditText)findViewById(R.id.et_right);
etmsh = (EditText)findViewById(R.id.et_msh);
etmlg = (EditText)findViewById(R.id.et_mlg);
etmup = (EditText)findViewById(R.id.et_mup);
etring = (EditText)findViewById(R.id.et_ring);
SharedPreferences preferences = getSharedPreferences("messages", MODE_PRIVATE);
etup.setText(preferences.getString("msg_up","1"));
etdown.setText(preferences.getString("msg_down","3"));
etleft.setText(preferences.getString("msg_left","4"));
etright.setText(preferences.getString("msg_right","2"));
etmsh.setText(preferences.getString("msg_msh","0"));
etmlg.setText(preferences.getString("msg_mlg","5"));
etmup.setText(preferences.getString("msg_mup","6"));
etring.setText(preferences.getString("msg_ring","0"));
}
public void SaveOnClick(View Source) {
SharedPreferences preferences = getSharedPreferences("messages", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("msg_up",etup.getText().toString());
editor.putString("msg_down",etdown.getText().toString());
editor.putString("msg_left",etleft.getText().toString());
editor.putString("msg_right",etright.getText().toString());
editor.putString("msg_msh",etmsh.getText().toString());
editor.putString("msg_mlg",etmlg.getText().toString());
editor.putString("msg_mup",etmup.getText().toString());
editor.putString("msg_ring",etring.getText().toString());
editor.apply();
// Close SettingsActivity
finish();
}
}
activity_main.xml
activity_settings.xml
BluetoothUnv
CONNECTED DEVICE:
(PLEASE CHOOSE)
SETTINGS
EXIT
SEND
SAVE
...
32 CHARACTERS LIMITED
Device does not support Bluetooth
(CONNECTION FAILED)
CHOOSE BLUETOOTH DEVICE
UP
DOWN
LEFT
RIGHT
MID-CLICK
MID-PRESS
MID-RELEASE
CALL_RINGING
default "1"
default "3"
default "4"
default "2"
default "0"
default "5"
default "6"
default "0"
八、AndroidManifest.xml
包括drawable文件夹中的一些.xml和.png,values文件夹下的colors.xml、dimens.xml和styles.xml,等。
十、代码下载
本项目代码已上传至“CODE”,地址:
https://code.csdn.net/sinat_30685475/bluetoothunv/tree/master
已上传至“下载”,地址:
http://download.csdn.net/detail/sinat_30685475/9595483