如果本地的蓝牙设备可以被附近的其它蓝牙设备发现,可以使用下面的方法,代码中有注释。
当然需要你的蓝牙设备设置一下,可以被附近的蓝牙设备检测到(一般为2分钟)
在设置-蓝牙中-选中可检测性复选框。我的数据时android4.1.1,手机厂家不同或版本不同,可能有所不同。
eg:
JAVA:代码:
package com.example.enabling_discoverability_bluetooth;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "本机没有找到蓝牙硬件或驱动!", Toast.LENGTH_SHORT).show();
finish();
}
// 如果允许本地蓝牙被附近的其它蓝牙设备发现,如果没有打开,就先打开蓝牙设备
// 设置让自己的手机被其他蓝牙设备发现
// 如果需要用户确认操作,不需要获取底层蓝牙服务实例,可以通过一个Intent来传递ACTION_REQUEST_DISCOVERABLE参数,
// 这里通过startActivityForResult来强制获取一个结果,重写onActivityResult()方法获取执行结果,
// 返回结果有RESULT_OK和RESULT_CANCELLED分别代表开启和取消(失败)
Intent mIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(mIntent, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "允许本地蓝牙被附近的其它蓝牙设备发现", Toast.LENGTH_SHORT)
.show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "不允许蓝牙被附近的其它蓝牙设备发现", Toast.LENGTH_SHORT)
.show();
finish();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
配置文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.enabling_discoverability_bluetooth"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<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="com.example.enabling_discoverability_bluetooth.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>
运行结果: