文章主要是想记录下自己学习蓝牙的过程,这也是结合了几个大神的博客才做出来一点点,主要是因为这是前段时间做的,想要继续或者从新做的时候,发现部分东西已经忘记,本想打开原来收藏的蓝牙的文章,才发现忘记收藏了。。。。不应该啊!!!所以就拿自己的源码记录下来,如果有所相似,还望见谅,都是想让自己更多进步嘛。
上代码:
首先--加权限
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
package com.example.litsoft.buletooth;
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.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity implements View.OnClickListener {
private static String TAG = "MainActivity";
private Button btOpen, btClose, btOpenBySystem, btDiscoveryDevice, btCancelDiscovery, btDiscoveryBySystem,continueSao;
private BluetoothAdapter mBluetoothAdapter; // 本机蓝牙适配器对象
private final int REQUEST_OPEN_BT_CODE = 1;
private final int REQUEST_DISCOVERY_BT_CODE = 2;
private TextView tv1,tv2;
private List<bean> aa = new ArrayList() ;
LinearLayout llyy;
// private ListView lview;
private com.example.litsoft.buletooth.BluetoothAdapter adapter;
private static final int CONTUIN = 1;
private static final int UNCONTUIN = 2;
private TextView tv1_tv,tv2_tv;
short rssi;
MediaPlayer mPlayer = null;
short s_a = -70;
short l_a = -75;
private TextView testrssi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
setContentView(R.layout.activity_main);
// 设置横屏显示
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
initViews();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // 获得本机蓝牙适配器对象引用
if (mBluetoothAdapter == null) {
toast("对不起 ,您的机器不具备蓝牙功能");
return;
}
IntentFilter bluetoothFilter = new IntentFilter();
bluetoothFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//蓝牙状态值发生改变
bluetoothFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);//蓝牙扫描状态(SCAN_MODE)发生改变
this.registerReceiver(BluetoothReciever, bluetoothFilter);
//蓝牙扫描相关设备
IntentFilter btDiscoveryFilter = new IntentFilter();
btDiscoveryFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//蓝牙扫描过程开始
btDiscoveryFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//蓝牙扫描过程结束
btDiscoveryFilter.addAction(BluetoothDevice.ACTION_FOUND);//蓝牙扫描时,扫描到任一远程蓝牙设备时,会发送此广播。
btDiscoveryFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
this.registerReceiver(BTDiscoveryReceiver, btDiscoveryFilter);
int initialBTState = mBluetoothAdapter.getState();
printBTState(initialBTState); // 初始时蓝牙状态
}
Handler mHanler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case CONTUIN:
mBluetoothAdapter.startDiscovery();
Message m = mHanler.obtainMessage();
m.what = UNCONTUIN;
mHanler.sendMessageDelayed(m,1000);
break;
case UNCONTUIN:
mBluetoothAdapter.cancelDiscovery();
sendMessageL(CONTUIN);
break;
}
}
};
private void sendMessageL(int tagP){
Message msg = new Message();
msg.what = tagP;
mHanler.sendMessage(msg);
}
private void initViews() {
// lview = (ListView) findViewById(R.id.lview);
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
tv1_tv = (TextView) findViewById(R.id.tv1_tv);
tv2_tv = (TextView) findViewById(R.id.tv2_tv);
btOpen = (Button) findViewById(R.id.btOpen);
btClose = (Button) findViewById(R.id.btClose);
btOpenBySystem = (Button) findViewById(R.id.btOpenBySystem);
btDiscoveryDevice = (Button) findViewById(R.id.btDiscoveryDevice);
btCancelDiscovery = (Button) findViewById(R.id.btCancelDiscovery);
btDiscoveryBySystem = (Button) findViewById(R.id.btDiscoveryBySystem);
continueSao = (Button) findViewById(R.id.continueSao);
btOpen.setOnClickListener(this);
btClose.setOnClickListener(this);
btOpenBySystem.setOnClickListener(this);
btDiscoveryDevice.setOnClickListener(this);
btCancelDiscovery.setOnClickListener(this);
btDiscoveryBySystem.setOnClickListener(this);
continueSao.setOnClickListener(this);
testrssi = (TextView) findViewById(R.id.testrssi);
}
@Override
public void onClick(View v) {
boolean wasBtOpened = mBluetoothAdapter.isEnabled(); // 是否已经打开
switch (v.getId()) {
case R.id.btOpen:// 打开
boolean result = mBluetoothAdapter.enable();
if (result)
toast("蓝牙打开操作成功");
else if (wasBtOpened)
toast("蓝牙已经打开了");
else
toast("蓝牙打开失败");
break;
case R.id.btClose:// 关闭
boolean result1 = mBluetoothAdapter.disable();
if (result1)
toast("蓝牙关闭操作成功");
else if (!wasBtOpened)
toast("蓝牙已经关闭");
else
toast("蓝牙关闭失败.");
break;
case R.id.btOpenBySystem://调用系统API打开蓝牙设备
if (!wasBtOpened) //未打开蓝牙,才需要打开蓝牙
{
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_OPEN_BT_CODE);
} else
toast("Hi ,蓝牙已经打开了,不需要在打开啦 ~~~");
break;
case R.id.btDiscoveryDevice://扫描时,必须先打开蓝牙
if (!mBluetoothAdapter.isDiscovering()) {
Log.i(TAG, "btCancelDiscovery ### the bluetooth dont't discovering");
toast("蓝牙无法找到~");
mBluetoothAdapter.startDiscovery();
} else
toast("蓝牙正在搜索设备了 ---- ");
break;
case R.id.btCancelDiscovery://取消扫描
if (mBluetoothAdapter.isDiscovering()) {
Log.i(TAG, "btCancelDiscovery ### the bluetooth is isDiscovering");
mBluetoothAdapter.cancelDiscovery();
//-----停止时进行列表的清空,刷新listview
aa.clear();
adapter.notifyDataSetChanged();
} else
toast("蓝牙并未搜索设备 ---- ");
//-----停止时进行列表的清空,刷新listview
aa.clear();
adapter.notifyDataSetChanged();
break;
case R.id.btDiscoveryBySystem://使蓝牙能被扫描
Intent discoveryintent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryintent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivityForResult(discoveryintent, REQUEST_DISCOVERY_BT_CODE);
break;
case R.id.continueSao:
if(!mBluetoothAdapter.isDiscovering()){
sendMessageL(CONTUIN);
}
break;
}
}
//蓝牙开个状态以及扫描状态的广播接收器
private BroadcastReceiver BluetoothReciever = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {//开关模式变化广播
Log.v(TAG, "### Bluetooth State has changed ##");
int btState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.STATE_OFF);
printBTState(btState);
} else if (BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(intent.getAction())) {//扫描模式变化广播
Log.v(TAG, "### ACTION_SCAN_MODE_CHANGED##");
int cur_mode_state = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.SCAN_MODE_NONE);//该蓝牙不能扫描以及被扫描
int previous_mode_state = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_SCAN_MODE, BluetoothAdapter.SCAN_MODE_NONE);
Log.v(TAG, "### cur_mode_state ##" + cur_mode_state + " ~~ previous_mode_state" + previous_mode_state);
}
}
};
//蓝牙扫描时的广播接收器
public BroadcastReceiver BTDiscoveryReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(intent.getAction())) { //蓝牙扫描过程开始
Log.v(TAG, "### BT ACTION_DISCOVERY_STARTED ##");
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())) { //蓝牙扫描过程结束
Log.v(TAG, "### BT ACTION_DISCOVERY_FINISHED ##");
} else if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {//发现远程设备,蓝牙扫描时,扫描到任一远程蓝牙设备时,会发送此广播
Log.v(TAG, "### BT BluetoothDevice.ACTION_FOUND ##");
BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// if (btDevice != null)
Log.v(TAG, "Name : " + btDevice.getName() + " Address: " + btDevice.getAddress());
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 搜索到的不是已经绑定的蓝牙设备
bean b = new bean();
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
// 显示在TextView上
aa.clear();
b.setName(device.getName());
b.setAdress(device.getAddress());
rssi = intent.getExtras().getShort(
BluetoothDevice.EXTRA_RSSI);
Log.v(TAG, "Name : " + device.getName() + " Address: " + device.getAddress() + "rssi:" + rssi + "");
b.setStrong(rssi);
aa.add(b);
if(device.getName().equals("XXXXXX_4FC6")){
tv1_tv.setText("Name : " + b.getName() + " Address: " + b.getAdress() + "rssi:" + b.getStrong() + "");
/*if( rssi >= l_a) {
testrssi.setText("接近XXXXXX_4FC6"+"-----强度"+rssi);
}else{
testrssi.setText("");
}*/
}else if(device.getName().equals("<span style="font-family: Arial, Helvetica, sans-serif;">XXXXXX_4FC6</span><span style="font-family: Arial, Helvetica, sans-serif;">")){</span>
tv2_tv.setText("Name : " + b.getName() + " Address: " + b.getAdress() + "rssi:" + b.getStrong() + "");
/* if(rssi >= l_a) {
Log.e("start_video","start music-------------ing----"+rssi);
testrssi.setText("接近XXXXXX_4FC5"+"-----强度"+rssi);
}else{
testrssi.setText("");
}*/
}
}
} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction())) {//指明一个远程设备的连接状态的改变
Log.v(TAG, "### BT ACTION_BOND_STATE_CHANGED ##");
int cur_bond_state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE);
int previous_bond_state = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.BOND_NONE);
Log.v(TAG, "### cur_bond_state ##" + cur_bond_state + " ~~ previous_bond_state" + previous_bond_state);
}
}
};
//请求码
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_OPEN_BT_CODE) {
if (resultCode == RESULT_CANCELED) {
toast("Sorry , 用户拒绝了您的打开蓝牙请求.");
} else
toast("Year , 用户允许了您的打开蓝牙请求.");
} else if (requestCode == REQUEST_DISCOVERY_BT_CODE) {
if (resultCode == RESULT_CANCELED) {
toast("Sorry , 用户拒绝了,您的蓝牙不能被扫描.");
} else
toast("Year , 用户允许了,您的蓝牙能被扫描");
}
}
private void printBTState(int btState) {
switch (btState) {
case BluetoothAdapter.STATE_OFF:
toast("蓝牙状态:已关闭");
Log.v(TAG, "BT State : BluetoothAdapter.STATE_OFF ###");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
toast("蓝牙状态:正在关闭");
Log.v(TAG, "BT State : BluetoothAdapter.STATE_TURNING_OFF ###");
break;
case BluetoothAdapter.STATE_TURNING_ON:
toast("蓝牙状态:正在打开");
Log.v(TAG, "BT State :BluetoothAdapter.STATE_TURNING_ON ###");
break;
case BluetoothAdapter.STATE_ON:
toast("蓝牙状态:已打开");
Log.v(TAG, "BT State :BluetoothAdapter.STATE_ON ###");
break;
default:
break;
}
}
private void toast(String str) {
Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(BluetoothReciever);
unregisterReceiver(BTDiscoveryReceiver);
}
}
好了,差不多就这些了。以后会继续加。。。。
哦。有些数据是别的需要的,我都尽量删除了,可能会有所遗漏