您的位置:首页 > 产品设计 > UI/UE

蓝牙自动打开并配对

2015-12-15 15:43 826 查看
主程序:
import java.util.Set;
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.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.guide.bluetooth.ClsUtils;

public class BluetoothActivity extends Activity {
private String TAG = "BluetoothTest ";
private static boolean noFound = true;
private final static int MSG_BLUETOOTH_SCAN = 1;
private Button skip;
private TextView showpro;
/* 取得默认的蓝牙适配器 */
private BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth);
if (!mBtAdapter.isEnabled()) {
mBtAdapter.enable();
Log.e(TAG, "bluetooth enable");
}
// 注册扫描广播
IntentFilter discoveryFilter = new IntentFilter();
discoveryFilter.addAction(BluetoothDevice.ACTION_FOUND);
// discoveryFilter.addAction(BluetoothDevice.ACTION_FOUND);
discoveryFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, discoveryFilter);
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
// 打印已绑定设备
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
Log.e(TAG + "------>", device.getName() + "\n" + device.getAddress());
}
} else {
Log.e(TAG, "MEI YOU PEI DUI SHE BEI");
}

mhandler.sendEmptyMessageDelayed(MSG_BLUETOOTH_SCAN, 1000);

skip = (Button) findViewById(R.id.skip);
showpro=(TextView)findViewById(R.id.bluetooth);
skip.setOnClickListener( new OnClickListener() {

@Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(BluetoothActivity.this,
GuideFirstNetworkActivity.class);
startActivity(intent);
finish();
}
});
}

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();

// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed
// already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
if (device.getName().equals("HBG BLE REMOTE")) {
try {
ClsUtils.createBond(device.getClass(), device);
// ClsUtils.cancelPairingUserInput(device.getClass(),
// device);
noFound = false;
showpro.setText("恭喜!连接成功");
Intent intentwire = new Intent();
intentwire.setClass(context,
GuideFirstNetworkActivity.class);
startActivity(intentwire);
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG,
device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action)) {
if (noFound) {
mBtAdapter.startDiscovery();

Log.e(TAG, "device has not found");
} else {
noFound = false;
mBtAdapter.cancelDiscovery();
Log.e(TAG, "device has found");
}
}
}
}

};
@Override
protected void onResume() {

mhandler.sendEmptyMessageDelayed(MSG_BLUETOOTH_SCAN, 1000);

super.onResume();
}

@Override
public void onDestroy() {
super.onDestroy();

// Make sure we're not doing discovery anymore
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}

Handler mhandler = new Handler() {

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
switch (msg.what) {
case MSG_BLUETOOTH_SCAN:
doScan();
if(noFound){
mhandler.sendEmptyMessage(MSG_BLUETOOTH_SCAN);
}
break;
default:
super.handleMessage(msg);
}
}
};

private void doScan() {
Log.e(TAG, "doscan...");
showpro.setText("正在扫描蓝牙遥控器设备...");
mBtAdapter.startDiscovery();
}

public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

}
ClsUtils.java
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import android.bluetooth.BluetoothDevice;
import android.util.Log;

public class ClsUtils {
/**
* 与设备配对 参考源码:platform/packages/apps/Settings.git
* /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
*/
static public boolean createBond(Class btClass, BluetoothDevice btDevice)
throws Exception
{
Method createBondMethod = btClass.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}

/**
* 与设备解除配对 参考源码:platform/packages/apps/Settings.git
* /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
*/
static public boolean removeBond(Class btClass, BluetoothDevice btDevice)
throws Exception
{
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}

static public boolean setPin(Class btClass, BluetoothDevice btDevice,
String str) throws Exception
{
try
{
Method removeBondMethod = btClass.getDeclaredMethod("setPin",
new Class[]
{byte[].class});
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice,
new Object[]
{str.getBytes()});
Log.e("returnValue", "" + returnValue);
}
catch (SecurityException e)
{
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;

}

// 取消用户输入
static public boolean cancelPairingUserInput(Class btClass,
BluetoothDevice device)

throws Exception
{
Method createBondMethod = btClass.getMethod("cancelPairingUserInput");
// cancelBondProcess()
Boolean returnValue = (Boolean) createBondMethod.invoke(device);
return returnValue.booleanValue();
}

// 取消配对
static public boolean cancelBondProcess(Class btClass,
BluetoothDevice device)

throws Exception
{
Method createBondMethod = btClass.getMethod("cancelBondProcess");
Boolean returnValue = (Boolean) createBondMethod.invoke(device);
return returnValue.booleanValue();
}

/**
*
* @param clsShow
*/
static public void printAllInform(Class clsShow)
{
try
{
// 取得所有方法
Method[] hideMethod = clsShow.getMethods();
int i = 0;
for (; i < hideMethod.length; i++)
{
Log.e("method name", hideMethod[i].getName() + ";and the i is:"
+ i);
}
// 取得所有常量
Field[] allFields = clsShow.getFields();
for (i = 0; i < allFields.length; i++)
{
Log.e("Field name", allFields[i].getName());
}
}
catch (SecurityException e)
{
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
// throw new RuntimeException(e.getMessage());
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Bluetooth.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bluetooth"
tools:context=".BluetoothActivity" >

<TextView
android:id="@+id/bluetooth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:textColor="@color/white"
android:textSize="40sp" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:layout_marginLeft="100dp"
android:text="@string/pleaseback"
android:textColor="@color/white"
android:textSize="40sp" />

</RelativeLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android bluetooth class