简单得蓝牙连接
public class MainActivity extends Activity {
// 成员变量
BluetoothAdapter adapter;
private ListView lv;
private String str;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 找到控件
tv = (TextView) findViewById(R.id.tv);
// 获取蓝牙适配器
adapter = BluetoothAdapter.getDefaultAdapter();
// 打开蓝牙
adapter.enable();
// 关闭蓝牙
adapter.disable();
// 得到蓝牙的设备状态
adapter.getState();
}
// 打开蓝牙方法
public void turnOn(View view) {
// 判断蓝牙是否开启
// if (adapter.isEnabled()) {
// Toast.makeText(MainActivity.this, "蓝牙已开启", Toast.LENGTH_SHORT)
// .show();
// } else {
// // 否则调用蓝牙
// adapter.enable();
// }
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600);
startActivity(intent);
}
public void shebei(View view) {
// 获得蓝牙配对的设备
Object[] objects = adapter.getBondedDevices().toArray();
// 循环取到每一个设备
for (int i = 0; i < objects.length; i++) {
BluetoothDevice device = (BluetoothDevice) objects[i];
str = "配对的设备名字:|" + device.getName() + "|" + device.getAddress()+device;
tv.setText(str);
}
adapter.startDiscovery();
}
//配对蓝牙设备
public void peidui(View view) {
//蓝牙发送action
Intent intent=new Intent(Intent.ACTION_SEND);
//设置mime类型
intent.setType("*/*");
//要传的文件
File file=new File(Environment.getExternalStorageDirectory()+"/sw.jpg");
//设置文件流
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
startActivity(intent);
}
}
布局文件
<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" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="turnOn"
android:text="打开蓝牙" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="shebei"
android:text="获取蓝牙设备" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="peidui"
android:text="配对蓝牙设备" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>