2013-07-25 2 views
0

Я разрабатываю приложение, где у меня есть кнопка, в которой отображается диалоговое окно «Активность», в котором он находит устройства Bluetooth.Активность результата закрывает основное действие при нажатии кнопки возврата

Он работает нормально, но если я нажму кнопку «Назад» во время этой операции, вместо того, чтобы вернуться к основному действию, он уничтожит его.

Активность диалога такая же, как в примере BluetoothChat. Это код основной деятельности:

/********************* 
* 
* ONCREATE 
* 
********************/ 

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

    final Button button1 = (Button) findViewById(R.id.button1); 
    final Button button2 = (Button) findViewById(R.id.button2); 



    /**Call to the Configuration activity*/ 
    button2.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      lanzarConfiguracion (null); 
     } 
    }); 

    /**Call to the DeviceList activity*/ 
    button1.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      lanzarBusqueda (null); 
     } 
    }); 

    GlobalVar.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 

    if (GlobalVar.mBluetoothAdapter == null) { 
     Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show(); 
     finish(); 
     return; 
    } 
} 



/********************* 
* 
* ONSTART 
* 
********************/ 

@Override 
public void onStart() { 
    super.onStart(); 

    if (!GlobalVar.mBluetoothAdapter.isEnabled()) { 

     Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivityForResult(enableBtIntent, GlobalVar.REQUEST_ENABLE_BT); 
    } 
    else { 
     if (GlobalVar.mTransmission == null) setupCaller(); 
    } 
} 



/********************* 
* 
* ONDESTROY 
* 
********************/ 

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    /**Stop the Bluetooth chat services*/ 
    if (GlobalVar.mTransmission != null) GlobalVar.mTransmission.stop(); 
} 



/********************* 
* 
* OPTIONS 
* 
********************/ 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    /**Inflate the menu; this adds items to the action bar if it is present.*/ 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     case R.id.info: 
      lanzarInfo(null); 
      break; 
     case R.id.config: 
      lanzarConfiguracion(null); 
      break; 
    } 
    return true; /** true -> consumimos el item, no se propaga*/ 
} 




@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    switch (requestCode) { 
     case GlobalVar.REQUEST_CONNECT_DEVICE: 
      /**When DeviceListActivity returns with a device to connect*/ 
      if (resultCode == Activity.RESULT_OK) { 
       connectDevice(data); 
      } 
     case GlobalVar.REQUEST_ENABLE_BT: 
      /**When the request to enable Bluetooth returns*/ 
      if (resultCode == Activity.RESULT_OK) { 
       /**Bluetooth is now enabled, so set up a chat session*/ 
       setupCaller(); 
      } else { 
       /**User did not enable Bluetooth or an error occurred*/ 
       Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show(); 
       finish(); 
      } 
      break; 
    } 

} 


private void connectDevice(Intent data) { 
    /**Get the device MAC address*/ 
    String address = data.getExtras().getString(DeviceListDialog.EXTRA_DEVICE_ADDRESS); 
    /**Get the BluetoothDevice object*/ 
    BluetoothDevice device = GlobalVar.mBluetoothAdapter.getRemoteDevice(address); 
    /**Attempt to connect to the device*/ 
    try{ 
     GlobalVar.mTransmission.connect(device); 
    }catch(Exception ex) { 
    } 
} 


private final void setStatus(int resId) { 
    final ActionBar actionBar = getActionBar(); 
    actionBar.setSubtitle(resId); 
} 

private final void setStatus(CharSequence subTitle) { 
    final ActionBar actionBar = getActionBar(); 
    actionBar.setSubtitle(subTitle); 
} 


/** 
* The Handler that gets information back from the Transmission 
*/ 
public final Handler mHandler = new Handler() { 
    @Override 
    public void handleMessage(Message msg) { 
     switch (msg.what) { 
      case GlobalVar.MESSAGE_STATE_CHANGE: 
       switch (msg.arg1) { 
        case GlobalVar.STATE_CONNECTED: 
         setStatus(getString(R.string.title_connected_to, GlobalVar.mConnectedDeviceName)); 
         GlobalVar.mCommunicationArrayAdapter.clear(); 
         break; 
        case GlobalVar.STATE_CONNECTING: 
         setStatus(R.string.title_connecting); 
         break; 
        case GlobalVar.STATE_LISTEN: 
        case GlobalVar.STATE_NONE: 
         setStatus(R.string.title_not_connected); 
         break; 
       } 
       break; 
      case GlobalVar.MESSAGE_WRITE: 
       byte[] writeBuf = (byte[]) msg.obj; 
       /**construct a string from the buffer*/ 
       String writeMessage = new String(writeBuf); 
       GlobalVar.mCommunicationArrayAdapter.add("Me: " + writeMessage); 
       break; 
      case GlobalVar.MESSAGE_READ: 
       byte[] readBuf = (byte[]) msg.obj; 
       /**construct a string from the valid bytes in the buffer*/ 
       String readMessage = new String(readBuf, 0, msg.arg1); 
       GlobalVar.mCommunicationArrayAdapter.add(GlobalVar.mConnectedDeviceName+": " + readMessage); 
       break; 
      case GlobalVar.MESSAGE_DEVICE_NAME: 
       /**save the connected device's name*/ 
       GlobalVar.mConnectedDeviceName = msg.getData().getString(GlobalVar.DEVICE_NAME); 
       Toast.makeText(getApplicationContext(), "Connected to " + GlobalVar.mConnectedDeviceName, Toast.LENGTH_SHORT).show(); 
       break; 
      case GlobalVar.MESSAGE_TOAST: 
       Toast.makeText(getApplicationContext(), msg.getData().getString(GlobalVar.TOAST), Toast.LENGTH_SHORT).show(); 
       break; 
     } 
    } 
}; 


public void setupCaller() { 
    /**Initialize the Transmission to perform bluetooth connections*/ 
    GlobalVar.mTransmission = new Transmission(this, mHandler); 
    /**Initialize the array adapter here for avoid errors with the Handler above*/ 
    //GlobalVar.mCommunicationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message); 
} 





/********************* 
* 
* INTENTS 
* 
********************/ 

public void lanzarConfiguracion (View view) { 
    Intent i = new Intent (this, Configuration.class); 
    startActivity(i); 
} 
public void lanzarInfo (View view) { 
    Intent i = new Intent(this, Info.class); 
    startActivity(i); 
} 
public void lanzarBusqueda (View view) { 
    Intent serverintent = new Intent(this, DeviceListDialog.class); 
    startActivityForResult(serverintent, GlobalVar.REQUEST_CONNECT_DEVICE); 
} 

}

ответ

1

Вы забыли break заявление до

case GlobalVar.REQUEST_ENABLE_BT: 

Выполнение продолжается в этом случае, и достигает finish() заявление, потому что по умолчанию RESULT_CODE для заднего пресса Activity.RESULT_CANCEL.

+0

Решено, спасибо! – masmic

Смежные вопросы