2013-05-13 3 views
1

Android 애플리케이션에 도움이 필요합니다. 나는 블루투스 장치를 발견하고 문자열과 이름을 비교하는 응용 프로그램을 만들려고합니다. 하지만 2 가지 문제가 발생했습니다.Android : 블루투스 기기 검색 오류

1 :. 나는 응용 프로그램 (뒤로 버튼)가 (몇 초 후에) .. 내가 문제가 "mReceiver"("두번째 문제를 확인)로 생각하는 나에게 충돌 메시지를 표시 한 후 종료를 종료 할 때

2 : (주된 문제) $ "mReceiver = new BroadcastReceiver()"부분에는 문제가 있습니다. 어떤 토큰이 작동하지 않는지를 확인하기 위해 여러 토스트를 던져 버렸습니다. 그러나 최종 원인 문제를 추가

; "개인 브로드 캐스트 리시버 mReceiver."> -

나는 확실하지 않다 그러나 나는 처음에 "mReciver"을 선언에서 "최종"가지고 있지의 문제를 생각합니다. 16,

강령 :

public class MainActivity extends Activity { 

private final static int REQUEST_ENABLE_BT = 1; //It's really just a number that you provide for onActivityResult (>0) 

//Temp objects for testing 
private String StringMeeting = "meeting"; 
ProgressBar bar; 

//Member fields 
private BluetoothAdapter mBluetoothAdapter; 
private ArrayAdapter<String> mPairedDevicesArrayAdapter; 
private ArrayAdapter<String> mNewDevicesArrayAdapter; 

// Create a BroadcastReceiver for ACTION_FOUND 
private BroadcastReceiver mReceiver; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    //declare & start progress bar 
    bar = (ProgressBar) findViewById(R.id.progressBar1); 
    bar.setVisibility(View.VISIBLE); 

    //------------Setup a Bluetooth (Get Adapter) ------------------ 
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    if (mBluetoothAdapter == null) { 
     // Device does not support Bluetooth 
     Toast.makeText(getApplicationContext(), "This Device does not support Bluetooth", Toast.LENGTH_LONG).show(); 
    }else{Toast.makeText(getApplicationContext(), "Getting the Adabter is done", Toast.LENGTH_SHORT).show();} 


    //------------Setup a Bluetooth (Enable Bluetooth) ------------------ 
    if (!mBluetoothAdapter.isEnabled()) { 
     Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
    }else{Toast.makeText(getApplicationContext(), "Enable Bluetooth is done", Toast.LENGTH_SHORT).show();} 

    //------------Finding Devices (Discovering Devices)---------------------- 
    // Create a BroadcastReceiver for ACTION_FOUND 
    Toast.makeText(getApplicationContext(), "creating the mReceiver", Toast.LENGTH_SHORT).show(); //last thing works 
    mReceiver = new BroadcastReceiver() { 
     public void onReceive(Context context, Intent intent) { 
      Toast.makeText(getApplicationContext(), "accessed onReceive + will create action", Toast.LENGTH_SHORT).show(); 
      String action = intent.getAction(); 

      Toast.makeText(getApplicationContext(), "Waiting to discover a device", Toast.LENGTH_SHORT).show(); 
      // When discovery finds a device 
      if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
       Toast.makeText(getApplicationContext(), "enterd the if", Toast.LENGTH_SHORT).show(); 
       // Get the BluetoothDevice object from the Intent 
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       Toast.makeText(getApplicationContext(), "Getting device names", Toast.LENGTH_SHORT).show(); 
       Toast.makeText(getApplicationContext(), device.getName(), Toast.LENGTH_LONG).show(); 
       Toast.makeText(getApplicationContext(), "displaying the name should be done", Toast.LENGTH_SHORT).show(); 

       // Add the name and address to an array adapter to show in a ListView 
       mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 

      }else{Toast.makeText(getApplicationContext(), "Error: BluetoothDevice.ACTION_FOUND.equals(action) = False", Toast.LENGTH_SHORT).show();} 
     } 
    }; 
    // Register the BroadcastReceiver 
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
    registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy 


} //onCreate end 

@Override 
protected void onDestroy() { 
    // TODO Auto-generated method stub 
    super.onDestroy(); 

    // Make sure we're not doing discovery anymore 
    if (mBluetoothAdapter != null) { 
     mBluetoothAdapter.cancelDiscovery(); 
    } 

    // Unregister broadcast listeners 
    this.unregisterReceiver(mReceiver); 
} 
} 

이 시간 내 주셔서 감사합니다.

+0

다시 버튼을 클릭하면 앱이 다운되지만 브로드 캐스트 리시버가 생성 된 지점을 오류의 원인이라고 말합니다. 브로드 캐스트 리시버는 onCreate에서 생성됩니다. 뒤로 버튼을 클릭하면 onDestroy가 호출됩니다. 따라서 실패하는 것은 onDestroy에서 실패해야합니다. – neo

+0

또 다른 요점은 뒤로 단추를 클릭하기 전에 장치 회전 여부입니다. 장치를 돌리면 활동이 삭제되고이를 처리 할 코드가 없으면 상태가 사라집니다. 장치를 회전 한 후 참조가 null 일 수 있습니다. – neo

+0

내가 보는 또 다른 것은 다음과 같다. mBluetoothAdapter가 null인지 아닌지 확인한 다음 else 외부의 isEnabled 메소드를 호출합니다. 즉, mBluetoothAdapter가 null이 아닌 경우에만 블루투스를 활성화하고 장치를 찾는 것이 의미가 있습니다. 축음 메시지 만 표시하면 나머지 코드는 여전히 실행됩니다. – neo

답변

0

사용자가 블루투스를 사용하도록 허용할지 여부를 묻는 메시지가 사용자에게 표시되도록 결과 활동을 시작하지만 결과를 기다리지 않고 즉시 장치를 찾으려고 시도합니다.

onActivityResult 콜백을 구현해야합니다. 결과가 RESULT_OK이면 디바이스 발견이 시작됩니다. 블루투스를 사용하려면 약간의 시간이 걸립니다.

+0

블루투스가 이미 켜져 있어도 계속 문제가 발생하지 않습니다. 그래서 문제는 블루투스를 가능하게하는 시간과 관련이 없습니다. 사실 isEnable() 후에 mReceiver를 제외한 모든 것이 잘 작동합니다. 나는 심지어 내 응용 프로그램이 "이전에 쌍으로 만든"장치를 검사하는 부분을 추가했으며 mReceiver로 이동하는 데 오랜 시간이 걸리고 여전히 작동하지 않습니다. – neorak

+0

오류가 발생했을 때 logcat이 표시하는 내용을 표시 할 수 있습니까? – neo

+0

로그를 복사 할 수는 없지만 오류는 발견되지 않았습니다. 그러나 코드를 확인하기 위해 일부 로그 메시지를 던졌습니다. onRecieve에 도달하면 작동을 멈추고 onReceive를 종료 한 후에도 작업을 계속합니다. 그것의 존재를 무시하는 것처럼. onReceive 전후의 모든 로그 메시지가 작동하지만 실제로는 발생하지 않습니다. – neorak

관련 문제