2

私はアンドロイドが初めてで、ブルートゥース機能を備えたアプリケーションを作成しています。Bluetooth アダプターを設定して自分のデバイス情報を取得することはできますが、startdiscovery を使用して Bluetooth デバイスを検出することはできませんでした。スキャンを開始しても何もしません。

onclicklistner を使用してスキャンを開始しています。

  bt.setOnClickListener(new OnClickListener() {
           @Override
           public void onClick(View v) {
               if (!(bluetooth.isEnabled())) {
                   status = "Bluetooth is not Enabled.";
                   Toast.makeText(AddUser.this, status, Toast.LENGTH_LONG).show();
                   Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);

                }
                else
                {

                    scand();
                }

           }

これは、「public void onCreate」関数の直後に配置した onActivityResult 関数です。

 protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    System.out.println(resultCode);
    if (resultCode ==  RESULT_CANCELED) {
        status="Error Enabling bluetooth";
        Toast.makeText(AddUser.this, status, Toast.LENGTH_LONG).show();
    } else {

            scand();
    }



}

これは私のscand関数で、startdiscoveryを呼び出しています:

    private void scand()
{



   bluetooth.startDiscovery(); 
   Log.d("itmes", ""+items.size());
   item1 = new String[items.size()];
   item1 = items.toArray(item1);
   AlertDialog.Builder builder = new AlertDialog.Builder(this);
   builder.setTitle("Choose a device");
   builder.setItems(item1, new DialogInterface.OnClickListener() {

       public void onClick(DialogInterface dialog, int item) {
            Toast.makeText(getApplicationContext(), item1[item], Toast.LENGTH_SHORT).show();

       }

    });

    AlertDialog alert = builder.create();

    alert.show();

}

これはブロードキャストレシーバーです:

 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) 
            {
                   Log.e("br", "--- device found ---");
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

               items.add(device.getName());
            }
          }
        };

上記の BroadcastReceiver のコードでは、見つかったデバイス名を文字列 ArrayList "items" に入れようとしています。

次のように、oncreate 関数内にブロードキャストレシーバーを登録しています。

filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
   registerReceiver(mReceiver, filter);

androidmanifest ファイルで Bluetooth パーミッションを設定しました。上記の scand 関数では、検出されたデバイスのリストを表示することになっていますが、タイトルだけの空のダイアログが表示されています。startdiscoveryとbroadcastreceiverをうまく使って結果をアラートダイアログに表示する方法を教えてください。

4

5 に答える 5

1
  discovery() {
     IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
     this.registerReceiver(mReceiver, filter);
     // Register for broadcasts when discovery has finished
     filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
     this.registerReceiver(mReceiver, filter);
        
     // If we're already discovering, stop it
     if (mBluetoothAdapter.isDiscovering()) {
         mBluetoothAdapter.cancelDiscovery();
     }
     // Request discover from BluetoothAdapter
     mBluetoothAdapter.startDiscovery();
  }

放送受信機:

  private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        try {
            Broadcast=true;
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                // If it's already paired, skip it, because it's been listed
                // already
                if (device.getBondState() !=BluetoothDevice.BOND_BONDED)    {
                    
                    near_device.add(device.getAddress());
                
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
                    .equals(action)) {
                scanResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

};

 scanresult()
    {

            mBluetoothAdapter.cancelDiscovery();
            receiverCheck = false;
            // Unregister broadcast listeners
            Home.this.unregisterReceiver(mReceiver);
          // near device arraylist contain all device mac address
    }
于 2015-03-12T16:09:04.870 に答える
0

私の意見では、配列 item1 を AlertDialog に表示されるコンテンツとして設定すると、Dialog にその時点で配列内の項目 (空の配列) を表示するように指示しているので、要素は表示されません。

その後、item1配列の内容を更新して、AlertDialogが更新されることを期待できるかどうかはわかりません。私はこれがそのように機能しているとは思わない (とにかく試したことはない)。

ListView と Adapter を使用してアプリケーションに同様のことを行ったので、アダプターを介して項目を追加すると、ListView が更新されます (とにかく adapter.notifyDataSetChanged() を使用する必要があります)。

protected ArrayList<BluetoothDevice> foundDevices 
                      = new ArrayList<BluetoothDevice>();
private ListView foundDevicesListView;
private ArrayAdapter<BluetoothDevice> adapter;

foundDevicesListView = (ListView) findViewById(R.id.foundDevicesListView);

adapter = new ArrayAdapter<BluetoothDevice>(this,
            android.R.layout.simple_list_item_1, foundDevices);
foundDevicesListView.setAdapter(adapter);
//
//  Initialization, etc ....


    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a new device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device= intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE));
                if (!foundDevices.contains(device)) {
                    foundDevices.add(device);
                    adapter.notifyDataSetChanged();
                }
            }

            // When discovery cycle finished
            if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if(foundDevices==null || foundDevices.isEmpty()){
                    // Show not devices found message
                }
            }
        } 
于 2013-04-29T16:26:48.567 に答える