標籤:
之前寫的部落格都被移除了,也不知道什麼原因,可能是字型太少了,我不喜歡怎麼說,直接上源碼比較好一點
我相信程式員都這樣,除非代碼難懂就會去解說一下,
先看下:
看下java代碼
public class MainActivity extends Activity {private ListView lv;private BluetoothAdapter adapter;private MyReciver myReciver;private ArrayList<String> list;private ArrayAdapter<String> adapters;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);lv = (ListView) findViewById(R.id.lv);//2、得到適配器adapter = BluetoothAdapter.getDefaultAdapter();list = new ArrayList<String>();adapters = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1,list);lv.setAdapter(adapters);}public void da(View view){//3、開啟藍芽-----兩種方式:調用系統方式2、強行開啟if(!adapter.isEnabled()){//判斷是否開啟Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//請求被發現startActivityForResult(intent, 100);//開啟會返回資源}//if(!adapter.isEnabled()){//adapter.enable();//強行開啟//}//4、設定可見Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//設定可見intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//秒startActivity(intent);}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {// TODO Auto-generated method stubsuper.onActivityResult(requestCode, resultCode, data);if(resultCode==Activity.RESULT_OK){Toast.makeText(this, "已經開啟", 0).show();}else{Toast.makeText(this, "失敗", 0).show();}}public void sao(View view){list.clear();//5、掃描藍芽IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);myReciver = new MyReciver();registerReceiver(myReciver, intentFilter);//開始掃描adapter.startDiscovery();}public void guan(View view){if(adapter.isEnabled()){adapter.disable();//關閉藍芽}}public void cha(View view){//得到已經配對的Set<BluetoothDevice> devices = adapter.getBondedDevices();list.clear();for (BluetoothDevice bluetoothDevice : devices) {list.add(bluetoothDevice.getName()+"\n"+bluetoothDevice.getAddress());adapters.notifyDataSetChanged();}}class MyReciver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {// 當系統發現裝置就發送一次廣播,接收廣播,得到該藍牙裝置BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);if(!list.contains(device.getName()+"\n"+device.getAddress())){list.add(device.getName()+"\n"+device.getAddress());adapters.notifyDataSetChanged();}}}}
上面的基本都有注釋,不懂的可以聯絡我
使用藍芽是需要許可權的
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
android 藍芽的基本操作