2013-04-24 2 views
0

저는 android에 익숙하지 않고 블루투스 기능으로 응용 프로그램을 만들고 있습니다. 블루투스 어댑터를 설정할 수 있는데, 내 장치 정보를 가져 오지만 블루투스 장치를 발견하기 위해 startdiscovery를 사용할 수는 없습니다. 스캔을 시작할 때 아무 것도하지 않습니다. 여기 Android의 블루투스 : StartDiscovery가 작동하지 않습니다. 장치를 스캔 할 수 없습니다.

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(); 
       } 

      } 

난 그냥 "공공 무효에서 onCreate"함수 뒤에 넣어 한 onActivityResult를 함수이다 :

은 내가 스캔을 시작하는 onclicklistner을 사용하고

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(); 

} 

이것은 broadca stReceiver : 브로드 캐스트 리시버에 대한 위의 코드에서

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()); 
      } 
      } 
     }; 

, 내가 문자열의 ArrayList "항목"에서 발견 된 장치 이름을 넣어하려합니다.

나는이 같은 한 OnCreate functon 내부 브로드 캐스트 리시버 등록하고 있습니다 :

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

난 AndroidManifest를 파일에 블루투스 권한을 설정했습니다. 위의 scand 기능에서 발견 된 장치의 목록을 보여주고 싶지만 제목이있는 빈 대화 상자를 표시하고 있습니다. startdiscovery 및 broadcastreceiver를 사용하여 alertdialog에 결과를 표시하는 방법을 알려주십시오.

+0

는 당신이 시도 블루투스 장치를 있습니까 검색 모드에서 스캔 하시겠습니까? –

+0

예, 검색 가능합니다. –

+0

startdiscovery 및 broadcastreceiver를 사용하는 올바른 방법은 무엇입니까? –

답변

1

startDiscovery()은 비동기식이므로 호출 직후 결과를받지 못합니다. 코드를 움직여 대화 상자에 함수를 표시하고 public void showScanResult()를 호출하여 onReceive에서 호출합니다.

+0

대화 상자를 표시 할 수 있는지 확신 할 수 없어 작동하지 않을 수 있습니다. 그러나 그것을 시도하고 우리는 거기에서 간다. –

+0

Yesss, 시작 발견 한 직후 {bluetooth.isdiscovering} {} 동안 사용했습니다. 검색이 완료 될 때까지 기다릴 것입니다. 올바른 방법입니까? 이제 작동 중입니다. 답장을 보내 주셔서 감사합니다. :) –

+0

발견하는 데 5 초 이상 걸릴 경우 ANR을 얻을 수 있기 때문에 그렇게해서는 안됩니다. 먼저 내 접근 방식을 시도해보고 거기에서부터 시작하겠습니다. –

0

글쎄, 내 생각에 AlertDialog에 표시 할 내용으로 배열 item1을 설정하면 그 순간에 배열에있는 항목을 표시하는 Dialog (빈 배열)가 표시됩니다. 요소 없음.

나는 그 일을 한 후에 item1 배열의 내용을 업데이트하고 AlertDialog가 새로 고쳐지기를 기대합니다. 나는 이것이 그런 식으로 일한다고 생각하지 않는다. (하지만 어쨌든 그것을 시도한 적이 없다.)

나는 ListView를 및 어댑터를 사용하여 내 응용 프로그램에 비슷한 일을했다, 그래서 당신은 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 
       } 
      } 
     } 
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 
    } 
관련 문제