2013-12-18 60 views
3

如何處理藍牙啓用對話框中的「」拒絕「按鈕。我厭倦了使用「OnDismissListener」和「OnCancelListener」甚至嘗試過「onActivityResult」,但沒有奏效。該代碼是...Android:按下藍牙啓用對話框中的拒絕按鈕

private BluetoothAdapter mBluetoothAdapter; 
    private static final int REQUEST_ENABLE_BT = 1; 

     @Override 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     if (isBleSupportedOnDevice()) { 
      initializeBtComponent(); 

     } else { 
      finish(); 
     } 
    } 

    private boolean isBleSupportedOnDevice() { 
     if (!getPackageManager().hasSystemFeature(
       PackageManager.FEATURE_BLUETOOTH_LE)) { 
      Toast.makeText(this, "BLE is not supported in this device.", 
        Toast.LENGTH_SHORT).show(); 
      return false; 
     } 
     return true; 
    } 

    private void initializeBtComponent() { 
     final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); 
     mBluetoothAdapter = bluetoothManager.getAdapter(); 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     if (!mBluetoothAdapter.isEnabled()) { 
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 


    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
      } 
} 

此代碼提示與對話的用戶,直到他按下「允許」或「OK」按鈕,但我必須回到以前的活動,一旦他按下「 Deny「或」Cancel「按鈕。我如何做到這一點,是否有任何功能,當我按下「拒絕」按鈕時被調用。

回答

0

您需要重寫onActivityResult方法。

您正在使用常數REQUEST_ENABLE_BT

所以,當過用戶按下允許或拒絕按鈕後onActivityResult方法會從你的活動被稱爲合格requestCode。

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    // TODO Auto-generated method stub 
    if(requestCode == REQUEST_ENABLE_BT){ 
    startBluetoothStuff(); 
    } 

} 

在上面的代碼中檢查回調是否爲相同的請求代碼。

所以,你的理想的流量會像這個東西

boolean isBluetoothManagerEnabled() 
{ 
    // Some code 
} 

public void startBluetoothStuff() 
{ 
    if(isBluetoothManagerEnabled()) 
    { 
     // Do whatever you want to do if BT is enabled. 
    } 
    else 
    { 
     Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
    } 
} 
+1

謝謝你的迴應。我試過這種方法,問題是「onResume」方法每次在「onActivityResult」方法之前被調用。所以用戶一次又一次地得到對話框。 –

0

爲了解決這個問題,只需在您的onActivityResult()回調檢查RESULT_CANCELED。有些事情是這樣的:

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if(requestCode==REQUEST_ENABLE_BT && resultCode==RESULT_CANCELED){ 
     ... Do your stuff... 
    } 
}