請嘗試下面的代碼。我認爲,這將通過裝置上顯示的細節和近::
1)AndroidManifest.xml中 - 下面添加的權限
uses-permission android:name="android.permission.BLUETOOTH"
uses-permission android:name="android.permission.BLUETOOTH_ADMIN"
2)MainActivity.java
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 12;
private TextView out;
private BluetoothAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
out = (TextView) findViewById(R.id.tvBluetoothInfo);
setBluetoothData();
if (Connections.blueTooth()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
out.setText("");
setBluetoothData();
}
private void setBluetoothData() {
// Getting the Bluetooth adapter
adapter = BluetoothAdapter.getDefaultAdapter();
out.append("\nAdapter: " + adapter.toString() + "\n\nName: "
+ adapter.getName() + "\nAddress: " + adapter.getAddress());
// Check for Bluetooth support in the first place
// Emulator doesn't support Bluetooth and will return null
if (adapter == null) {
Toast.makeText(this, "Bluetooth NOT supported. Aborting.",
Toast.LENGTH_LONG).show();
}
// Starting the device discovery
out.append("\n\nStarting discovery...");
adapter.startDiscovery();
out.append("\nDone with discovery...\n");
// Listing paired devices
out.append("\nDevices Pared:");
Set<BluetoothDevice> devices = adapter.getBondedDevices();
for (BluetoothDevice device : devices) {
out.append("\nFound device: " + device.getName() + " Add: "
+ device.getAddress());
}
}
}
3)連接。的java
import android.bluetooth.BluetoothAdapter;
public class Connections {
private static boolean state = false;
public static boolean blueTooth() {
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
if (!bluetooth.isEnabled()) {
System.out.println("Bluetooth is Disable...");
state = true;
} else if (bluetooth.isEnabled()) {
String address = bluetooth.getAddress();
String name = bluetooth.getName();
System.out.println(name + " : " + address);
state = false;
}
return state;
}
}
4)main.xml中
<TextView
android:id="@+id/tvBluetoothInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
你能簡單明瞭地告訴你到底想知道什麼嗎? – 7383