34蓝牙操作

基本的蓝牙操作:

包括:打开,关闭,搜索,配对,我的蓝牙信息,初步连接。就差一个通信了。通信下一篇写。

主要用到包:android.bluetooth

主要用到类:BluetoothAdapter BluetoothDevice BluetoothServerSocket BluetoothSocket

代码:

MainActivity.java

package com.study.ibluetooth;

import java.io.OutputStream;
import java.lang.reflect.Method;

import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private static int CODE = 1;
	private TextView show;
	private Button start, stop, discovery, mine, pair, connect;
	private BluetoothAdapter adapter = null;
	private String address = null;
	private BluetoothDevice remoteDevice;
	public static final String UUID_CONTENT = "00001101-0000-1000-8000-00805F9B34FB";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		show = (TextView) findViewById(R.id.show);
		start = (Button) findViewById(R.id.start);
		stop = (Button) findViewById(R.id.stop);
		discovery = (Button) findViewById(R.id.discovery);
		mine = (Button) findViewById(R.id.mine);
		pair = (Button) findViewById(R.id.pair);
		connect = (Button) findViewById(R.id.connect);

		adapter = BluetoothAdapter.getDefaultAdapter();

		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		registerReceiver(receiver, filter);

		start.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (adapter != null) {
					if (!adapter.isEnabled()) {
						Intent intent = new Intent(
								BluetoothAdapter.ACTION_REQUEST_ENABLE);
						startActivityForResult(intent, CODE);
					}
				} else {
					Toast.makeText(MainActivity.this, "您的设备不支持蓝牙",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		stop.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (adapter != null && adapter.isEnabled()) {
					adapter.disable();
				}
			}
		});

		mine.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (adapter != null) {
					String name = adapter.getName();
					String address = adapter.getAddress();
					show.setText("name:" + name + "\n" + "address" + address);
				}
			}
		});

		discovery.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (adapter != null) {
					adapter.startDiscovery();
				}
			}
		});

		pair.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				BluetoothDevice device = adapter.getRemoteDevice(address);
				if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
					try {
						autoBond(device.getClass(), device, "1");
						createBond(device.getClass(), device);
						remoteDevice = device;
					} catch (Exception e) {
					}
				} else {
					remoteDevice = device;
				}
			}
		});

		connect.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							UUID uuid = UUID.fromString(UUID_CONTENT);
							BluetoothSocket socket = remoteDevice
									.createRfcommSocketToServiceRecord(uuid);
							socket.connect();
							OutputStream out = socket.getOutputStream();
							if (out != null) {
								Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
								out.write("hello".getBytes());
							}
						} catch (Exception e) {
						}
					}
				}).start();

			}
		});
	}

	// 自动配对设置Pin值
	static public boolean autoBond(Class btClass, BluetoothDevice device,
			String strPin) throws Exception {
		Method autoBondMethod = btClass.getMethod("setPin",
				new Class[] { byte[].class });
		Boolean result = (Boolean) autoBondMethod.invoke(device,
				new Object[] { strPin.getBytes() });
		return result;
	}

	// 开始配对
	static public boolean createBond(Class btClass, BluetoothDevice device)
			throws Exception {
		Method createBondMethod = btClass.getMethod("createBond");
		Boolean returnValue = (Boolean) createBondMethod.invoke(device);
		return returnValue.booleanValue();
	}

	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (address == null) {
					address = device.getAddress();
				}
				show.setText(show.getText() + "\n" + device.getName() + " : "
						+ device.getAddress());
			}
		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		unregisterReceiver(receiver);
		super.onDestroy();
	}

}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/start"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="打开蓝牙" />

    <Button
        android:id="@+id/stop"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="关闭蓝牙" />

    <Button
        android:id="@+id/discovery"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="搜索蓝牙设备" />

    <Button
        android:id="@+id/mine"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="我的蓝牙设备" />
    <Button
        android:id="@+id/pair"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="配对第一个" />
    
	<Button
        android:id="@+id/connect"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="连接" />
	
    <TextView
        android:id="@+id/show"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="show" />

</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.study.ibluetooth"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柠檬李先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值