如果本地的藍牙設備可以被附近的其它藍牙設備發現,可以使用下面的方法,代碼中有註釋。
當然需要你的藍牙設備設置一下,可以被附近的藍牙設備檢測到(一般爲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>
運行結果: