Android蓝牙广播接收器无法正常工作

时间:2016-08-04 22:42:26

标签: android android-studio bluetooth

我想构建一个应用程序,通过蓝牙查找可用的设备有Tact of manifest,我没有在ListView中显示我的设备,我不知道是什么问题?

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ArrayAdapter<String> item = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1);
        final Switch sw =(Switch) findViewById(R.id.switch1);
        final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        final ListView lv =(ListView)findViewById(R.id.listView);
        final Button bu= (Button)findViewById(R.id.button);

    sw.setChecked(false);
    sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             if (!mBluetoothAdapter.isEnabled()&&sw.isChecked())
             {
                 mBluetoothAdapter.enable();

                 Toast.makeText(MainActivity.this, " Bluetooth  enabled", Toast.LENGTH_SHORT).show();
             }
             else if(mBluetoothAdapter.isEnabled()&&!sw.isChecked()) {
                 mBluetoothAdapter.disable();
                 Toast.makeText(MainActivity.this, "Bluetooth disabled", Toast.LENGTH_SHORT).show();
             }
        }
    });

    bu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                      if (!sw.isChecked())
                          item.clear();
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    item.add(device.getName() + "\n" + device.getAddress());

                }


            }
            mBluetoothAdapter.startDiscovery();
            final BroadcastReceiver   ActionFoundReceiver=new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();

                    if (BluetoothDevice.ACTION_FOUND.equals(action))
                    {
                        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                        item.add(device.getName()+"\n"+device.getAddress());
                        Toast.makeText(MainActivity.this, device.getName(), Toast.LENGTH_SHORT).show();



                    }
                }
            };
            lv.setAdapter(item);

        }

    });
}

}

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些问题:

  • 您尚未注册BroadcastReceiver课程。

  • ArrayAdapter添加项目后,您应该调用notifyDataSetChanged的{​​{1}}方法。此方法调用使ListView更新。