// Função para enviar uma string por bluetooth private void sendMessage(String message) { desabilitaBotoes(); if (jogador == 1) { jogador = 2; } else { jogador = 1; } // Verifica se há conexão if (mBtService.getState() != BluetoothService.STATE_CONNECTED) { Toast.makeText(this, "Não há conexão estabelecida!", Toast.LENGTH_SHORT).show(); return; } // Verifica se há informação para ser enviada if (message.length() > 0) { // Pega a string passada como parâmetro e transforma em um vetor de bytes byte[] send = message.getBytes(); // Passa o vetor de bytes para o método de envio da classe bluetooth mBtService.write(send); // Limpa a mensagem (para evitar envios errados) message = ""; } // Variavel que guarda o numero de jogadas(no envio e na recepcao) // se chegar ao numero de 10 jogadas(9 da matriz + 1 do envio do nome) // entao e pq a matriz esta cheia e ninguem ganhou. matrizCheia++; if (matrizCheia == 10) { flagGanhador = 2; chamaTelaVencedor(); } }
@Override protected void onDestroy() { if (btService != null) { btService.unregisterChannel(CHANNEL_ID); } if (btService != null && shouldStop) { btService.stopSelf(); } unbindService(connection); super.onDestroy(); }
public void testStart() { // remove this comments to test this class standalone // jxmeService.initComponent(); // jxmeService.startComponent(null); jxmeService.addMessageListener(new TestListener()); if (LOG.isDebugEnabled()) { LOG.debug("adding IMessageListener to JxmeService"); } LOG.info("JUNIT: init BluetoothComponent"); // btcop.initComponent(); // btcop.startComponent(null); assertTrue(true); if (btcop.isRendezVousPeer()) { while (btcop.numberOfConnections() == 0) { synchronized (this) { try { this.wait(1000); } catch (InterruptedException e) { LOG.error("interrupted during waiting for incomming messages", e); } } } IElement[] elements = new Element[1]; elements[0] = new Element("test", "test"); IMessage msg = new Message(elements); try { jxmeService.send(null, msg); if (LOG.isDebugEnabled()) { LOG.debug("============> sent message"); } } catch (IOException e) { LOG.fatal("IOException during sending message: ", e); } } else { synchronized (this) { try { this.wait(30000); } catch (InterruptedException e) { LOG.error("interrupted during waiting for incomming messages", e); } } } synchronized (this) { try { this.wait(3000); } catch (InterruptedException e) { LOG.error("interrupted during waiting for incomming messages", e); } } }
@Override public void onResume() { super.onResume(); BTService = app.getBTService(mHandler); if (BTService != null) { // Only if the state is STATE_NONE, do we know that we haven't started already if (BTService.getState() == BluetoothService.STATE_NONE) { // Start the Bluetooth chat services BTService.start(); } } }
// Método para obter as respostas das chamadas startActivityForResult() public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_CONNECT_DEVICE: // Chamado qndo o usuário clica em connect no menu // Quando a classe ListDevice retorna um dispositivo para se conectar if (resultCode == Activity.RESULT_OK) { // Recebimento do MAC String address = data.getExtras().getString(TelaDeviceList.EXTRA_DEVICE_ADDRESS); // Recebe o objeto do dispositivo a se conectar BluetoothDevice device = myBluetoothAdapter.getRemoteDevice(address); // Tenta estabelecer uma conexão mBtService.connect(device); } break; case REQUEST_ENABLE_BT: // Retorno da requisição de habilitar bt if (resultCode == Activity.RESULT_OK) { // BT ligado, prepara para conexões setupConnection(); } else { // Caso usuário não habilite o bt, encerra o aplicativo Toast.makeText(this, "Bluetooth não ativado...", Toast.LENGTH_SHORT).show(); finish(); } } }
@Override protected void onStart() { super.onStart(); if (btService != null) { btService.registerActivity(BtGameConfigurationActivity.class); } }
@Override public void onDestroy() { super.onDestroy(); // Stop the Bluetooth services if (mService != null) mService.stop(); if (D) Log.e(TAG, "--- ON DESTROY ---"); }
@Override protected void onStop() { if (btService != null) { btService.unregisterActivity(); } super.onStop(); }
/** * Sends a message. * * @param message A string of text to send. */ private void sendMessage(String message) { // Check that we're actually connected before trying anything if (mService.getState() != BluetoothService.STATE_CONNECTED) { Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show(); return; } // Check that there's actually something to send if (message.length() > 0) { // Get the message bytes and tell the BluetoothService to write byte[] send = message.getBytes(); mService.write(send); // Reset out string buffer to zero and clear the edit text field mOutStringBuffer.setLength(0); } }
@Override public synchronized void onResume() { super.onResume(); /* * Caso o BT não tenha sido ligado no inicio, * deve ser habilitado nesse momento. * onResume() é executada após o retorno da * requisição de ativação do adaptador */ if (mBtService != null) { // Estado NONE idica que as threads de conexão ainda não foram iniciadas if (mBtService.getState() == BluetoothService.STATE_NONE) { // Inicializa as threads necessárias para comunicação -> Ver BluetoothService.java mBtService.start(); } } }
@Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if (mBtService != null) { mBtService.stop(); } }
private void connectDevice(Intent data, boolean secure) { // Get the device's MAC address String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS); // Get the BluetoothDevice object BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); // Attempt to connect to the device mService.connect(device, secure); }
@Override public boolean onOptionsItemSelected(MenuItem item) { if (btService != null) { btService.stopSelf(); btService = null; } finish(); return super.onOptionsItemSelected(item); }
@Override public synchronized void onResume() { super.onResume(); if (D) Log.e(TAG, "+ ON RESUME +"); // Performing this check in onResume() covers the case in which BT was // not enabled during onStart(), so we were paused to enable it... // onResume() will be called when ACTION_REQUEST_ENABLE activity // returns. if (mService != null) { // Only if the state is STATE_NONE, do we know that we haven't // started already if (mService.getState() == BluetoothService.STATE_NONE) { // Start the Bluetooth services mService.start(); } } }
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_ENABLE_BLUETOOTH: if (resultCode == BluetoothService.BLUETOOTH_DISCOVERABLE_DURATION) { bService.bluetoothDiscoverable(); } else { // User did not enable Bluetooth or an error occured } break; } }
protected void onIntentSendFail(BluetoothService bluetoothService, Packet packet) { if (!bluetoothService.isBTServer()) { lastClientError = System.currentTimeMillis(); if (!mServerService.isConnected()) { mServerService.onConnectionLost(); } } if (packet != null) { mPackets.addFirst(packet); } processQueue(); }
@Override public void onServiceConnected(ComponentName name, IBinder service) { btService = ((BluetoothService.BtBinder) service).getService(); btService.registerActivity(BtGameConfigurationActivity.class); messageChannel = btService.getChannel(CHANNEL_ID); messageChannel.setOnMessageReceivedListener( new BluetoothService.OnMessageReceivedListener() { @Override public void process(final byte[] buffer) { BtGameConfigurationClientActivity.this.runOnUiThread( new Runnable() { @Override public void run() { long seed = fromByteArray(Arrays.copyOfRange(buffer, 0, 8)); byte color = buffer[8]; byte type = buffer[9]; Log.d(TAG, Long.toString(seed)); Intent intent = new Intent( BtGameConfigurationClientActivity.this, BtGameActivity.class) .putExtra(GameActivity.SEED, seed) .putExtra(GameActivity.GAME, (int) type) .putExtra( BtGameActivity.LOCAL_PLAYER_COLOR, color == GameConfigurationActivity.COLOR_WHITE); startActivity(intent); shouldStop = false; finish(); } }); } }); }
@Override public void handleMessage(Message msg) { switch (msg.what) { case Node.MESSAGE_STATE_CHANGE: if (D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1); if (msg.arg1 == BluetoothService.STATE_CONNECTED) { // BTService.setReadContinually(true); BTService.startWeather(); } break; case Node.MESSAGE_READ: updateUI(); break; case Node.MESSAGE_ERROR: Intent i = new Intent(context, BluetoothActivity.class); startActivity(i); break; } }
/** * @author daniel * <p>To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class TestBluetoothService extends TestCase implements IComponent { private static Logger LOG = Logger.getLogger(TestBluetoothService.class); private static TestBluetoothService testJxmeService = null; private JxmeService jxmeService = JxmeService.Instance(); private BluetoothService btcop = BluetoothService.Instance(); private TestBluetoothService() {} public TestBluetoothService(String arg) { super(arg); } /* singleton */ public static TestBluetoothService Instance() { if (testJxmeService == null) { testJxmeService = new TestBluetoothService(); } return testJxmeService; } /* ******************************************************************************* */ /* Component */ /* ******************************************************************************* */ public void initComponent() { if (LOG.isInfoEnabled()) { LOG.info("Initialize TestJxmeServiceAopAspectJ"); } } public void startComponent(String[] args) { if (LOG.isInfoEnabled()) { LOG.info("Start TestJxmeServiceAopAspectJ"); } junit.textui.TestRunner.run(TestBluetoothService.class); } public void stopComponent() { if (LOG.isInfoEnabled()) { LOG.info("Stop TestJxmeServiceAopAspectJ"); } return; } /* ******************************************************************************* */ /* TestCase */ /* ******************************************************************************* */ public void setUp() {} public void tearDown() { return; } public void testCreation() { LOG.info("JUNIT: testeCreation"); assertTrue(true); } public void testInit() { LOG.info("JUNIT: init BluetoothComponent"); assertTrue(true); } public void testStart() { // remove this comments to test this class standalone // jxmeService.initComponent(); // jxmeService.startComponent(null); jxmeService.addMessageListener(new TestListener()); if (LOG.isDebugEnabled()) { LOG.debug("adding IMessageListener to JxmeService"); } LOG.info("JUNIT: init BluetoothComponent"); // btcop.initComponent(); // btcop.startComponent(null); assertTrue(true); if (btcop.isRendezVousPeer()) { while (btcop.numberOfConnections() == 0) { synchronized (this) { try { this.wait(1000); } catch (InterruptedException e) { LOG.error("interrupted during waiting for incomming messages", e); } } } IElement[] elements = new Element[1]; elements[0] = new Element("test", "test"); IMessage msg = new Message(elements); try { jxmeService.send(null, msg); if (LOG.isDebugEnabled()) { LOG.debug("============> sent message"); } } catch (IOException e) { LOG.fatal("IOException during sending message: ", e); } } else { synchronized (this) { try { this.wait(30000); } catch (InterruptedException e) { LOG.error("interrupted during waiting for incomming messages", e); } } } synchronized (this) { try { this.wait(3000); } catch (InterruptedException e) { LOG.error("interrupted during waiting for incomming messages", e); } } } class TestListener implements IMessageListener { public void processMessage(IMessage msg) { LOG.info("===>\t\tGOT MESSAGE:\n" + msg.toXMLString()); } } }
@Override public void onStop() { super.onStop(); if (D) Log.e(TAG, "-- ON STOP --"); BTService.stopWeather(); }
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_view_tags: // little hack to refresh the data in our tag list view when we open it ListView lv = (ListView) viewTagList.findViewById(R.id.item_list); ((TagViewListAdaptor) lv.getAdapter()).refreshData(); setContentView(viewTagList); return true; case R.id.menu_delete_note: Note n = ((NoteView) viewNote).getNote(); db.deleteTag(n.getId()); Toast.makeText(SBActivity.this, "Note " + n.getId() + " deleted.", Toast.LENGTH_SHORT) .show(); goBack(); return true; case R.id.menu_save_note: setContentView(viewCaptureNote); return true; case R.id.menu_tag_note: final Note curNote = ((NoteView) viewNote).getNote(); final Cursor c = db.getTagListForImg(curNote.getId()); CharSequence[] items = new CharSequence[c.getCount()]; for (int i = 0; i < items.length; i++) { c.moveToNext(); items[i] = c.getString(1); } final boolean[] checked = new boolean[c.getCount()]; c.moveToFirst(); for (int i = 0; i < items.length; i++) { checked[i] = c.getInt(2) == 1; c.moveToNext(); } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder .setTitle("Set tags for note " + curNote.getId()) .setIcon(android.R.drawable.ic_menu_edit) .setMultiChoiceItems( items, checked, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i, boolean b) { c.moveToPosition(i); db.setTagForNote(curNote.getId(), c.getLong(0), b); } }); builder.show(); return true; case R.id.menu_bluetooth_sync: Cursor c1 = getDbAdaptor().getUpdateList(null); int idxId = c1.getColumnIndex("_id"); int idxTable = c1.getColumnIndex("table_name"); int idxTarget = c1.getColumnIndex("target_id"); int idxTarget2 = c1.getColumnIndex("target2_id"); int idxType = c1.getColumnIndex("update_type"); int idxTime = c1.getColumnIndex("update_time"); Log.i(getClass().getName(), "Update list:"); while (c1.moveToNext()) { Log.i( getClass().getName(), " [_id=" + c1.getInt(idxId) + "] " + (c1.getInt(idxType) == DbAdaptor.UPDATE_TYPE_ADD ? "Added" : "Deleted") + " " + "id " + c1.getInt(idxTarget) + (!c1.isNull(idxTarget2) ? " (id2 " + c1.getInt(idxTarget2) + ")" : "") + " in table " + c1.getString(idxTable) + " (@ " + new Date(c1.getInt(idxTime)) + ")"); } if (bService.requestEnableBluetooth()) bService.bluetoothDiscoverable(); return true; } return false; }
@Override public void onDestroy() { super.onDestroy(); bService.cancel(); db.close(); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // open up the DbAdaptor db.open(); // gives us more screen space requestWindowFeature(Window.FEATURE_NO_TITLE); // need to do this because the camera doesn't do portrait mode setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // initialize all our views. LayoutInflater inflater = getLayoutInflater(); viewCaptureNote = inflater.inflate(R.layout.view_capture_note, null); viewNote = inflater.inflate(R.layout.view_note, null); viewTagList = inflater.inflate(R.layout.view_tag_list, null); viewNoteGallery = inflater.inflate(R.layout.view_note_gallery, null); // set the content view initially to save notes setContentView(viewCaptureNote); // set up the click listeners for the camera preview screen CameraPreview cameraPreview = (CameraPreview) findViewById(R.id.surface); findViewById(R.id.discard).setOnClickListener(cameraPreview); findViewById(R.id.take).setOnClickListener(cameraPreview); findViewById(R.id.save_untagged).setOnClickListener(cameraPreview); findViewById(R.id.save_and_tag).setOnClickListener(cameraPreview); // set up the 'view untagged' option in the list menu View someView = viewTagList.findViewById(R.id.tag_list_untagged); someView.findViewById(R.id.tag_subtags).setVisibility(View.GONE); ((TextView) someView.findViewById(R.id.tag_name)).setText("Click to view untagged notes"); someView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Gallery g = (Gallery) viewNoteGallery.findViewById(R.id.note_gallery); g.setAdapter(new NoteGalleryImageAdaptor(SBActivity.this, db.getUntaggedNotes())); setContentView(viewNoteGallery); } }); // set the list adaptor for our tag list final ListView lv = (ListView) viewTagList.findViewById(R.id.item_list); lv.setAdapter(new TagViewListAdaptor(this, db.getTagList())); registerForContextMenu(lv); lv.setOnItemClickListener( new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView v = (TextView) view.findViewById(R.id.tag_subtags); v.setVisibility(v.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE); long tagId = (Long) view.findViewById(R.id.tag_name).getTag(); if (v.getVisibility() == View.VISIBLE) { int subtagCount = 0; StringBuilder subTags = new StringBuilder("Sub-tags: "); Cursor c = db.getSubTags(tagId); while (c.moveToNext()) { subTags.append(c.getString(1) + " "); subtagCount++; } if (subtagCount > 0) v.setText(subTags); else v.setText("No sub-tags."); } } }); lv.setOnCreateContextMenuListener( new View.OnCreateContextMenuListener() { public void onCreateContextMenu( ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { menu.setHeaderIcon(android.R.drawable.ic_menu_info_details); ListView lv = (ListView) viewTagList.findViewById(R.id.item_list); Cursor listItem = (Cursor) lv.getItemAtPosition(((AdapterView.AdapterContextMenuInfo) menuInfo).position); String tagName = listItem.getString(1); menu.setHeaderTitle("Tag '" + tagName + "'"); menu.add(0, CONTEXT_VIEW_NOTES, 0, "View notes tagged with '" + tagName + "'"); menu.add(0, CONTEXT_DELETE_TAG, 0, "Delete tag"); } }); // set up click listeners for add tag viewTagList .findViewById(R.id.save_tag) .setOnClickListener( new View.OnClickListener() { public void onClick(View view) { EditText editText = (EditText) viewTagList.findViewById(R.id.tag_id); if (editText.getText().length() == 0) return; db.addNewTag(editText.getText()); ((TagViewListAdaptor) lv.getAdapter()).refreshData(); Toast.makeText( SBActivity.this, "Tag '" + editText.getText() + "' added.", Toast.LENGTH_SHORT) .show(); editText.setText(""); } }); viewTagList.setOnFocusChangeListener( new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { Log.i(TAG, "Focus changed innit: " + b); if (b) ((TagViewListAdaptor) lv.getAdapter()).refreshData(); } }); // set up our note viewing gallery final Gallery g = (Gallery) viewNoteGallery.findViewById(R.id.note_gallery); g.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { // set the note number i.e. 1/3 ((TextView) viewNoteGallery.findViewById(R.id.gallery_note_number)) .setText((i + 1) + " / " + g.getCount()); // set the date field Date d = new Date(((Note) view.getTag()).getSaveTime()); ((TextView) viewNoteGallery.findViewById(R.id.gallery_note_date)) .setText(DateFormat.getDateTimeInstance().format(d)); // set the tag field Cursor c = db.getTagListForImg(l); StringBuilder sb = new StringBuilder(); while (c.moveToNext()) { if (c.getInt(2) == 0) continue; sb.append(c.getString(1)); sb.append(", "); } // delete the last 2 chars: ", " if (sb.length() > 0) sb.delete(sb.length() - 2, sb.length()); else sb.append("none"); ((TextView) viewNoteGallery.findViewById(R.id.gallery_note_tags)) .setText(sb.toString()); } @Override public void onNothingSelected(AdapterView<?> adapterView) {} }); g.setOnItemLongClickListener( new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) { return true; } }); viewNoteGallery .findViewById(R.id.note_gallery_examine) .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Note n = (Note) ((View) g.getSelectedView()).getTag(); setViewSingleNote(n.getFileName()); } }); Handler btProgressHandler = new Handler() { public void handleMessage(Message msg) { if (btProgressDialog == null) return; switch (msg.what) { case BluetoothService.MSG_CONNECTED: btProgressDialog.setMessage("Bluetooth connected! Sending updates..."); break; case BluetoothService.MSG_RECEIVING: btProgressDialog.setMessage("Receiving updates from computer.."); break; case BluetoothService.MSG_PROGRESS: int cur = msg.arg1; int max = msg.arg2; btProgressDialog.setProgress(cur); btProgressDialog.setMax(max); break; case BluetoothService.MSG_DONE: btProgressDialog.dismiss(); break; } } }; bService.setProgressHandler(btProgressHandler); }