List of usage examples for android.bluetooth BluetoothAdapter ACTION_REQUEST_ENABLE
String ACTION_REQUEST_ENABLE
To view the source code for android.bluetooth BluetoothAdapter ACTION_REQUEST_ENABLE.
Click Source Link
From source file:com.github.akinaru.rfdroid.activity.BtDevicesActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_btdevices); deviceNameTv = (TextView) findViewById(R.id.device_name); sharedpreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); int scanIntervalValue = sharedpreferences.getInt(JsonConstants.BT_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL); int scanWindowValue = sharedpreferences.getInt(JsonConstants.BT_SCAN_WINDOW, DEFAULT_SCAN_WINDOW); tablelayout = (TableLayout) findViewById(R.id.tablelayout); altTableRow(2);//from ww w . jav a2s.com // Set a Toolbar to replace the ActionBar. toolbar = (Toolbar) findViewById(R.id.toolbar_item); setSupportActionBar(toolbar); getSupportActionBar().setTitle("BLE device - reception rate"); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.inflateMenu(R.menu.toolbar_menu); // Find our drawer view mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawerToggle = setupDrawerToggle(); mDrawer.setDrawerListener(drawerToggle); nvDrawer = (NavigationView) findViewById(R.id.nvView); // Setup drawer view setupDrawerContent(nvDrawer); // Use this check to determine whether BLE is supported on the device. Then // you can selectively disable BLE-related features. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, "Bluetooth Smart is not supported on your device", Toast.LENGTH_SHORT).show(); finish(); } mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter()); mChart = (BarChart) findViewById(R.id.chart1); mChart.setDrawBarShadow(false); mChart.setDrawValueAboveBar(true); mChart.setDescription(""); // if more than 60 entries are displayed in the chart, no values will be // drawn mChart.setMaxVisibleValueCount(60); // scaling can now only be done on x- and y-axis separately mChart.setPinchZoom(false); mChart.setDrawGridBackground(false); mChart.setDescriptionColor(Color.parseColor("#000000")); XAxis xAxis = mChart.getXAxis(); xAxis.setDrawGridLines(false); xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); xAxis.setSpaceBetweenLabels(0); YAxisValueFormatter custom = new DataAxisFormatter("%"); YAxis leftAxis = mChart.getAxisLeft(); leftAxis.setValueFormatter(custom); leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART); YAxis rightAxis = mChart.getAxisRight(); rightAxis.setValueFormatter(custom); rightAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART); leftAxis.setDrawGridLines(true); rightAxis.setDrawGridLines(false); mChart.animateY(1000); mChart.getLegend().setEnabled(true); mChart.setVisibility(View.GONE); mScanIntervalSeekbar = (DiscreteSeekBar) findViewById(R.id.scan_interval_seekbar); mScanIntervalSeekbar.setVisibility(View.GONE); mScanIntervalSeekbar.keepShowingPopup(true); mScanIntervalSeekbar.setNumericTransformer(new DiscreteSeekBar.NumericTransformer() { @Override public int transform(int value) { return value * 10; } }); mScanIntervalSeekbar.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { mScanIntervalSeekbar.showFloater(250); } } }); mScanIntervalSeekbar.setOnProgressChangeListener(new DiscreteSeekBar.OnProgressChangeListener() { @Override public void onProgressChanged(DiscreteSeekBar seekBar, int value, boolean fromUser) { if (scanIntervalTv != null) scanIntervalTv.setText("" + (value * 10)); } @Override public void onStartTrackingTouch(DiscreteSeekBar seekBar) { } @Override public void onStopTrackingTouch(DiscreteSeekBar seekBar) { //setScanInterval(); } }); mWindowIntervalSeekbar = (DiscreteSeekBar) findViewById(R.id.scan_window_seekbar); mWindowIntervalSeekbar.setVisibility(View.GONE); mWindowIntervalSeekbar.keepShowingPopup(true); mWindowIntervalSeekbar.setNumericTransformer(new DiscreteSeekBar.NumericTransformer() { @Override public int transform(int value) { return value * 10; } }); mWindowIntervalSeekbar.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { mWindowIntervalSeekbar.showFloater(250); } } }); mWindowIntervalSeekbar.setOnProgressChangeListener(new DiscreteSeekBar.OnProgressChangeListener() { @Override public void onProgressChanged(DiscreteSeekBar seekBar, int value, boolean fromUser) { if (scanWindowTv != null) scanWindowTv.setText("" + (value * 10)); } @Override public void onStartTrackingTouch(DiscreteSeekBar seekBar) { } @Override public void onStopTrackingTouch(DiscreteSeekBar seekBar) { //setWindowInterval(); } }); mScanIntervalSeekbar.setProgress(scanIntervalValue / 10); mWindowIntervalSeekbar.setProgress(scanWindowValue / 10); scanIntervalTv = (TextView) findViewById(R.id.scan_interval_value); scanWindowTv = (TextView) findViewById(R.id.scan_window_value); scanIntervalTv.setText("" + scanIntervalValue); scanWindowTv.setText("" + scanWindowValue); Button button_stop = (Button) findViewById(R.id.button_stop); Button button_restart_scan = (Button) findViewById(R.id.button_restart_scan); button_stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (currentService != null && currentService.isScanning()) { Log.i(TAG, "scanning stopped..."); runOnUiThread(new Runnable() { @Override public void run() { hideProgressBar(); Toast.makeText(BtDevicesActivity.this, "scanning has stopped", Toast.LENGTH_SHORT) .show(); } }); currentService.stopScan(); } } }); button_restart_scan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { currentService.stopScan(); Log.i(TAG, "scanning ..."); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(BtDevicesActivity.this, "scanning ...", Toast.LENGTH_SHORT).show(); } }); scanningListView.setItemChecked(-1, true); triggerNewScan(); } }); initTv(); if (mBluetoothAdapter.isEnabled()) { Intent intent = new Intent(this, RFdroidService.class); bound = bindService(intent, mServiceConnection, BIND_AUTO_CREATE); } }
From source file:com.nordicsemi.nrfUARTv2.MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);/*from www. j av a 2 s . c o m*/ mBtAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBtAdapter == null) { Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show(); finish(); return; } messageListView = (ListView) findViewById(R.id.listMessage); listAdapter = new ArrayAdapter<String>(this, R.layout.message_detail); messageListView.setAdapter(listAdapter); messageListView.setDivider(null); btnConnectDisconnect = (Button) findViewById(R.id.btn_select); btnConnectRight = (Button) findViewById(R.id.button); btnSend = (Button) findViewById(R.id.sendButton); edtMessage = (EditText) findViewById(R.id.sendText); service_init(); // Handler Disconnect & Connect button btnConnectDisconnect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //should not be here, only for debug UploadData(); // if (!mBtAdapter.isEnabled()) { // Log.i(TAG, "onClick - BT not enabled yet"); // Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // startActivityForResult(enableIntent, REQUEST_ENABLE_BT); // } // else { // if (btnConnectDisconnect.getText().equals("Connect Left")){ // // //Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices // // Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class); // startActivityForResult(newIntent, REQUEST_SELECT_DEVICE); // } else { // //Disconnect button pressed // if (mDevice!=null) // { // mService.disconnect(); // // } // if (mDevice2!=null) // { // mService2.disconnect(); // // } // mCollecting = false; // UploadData(); // } // } } }); btnConnectRight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!mBtAdapter.isEnabled()) { Log.i(TAG, "onClick - BT not enabled yet"); Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } else { if (btnConnectRight.getText().equals("Connect Right")) { //Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class); startActivityForResult(newIntent, REQUEST_SELECT_DEVICE2); } else { //Disconnect button pressed if (mDevice2 != null) { mService2.disconnect(); } } } } }); // Handler Send button btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText editText = (EditText) findViewById(R.id.sendText); String message = editText.getText().toString(); byte[] value; try { //send data to service value = message.getBytes("UTF-8"); mService.writeRXCharacteristic(value); //Update the log with time stamp String currentDateTimeString = DateFormat.getTimeInstance().format(new Date()); listAdapter.add("[" + currentDateTimeString + "] TX: " + message); messageListView.smoothScrollToPosition(listAdapter.getCount() - 1); edtMessage.setText(""); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); // Set initial UI state }
From source file:com.variable.demo.api.MainActivity.java
/** * Invokes a new intent to request to start the bluetooth, if not already on. *//*from ww w.j a v a2 s .c o m*/ private boolean ensureBluetoothIsOn() { if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) { Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); btIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivityForResult(btIntent, 200); return false; } return true; }
From source file:org.apache.cordova.plugin.BluetoothPlugin.java
@Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { logDbg("Action: " + action); if (ACTION_IS_SUPPORTED.equals(action)) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, m_bluetoothAdapter != null)); return true; } else if (m_bluetoothAdapter == null) { String msg = "Bluetooth is not supported !"; callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, msg)); logErr(msg);//from w ww .ja v a 2 s . c o m return true; } else if (ACTION_ENABLE.equals(action)) { this.callback_enable = callbackContext; PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); if (!m_bluetoothAdapter.isEnabled()) { this.cordova.startActivityForResult(this, new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), this.REQUEST_CODE_ENABLE); } callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_DISABLE.equals(action)) { PluginResult pluginResult; if (!m_bluetoothAdapter.disable() && !(m_bluetoothAdapter.getState() == BluetoothAdapter.STATE_TURNING_OFF || m_bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF)) { pluginResult = new PluginResult(PluginResult.Status.ERROR); } else { pluginResult = new PluginResult(PluginResult.Status.OK); } callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_IS_ENABLED.equals(action)) { boolean b = m_bluetoothAdapter.isEnabled(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b)); return true; } else if (ACTION_GETADDRESS.equals(action)) { String address = m_bluetoothAdapter.getAddress(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, address)); return true; } else if (ACTION_GETNAME.equals(action)) { String name = m_bluetoothAdapter.getName(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, name)); return true; } else if (ACTION_REQUEST_DISCOVERABLE.equals(action)) { final int duration = args.getInt(0); this.callback_discoverable = callbackContext; Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, duration); this.cordova.startActivityForResult(this, intent, this.REQUEST_CODE_DISCOVERABLE); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_STARTDISCOVERY.equals(action)) { this.callback_discovery = callbackContext; m_discoveredDevices = new JSONArray(); // be sure there are no ongoing discovery m_bluetoothAdapter.cancelDiscovery(); if (!m_bluetoothAdapter.startDiscovery()) { String msg = "Unable to start discovery"; logErr(msg); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, msg)); } else { PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } return true; } else if (ACTION_CANCELDISCOVERY.equals(action)) { if (m_bluetoothAdapter.cancelDiscovery()) callbackContext.success(); else callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR)); return true; } else if (ACTION_GETBONDEDDEVICES.equals(action)) { JSONArray bondedDevices = new JSONArray(); Set<BluetoothDevice> bondSet = m_bluetoothAdapter.getBondedDevices(); for (Iterator<BluetoothDevice> it = bondSet.iterator(); it.hasNext();) { BluetoothDevice bluetoothDevice = (BluetoothDevice) it.next(); JSONObject deviceInfo = new JSONObject(); deviceInfo.put("name", bluetoothDevice.getName()); deviceInfo.put("address", bluetoothDevice.getAddress()); deviceInfo.put("isBonded", true); bondedDevices.put(deviceInfo); } callbackContext.success(bondedDevices); return true; } else if (ACTION_FETCHUUIDS.equals(action)) { final String address = args.getString(0); this.callback_uuids = callbackContext; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { String msg = "Not supported, minimum SDK version is :" + Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1; logErr(msg); callbackContext.error(msg); return true; } try { logDbg("Listing UUIDs for : " + address); // Fetch UUIDs from bluetooth device BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address); // min api 15 !!! Method m = bluetoothDevice.getClass().getMethod("fetchUuidsWithSdp", (Class[]) null); m.invoke(bluetoothDevice, (Object[]) null); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } catch (Exception e) { logErr(e.toString() + " / " + e.getMessage()); callbackContext.error(e.getMessage()); } return true; } else if (ACTION_CONNECT.equals(action)) { final String address = args.getString(0); final String uuid = args.getString(1); final boolean secure = args.getBoolean(2); this.callback_connect = callbackContext; cordova.getThreadPool().execute(new Runnable() { public void run() { BluetoothSocket socket = null; try { logDbg("Connecting..."); // Cancel discovery because it will slow down the connection if (m_bluetoothAdapter.isDiscovering()) m_bluetoothAdapter.cancelDiscovery(); BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address); if (secure) { socket = connectSecureHelper(bluetoothDevice, UUID.fromString(uuid)); } else { socket = connectInsecureHelper(bluetoothDevice, UUID.fromString(uuid)); } } catch (Exception e) { logErr(e.toString() + " / " + e.getMessage()); callback_connect.error(e.getMessage()); } if (socket != null) { logDbg("Connected"); m_sockets.add(socket); int socketId = m_sockets.indexOf(socket); callback_connect.sendPluginResult(new PluginResult(PluginResult.Status.OK, socketId)); } else { callback_connect.error(0); } } }); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_DISCONNECT.equals(action)) { final int socketId = args.getInt(0); try { BluetoothSocket socket = m_sockets.get(socketId); logDbg("Close socket"); socket.close(); logDbg("Delete socket from list"); m_sockets.remove(socketId); for (int i = 0; i < m_readThreads.size(); i++) { if (m_readThreads.get(i).socketId == socketId) { m_readThreads.remove(i); break; } } callbackContext.success(); } catch (Exception e) { logErr(e.toString() + " / " + e.getMessage()); callbackContext.error(e.getMessage()); } return true; } else if (ACTION_LISTEN.equals(action)) { final String name = args.getString(0); final String uuid = args.getString(1); final boolean secure = args.getBoolean(2); this.callback_listen = callbackContext; if (m_listenThread != null) { m_listenThread.cancel(); m_listenThread = null; } m_listenThread = new ListenThread(this.cordova, name, UUID.fromString(uuid), secure); m_listenThread.start(); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_CANCEL_LISTENING.equals(action)) { if (m_listenThread != null) { m_listenThread.cancel(); } m_listenThread = null; callbackContext.success(); return true; } else if (ACTION_READ.equals(action)) { final int socketId = args.getInt(0); final int bufferSize = args.getInt(1); this.callback_read = callbackContext; ReadThread readThread = new ReadThread(m_sockets.get(socketId), socketId, bufferSize); readThread.start(); m_readThreads.add(readThread); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_WRITE.equals(action)) { final int socketId = args.getInt(0); final JSONArray jsonArray = args.getJSONArray(1); try { OutputStream outputStream = m_sockets.get(socketId).getOutputStream(); byte[] buffer = new byte[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { buffer[i] = (byte) jsonArray.getInt(i); } outputStream.write(buffer); callbackContext.success(); } catch (Exception e) { logErr(e.toString() + " / " + e.getMessage()); callbackContext.error(e.getMessage()); } return true; } return false; }
From source file:com.zpci.firstsignhairclipdemo.MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.diag);/*from w w w. j a v a 2 s. c o m*/ mBtAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBtAdapter == null) { Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show(); finish(); return; } messageListView = (ListView) findViewById(R.id.listMessage); listAdapter = new ArrayAdapter<String>(this, R.layout.message_detail); messageListView.setAdapter(listAdapter); messageListView.setDivider(null); btnConnectDisconnect = (Button) findViewById(R.id.btn_select); btnSend = (Button) findViewById(R.id.sendButton); edtMessage = (EditText) findViewById(R.id.sendText); // top level select either demo mode or diag mode dm1 = (Button) findViewById(R.id.DemoModeButton); dm2 = (Button) findViewById(R.id.DiagModeButton); // make other controls invisible until mode is selected c1 = (Button) findViewById(R.id.Command1Button); c2 = (Button) findViewById(R.id.Command2Button); sb1 = (Button) findViewById(R.id.Sens1Button); sb2 = (Button) findViewById(R.id.Sens2Button); sb3 = (Button) findViewById(R.id.Sens3Button); stxt = (TextView) findViewById(R.id.textSensy); Log.d(TAG, "stext = " + stxt); alonb = (Button) findViewById(R.id.DemoAlarmOnButton); aloffb = (Button) findViewById(R.id.DemoAlarmOffButton); Log.d(TAG, "demomode = " + demomode); c1.setVisibility(View.INVISIBLE); c2.setVisibility(View.INVISIBLE); btnSend.setVisibility(View.INVISIBLE); edtMessage.setVisibility(View.INVISIBLE); messageListView.setVisibility(View.INVISIBLE); sb1.setVisibility(View.GONE); sb2.setVisibility(View.GONE); sb3.setVisibility(View.GONE); stxt.setVisibility(View.GONE); alonb.setVisibility(View.GONE); aloffb.setVisibility(View.GONE); service_init(); // Handler Disconnect & Connect button btnConnectDisconnect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!mBtAdapter.isEnabled()) { Log.i(TAG, "onClick - BT not enabled yet"); Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } else { if (btnConnectDisconnect.getText().equals("Connect")) { //Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class); startActivityForResult(newIntent, REQUEST_SELECT_DEVICE); } else { //Disconnect button pressed if (mDevice != null) { mService.disconnect(); } } } } }); // Handler Send button btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText editText = (EditText) findViewById(R.id.sendText); String message = editText.getText().toString(); byte[] value; try { //send data to service value = message.getBytes("UTF-8"); mService.writeRXCharacteristic(value); //Update the log with time stamp String currentDateTimeString = DateFormat.getTimeInstance().format(new Date()); listAdapter.add("[" + currentDateTimeString + "] TX: " + message); messageListView.smoothScrollToPosition(listAdapter.getCount() - 1); edtMessage.setText(""); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); }
From source file:com.rimbit.android_wallet.ui.RequestCoinsFragment.java
@Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.request_coins_fragment, container, false); qrView = (ImageView) view.findViewById(R.id.request_coins_qr); qrView.setOnClickListener(new OnClickListener() { @Override//from w w w . j a v a 2 s . co m public void onClick(final View v) { BitmapFragment.show(getFragmentManager(), qrCodeBitmap); } }); final CurrencyAmountView RBTAmountView = (CurrencyAmountView) view .findViewById(R.id.request_coins_amount_rbt); RBTAmountView.setCurrencySymbol(config.getRBTPrefix()); RBTAmountView.setInputPrecision(config.getRBTMaxPrecision()); RBTAmountView.setHintPrecision(config.getRBTPrecision()); RBTAmountView.setShift(config.getRBTShift()); final CurrencyAmountView localAmountView = (CurrencyAmountView) view .findViewById(R.id.request_coins_amount_local); localAmountView.setInputPrecision(Constants.LOCAL_PRECISION); localAmountView.setHintPrecision(Constants.LOCAL_PRECISION); amountCalculatorLink = new CurrencyCalculatorLink(RBTAmountView, localAmountView); acceptBluetoothPaymentView = (CheckBox) view.findViewById(R.id.request_coins_accept_bluetooth_payment); acceptBluetoothPaymentView .setVisibility(ENABLE_BLUETOOTH_LISTENING && bluetoothAdapter != null ? View.VISIBLE : View.GONE); acceptBluetoothPaymentView .setChecked(ENABLE_BLUETOOTH_LISTENING && bluetoothAdapter != null && bluetoothAdapter.isEnabled()); acceptBluetoothPaymentView.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) { if (ENABLE_BLUETOOTH_LISTENING && bluetoothAdapter != null && isChecked) { if (bluetoothAdapter.isEnabled()) { startBluetoothListening(); } else { // ask for permission to enable bluetooth startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), REQUEST_CODE_ENABLE_BLUETOOTH); } } else { stopBluetoothListening(); } updateView(); } }); initiateRequestView = (TextView) view.findViewById(R.id.request_coins_fragment_initiate_request); return view; }
From source file:org.apache.cordova.plugin.BluetoothPlugin2.java
@Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { logDbg("Action: " + action); if (ACTION_IS_SUPPORTED.equals(action)) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, m_bluetoothAdapter != null)); return true; } else if (m_bluetoothAdapter == null) { String msg = "Bluetooth is not supported !"; callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, msg)); logErr(msg);//from w w w . j a va2 s.c om return true; } else if (ACTION_ENABLE.equals(action)) { this.callback_enable = callbackContext; PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); if (!m_bluetoothAdapter.isEnabled()) { this.cordova.startActivityForResult(this, new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), this.REQUEST_CODE_ENABLE); } callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_DISABLE.equals(action)) { PluginResult pluginResult; if (!m_bluetoothAdapter.disable() && !(m_bluetoothAdapter.getState() == BluetoothAdapter.STATE_TURNING_OFF || m_bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF)) { pluginResult = new PluginResult(PluginResult.Status.ERROR); } else { pluginResult = new PluginResult(PluginResult.Status.OK); } callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_IS_ENABLED.equals(action)) { boolean b = m_bluetoothAdapter.isEnabled(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b)); return true; } else if (ACTION_GETADDRESS.equals(action)) { String address = m_bluetoothAdapter.getAddress(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, address)); return true; } else if (ACTION_GETNAME.equals(action)) { String name = m_bluetoothAdapter.getName(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, name)); return true; } else if (ACTION_REQUEST_DISCOVERABLE.equals(action)) { final int duration = args.getInt(0); this.callback_discoverable = callbackContext; Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, duration); this.cordova.startActivityForResult(this, intent, this.REQUEST_CODE_DISCOVERABLE); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_STARTDISCOVERY.equals(action)) { this.callback_discovery = callbackContext; m_discoveredDevices = new JSONArray(); // be sure there are no ongoing discovery m_bluetoothAdapter.cancelDiscovery(); if (!m_bluetoothAdapter.startDiscovery()) { String msg = "Unable to start discovery"; logErr(msg); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, msg)); } else { PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } return true; } else if (ACTION_CANCELDISCOVERY.equals(action)) { if (m_bluetoothAdapter.cancelDiscovery()) callbackContext.success(); else callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR)); return true; } else if (ACTION_GETBONDEDDEVICES.equals(action)) { JSONArray bondedDevices = new JSONArray(); Set<BluetoothDevice> bondSet = m_bluetoothAdapter.getBondedDevices(); for (Iterator<BluetoothDevice> it = bondSet.iterator(); it.hasNext();) { BluetoothDevice bluetoothDevice = (BluetoothDevice) it.next(); JSONObject deviceInfo = new JSONObject(); deviceInfo.put("name", bluetoothDevice.getName()); deviceInfo.put("address", bluetoothDevice.getAddress()); deviceInfo.put("isBonded", true); bondedDevices.put(deviceInfo); } callbackContext.success(bondedDevices); return true; } else if (ACTION_FETCHUUIDS.equals(action)) { final String address = args.getString(0); this.callback_uuids = callbackContext; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { String msg = "Not supported, minimum SDK version is :" + Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1; logErr(msg); callbackContext.error(msg); return true; } try { logDbg("Listing UUIDs for : " + address); // Fetch UUIDs from bluetooth device BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address); // min api 15 !!! Method m = bluetoothDevice.getClass().getMethod("fetchUuidsWithSdp", (Class[]) null); m.invoke(bluetoothDevice, (Object[]) null); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } catch (Exception e) { logErr(e.toString() + " / " + e.getMessage()); callbackContext.error(e.getMessage()); } return true; } else if (ACTION_CONNECT.equals(action)) { final String address = args.getString(0); final String uuid = args.getString(1); final boolean secure = args.getBoolean(2); this.callback_connect = callbackContext; cordova.getThreadPool().execute(new Runnable() { public void run() { BluetoothSocket socket = null; try { logDbg("Connecting..."); // Cancel discovery because it will slow down the connection if (m_bluetoothAdapter.isDiscovering()) m_bluetoothAdapter.cancelDiscovery(); //JWC adding /* BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address); //"74:45:8A:B2:4E:9A"); //Method m = device.getClass().getMethod("createInsecureRfcommSocket", // new Class[] { int.class }); //socket = (BluetoothSocket)m.invoke(device, Integer.valueOf(1)); socket = device.createRfcommSocketToServiceRecord(java.util.UUID.fromString(uuid)); */ ////// System.out.println("BluetoothPlugin2.ACTION_CONNECT address=" + address + ", uuid=" + uuid + ", secure=" + secure); BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address); //"74:45:8A:B2:4E:9A"); socket = device.createInsecureRfcommSocketToServiceRecord(java.util.UUID.fromString(uuid)); // for others devices its works with: // Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}); // for galaxy tab 2 with: //Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class}); //socket = (BluetoothSocket) m.invoke(device, 1); socket.connect(); /////JWC READ System.out.println("BluetoothPlugin2 trying to read right away..."); final int socketId = 0; //args.getInt(0); final int bufferSize = 512; //args.getInt(1); //this.callback_read = callbackContext; ReadThread readThread = new ReadThread(m_sockets.get(socketId), socketId, bufferSize); readThread.start(); m_readThreads.add(readThread); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); /////////////// /* JWC removing BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice( address); if (secure) { socket = connectSecureHelper( bluetoothDevice, UUID.fromString(uuid)); } else { socket = connectInsecureHelper( bluetoothDevice, UUID.fromString(uuid)); } */ } catch (Exception e) { logErr(e.toString() + " / " + e.getMessage()); callback_connect.error(e.getMessage()); } if (socket != null) { logDbg("Connected"); m_sockets.add(socket); int socketId = m_sockets.indexOf(socket); callback_connect.sendPluginResult(new PluginResult(PluginResult.Status.OK, socketId)); } else { callback_connect.error(0); } } }); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_DISCONNECT.equals(action)) { final int socketId = args.getInt(0); try { BluetoothSocket socket = m_sockets.get(socketId); logDbg("Close socket"); socket.close(); logDbg("Delete socket from list"); m_sockets.remove(socketId); for (int i = 0; i < m_readThreads.size(); i++) { if (m_readThreads.get(i).socketId == socketId) { m_readThreads.remove(i); break; } } callbackContext.success(); } catch (Exception e) { logErr(e.toString() + " / " + e.getMessage()); callbackContext.error(e.getMessage()); } return true; } else if (ACTION_LISTEN.equals(action)) { final String name = args.getString(0); final String uuid = args.getString(1); final boolean secure = args.getBoolean(2); System.out.println( "BluetoothPlugin2.ACTION_LISTEN name=" + name + ", uuid=" + uuid + ", secure=" + secure); this.callback_listen = callbackContext; if (m_listenThread != null) { m_listenThread.cancel(); m_listenThread = null; } m_listenThread = new ListenThread(this.cordova, name, UUID.fromString(uuid), secure); m_listenThread.start(); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_CANCEL_LISTENING.equals(action)) { if (m_listenThread != null) { m_listenThread.cancel(); } m_listenThread = null; callbackContext.success(); return true; } else if (ACTION_READ.equals(action)) { final int socketId = args.getInt(0); final int bufferSize = args.getInt(1); System.out.println("BluetoothPlugin2.ACTION_READ socketId=" + socketId + ", bufferSize=" + bufferSize); this.callback_read = callbackContext; ReadThread readThread = new ReadThread(m_sockets.get(socketId), socketId, bufferSize); readThread.start(); m_readThreads.add(readThread); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); return true; } else if (ACTION_WRITE.equals(action)) { final int socketId = args.getInt(0); final JSONArray jsonArray = args.getJSONArray(1); try { OutputStream outputStream = m_sockets.get(socketId).getOutputStream(); byte[] buffer = new byte[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { buffer[i] = (byte) jsonArray.getInt(i); } outputStream.write(buffer); callbackContext.success(); } catch (Exception e) { logErr(e.toString() + " / " + e.getMessage()); callbackContext.error(e.getMessage()); } return true; } return false; }
From source file:com.megster.cordova.BluetoothPlugin.java
/** * Execute a bluetooth function//from ww w . ja v a 2 s. co m */ @SuppressWarnings({ "null", "deprecation" }) @Override public PluginResult execute(String action, JSONArray args, String callbackId) { PluginResult pluginResult = null; //Log.d("BluetoothPlugin", "Action: " + action); // Check if bluetooth is supported at all if (m_bluetoothAdapter == null) { pluginResult = new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION, "No bluetooth adapter found"); } else { if (ACTION_ENABLE.equals(action)) { // Check if bluetooth isn't disabled already if (!m_bluetoothAdapter.isEnabled()) { m_stateChanging = true; ctx.startActivityForResult(this, new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 1); while (m_stateChanging) { } ; } // Check if bluetooth is enabled now if (m_bluetoothAdapter.isEnabled()) { //start(); pluginResult = new PluginResult(PluginResult.Status.OK, "OK"); } else { pluginResult = new PluginResult(PluginResult.Status.ERROR, "Bluetooth not enabled"); } } // Want to disable bluetooth? else if (ACTION_DISABLE.equals(action)) { if (!m_bluetoothAdapter.disable() && m_bluetoothAdapter.isEnabled()) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "Unable to disable bluetooth"); } else { pluginResult = new PluginResult(PluginResult.Status.OK, "OK"); } } else if (ACTION_DISCOVERDEVICES.equals(action)) { m_discoveredDevices = new JSONArray(); if (!m_bluetoothAdapter.startDiscovery()) { pluginResult = new PluginResult(PluginResult.Status.ERROR, "Unable to start discovery"); } else { m_discovering = true; // Wait for discovery to finish while (m_discovering) { } Log.d("BluetoothPlugin", "DiscoveredDevices: " + m_discoveredDevices.length()); pluginResult = new PluginResult(PluginResult.Status.OK, m_discoveredDevices); } } // Want to list UUIDs of a certain device else if (ACTION_GETUUIDS.equals(action)) { try { String address = args.getString(0); Log.d("BluetoothPlugin", "Listing UUIDs for: " + address); // Fetch UUIDs from bluetooth device BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address); Method m = bluetoothDevice.getClass().getMethod("fetchUuidsWithSdp"); Log.d("BluetoothPlugin", "Method: " + m); m.invoke(bluetoothDevice); m_gettingUuids = true; while (m_gettingUuids) { } pluginResult = new PluginResult(PluginResult.Status.OK, m_gotUUIDs); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else if (ACTION_GETBONDEDDEVICES.equals(action)) { JSONArray bondedDevices = new JSONArray(); Log.d("BluetoothPlugin", "Getting Bonded List..."); Set<BluetoothDevice> bondSet = m_bluetoothAdapter.getBondedDevices(); for (Iterator<BluetoothDevice> it = bondSet.iterator(); it.hasNext();) { BluetoothDevice bluetoothDevice = (BluetoothDevice) it.next(); JSONObject deviceInfo = new JSONObject(); try { deviceInfo.put("name", bluetoothDevice.getName()); deviceInfo.put("address", bluetoothDevice.getAddress()); deviceInfo.put("isBonded", true); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } bondedDevices.put(deviceInfo); pluginResult = new PluginResult(PluginResult.Status.OK, bondedDevices); } } // Connect to a given device & uuid endpoint else if (ACTION_CONNECT.equals(action)) { try { String address = args.getString(0); UUID uuid = UUID.fromString(args.getString(1)); //UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); Log.d("BluetoothPlugin", "Connecting..."); BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address); BluetoothSocket bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid); bluetoothSocket.connect(); m_bluetoothSockets.add(bluetoothSocket); int socketId = m_bluetoothSockets.indexOf(bluetoothSocket); pluginResult = new PluginResult(PluginResult.Status.OK, socketId); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else if (ACTION_READ.equals(action)) { try { int socketId = args.getInt(0); //Log.d( "BluetoothPlugin", "Get Data..." ); BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId); InputStream inputStream = bluetoothSocket.getInputStream(); Calendar cal = Calendar.getInstance(); Date startTime = cal.getTime(); byte[] buffer = new byte[1024]; // char [] buffer = new char[1024]; String recvdString = ""; int i = 0; int k = 0; int byteCnt = 0; boolean j = true; char buf = 0; boolean timeOut = false; while (j) { Calendar newCal = Calendar.getInstance(); Date endTime = newCal.getTime(); if ((endTime.getTime() - startTime.getTime()) < 60000) { if (inputStream.available() > 0) { // Log.d( "BluetoothPlugin", "Time Increment: " + format.format(endTime)); i += inputStream.read(buffer, k, inputStream.available()); k = i; Log.d("BluetoothPlugin", "i=" + i); buf = (char) (buffer[i - 1] & 0xFF); Log.d("BluetoothPlugin", "buf=" + Integer.toHexString(buffer[i - 1] & 0xFF)); if ((buf == '#') || (buf == 0x0A) || (buf == (char) 0xBB) || (buf == (char) 0xAA)) { //if (timeOut == true) Log.d( "BluetoothPlugin", "Time Out"); j = false; } } } else { timeOut = true; j = false; } /* buffer[i]= (char) inputStream.read(); if ((buffer[i] == '#') || (buffer[i]==0x0A)) { j=false; } i++; */ } if (timeOut) { Log.d("BluetoothPlugin", "Time Out"); recvdString = "Timeout"; } else { byteCnt = i; recvdString = new String(buffer, 0, i);//.toString();//"KBytes" + byteCnt; i = 0; String stringByteCnt = String.valueOf(byteCnt); } //buffer = b.toString(); Log.d("BluetoothPlugin", "String: " + recvdString); pluginResult = new PluginResult(PluginResult.Status.OK, recvdString); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else if (ACTION_READ2.equals(action)) { try { int socketId = args.getInt(0); Calendar cal = Calendar.getInstance(); Date startTime = cal.getTime(); //Log.d( "BluetoothPlugin", "Get Data..." ); BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId); InputStream inputStream = bluetoothSocket.getInputStream(); // DataInputStream dataInputStream = new DataInputStream(inputStream); //char[] buffer = new char[15000]; byte[] buf = new byte[55000]; //byte[] buffer2 = new byte[128]; String recvdString = ""; int i = 0; int k = 0; int byteCnt = 0; boolean j = true; SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Log.d("BluetoothPlugin", "StartTime: " + format.format(startTime)); boolean timeOut = false; while (j) { Calendar newCal = Calendar.getInstance(); Date endTime = newCal.getTime(); if ((endTime.getTime() - startTime.getTime()) < 12000) { if (inputStream.available() > 0) { // Log.d( "BluetoothPlugin", "Time Increment: " + format.format(endTime)); i += inputStream.read(buf, k, inputStream.available()); k = i; Log.d("BluetoothPlugin", "i=" + i); } //Log.d( "BluetoothPlugin", "i="+dataInputStream); //inputStream.close(); if (i > 51180) { //Log.d( "BluetoothPlugin", "i="+i); j = false; //i++; } } else { j = false; timeOut = true; Log.d("BluetoothPlugin", "ECG Read TimeOut"); } } if (timeOut) { recvdString = "Aborted"; } else { File ecgPath = Environment.getExternalStorageDirectory(); File ecg = new File(ecgPath, "/prago/ecg.txt"); FileWriter fos = new FileWriter(ecg, false); String stringBuf = new String(""); //long byteCnt byteCnt = (i - 1) / 3; long[] buf2 = new long[byteCnt]; for (k = 0; k < byteCnt; k++) { int firstByte = 0; int secondByte = 0; int thirdByte = 0; int fourthByte = 0; int index = k * 3; firstByte = (0x000000FF & ((int) buf[index + 1])); secondByte = (0x000000FF & ((int) buf[index + 2])); thirdByte = (0x000000FF & ((int) buf[index + 3])); buf2[k] = ((long) (firstByte << 16 | secondByte << 8 | thirdByte)) & 0xFFFFFFFFL; stringBuf = buf2[k] + ","; fos.write(stringBuf); } fos.flush(); fos.close(); byteCnt = i; recvdString = ecg.getPath(); } i = 0; pluginResult = new PluginResult(PluginResult.Status.OK, recvdString); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else if (ACTION_READ3.equals(action)) { try { int socketId = args.getInt(0); Log.d("BluetoothPlugin", "Get Steth Data..."); BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId); //bluetoothSocket.close(); //bluetoothSocket = m_bluetoothSockets.get(socketId); //bluetoothSocket.connect(); InputStream inputStream = bluetoothSocket.getInputStream(); //inputStream.reset(); //int server_port = 9999; //DatagramSocket s = new DatagramSocket(); //InetAddress local = InetAddress.getByName("192.168.2.7"); //s.connect(local,server_port); //int msg_length=messageStr.length(); //byte[] message = messageStr.getBytes(); //char[] buffer = new char[15000]; //byte [] buf = new byte[10000]; //byte[] buffer2 = new byte[128]; // String recvdString; Calendar cal = Calendar.getInstance(); //byte [] buf = new byte[245000]; Date startTime = cal.getTime(); String recvdString = ""; int i = 0; int endofFileDetect = 0; byte[] firstChar = new byte[1]; int writetoFile = 0; int k = 0; long finalbytes = 0; boolean startdetect = false; int byteCnt = 0; boolean j = true; boolean ecgRec = false; byte[] buf = new byte[10000]; firstChar[0] = 0x52; File stethPath = Environment.getExternalStorageDirectory(); File steth = new File(stethPath, "/prago/steth.wav"); FileOutputStream fos = new FileOutputStream(steth); while (j) { Calendar newCal = Calendar.getInstance(); Date endTime = newCal.getTime(); if ((endTime.getTime() - startTime.getTime()) < 90000) { if (inputStream.available() > 0) { //Log.d( "BluetoothPlugin", "inputStream.available="+inputStream.available()); //byte [] buf = new byte[inputStream.available()]; k = inputStream.read(buf, 0, inputStream.available()); //Log.d( "BluetoothPlugin", "buf[0]="+buf[0]); if ((writetoFile == 0)) { if ((buf[0] & 0xFF) == 0x52) { if (k > 1) { if ((buf[1] & 0xFF) == 0x49) { writetoFile = 1; i = 0; } } else { startdetect = true; } } else if (((buf[0] & 0xFF) == 0x49) && startdetect == true) { fos.write(firstChar, 0, 1); writetoFile = 1; i = 0; } else { startdetect = false; } } if (writetoFile == 1) { i += k; //Log.d( "BluetoothPlugin", "i="+i); //Log.d( "BluetoothPlugin", "k="+k); fos.write(buf, 0, k); //if (k>1)Log.d( "BluetoothPlugin", "buf[k-2]="+Integer.toHexString(buf[k-2]&0xFF)); //Log.d( "BluetoothPlugin", "buf[k-1]="+Integer.toHexString(buf[k-1]&0xFF)); if ((k > 1) && ((buf[k - 2] & 0xFF) == 0xAA) && ((buf[k - 1] & 0xFF) == 0xBB)) { endofFileDetect = 2; // Log.d( "BluetoothPlugin", "EoF Detected Multibyte"); } else if ((k == 1) && ((buf[0] & 0xFF) == 0xAA)) { endofFileDetect = 1; // Log.d( "BluetoothPlugin", "EoF Detected Firstbyte"); } else if (((buf[0] & 0xFF) == 0xBB) && (endofFileDetect == 1)) { endofFileDetect += 1; // Log.d( "BluetoothPlugin", "EoF Detected Sectbyte"); } else { endofFileDetect = 0; } if (endofFileDetect == 2) { Log.d("BluetoothPlugin", "File Write Complete"); //Log.d( "BluetoothPlugin", "i="+i); fos.flush(); fos.close(); j = false; //i++; recvdString = steth.getPath(); } } // DatagramPacket p = new DatagramPacket(buf, k,local,server_port); // s.send(p);// DataInputStream dataInputStream = new DataInputStream(inputStream); } //Log.d( "BluetoothPlugin", "i="+dataInputStream); //inputStream.close(); } else { j = false; //timeOut=true; Log.d("BluetoothPlugin", "Steth Read TimeOut"); //bluetoothSocket.close(); // recvdString= "Aborted"; fos.flush(); fos.close(); recvdString = steth.getPath(); } } pluginResult = new PluginResult(PluginResult.Status.OK, recvdString); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } //--change--// else if (ACTION_READ5.equals(action)) { try { int socketId = args.getInt(0); Log.d("BluetoothPlugin", "Transfer Steth Data..."); BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId); //bluetoothSocket.close(); //bluetoothSocket = m_bluetoothSockets.get(socketId); //bluetoothSocket.connect(); InputStream inputStream = bluetoothSocket.getInputStream(); //inputStream.reset(); //int server_port = 9999; //DatagramSocket s = new DatagramSocket(); //InetAddress local = InetAddress.getByName("192.168.2.7"); //s.connect(local,server_port); //int msg_length=messageStr.length(); //byte[] message = messageStr.getBytes(); //char[] buffer = new char[15000]; //byte [] buf = new byte[10000]; //byte[] buffer2 = new byte[128]; //String recvdString; Calendar cal = Calendar.getInstance(); //byte [] buf = new byte[245000]; Date startTime = cal.getTime(); String recvdString = ""; int i = 0; int endofFileDetect = 0; byte[] firstChar = new byte[1]; int writetoFile = 0; int k = 0; long finalbytes = 0; boolean startdetect = false; int byteCnt = 0; boolean j = true; boolean ecgRec = false; byte[] buf = new byte[10000]; firstChar[0] = 0x52; File stethPath = Environment.getExternalStorageDirectory(); File steth = new File(stethPath, "/prago/steth.wav"); FileOutputStream fos = new FileOutputStream(steth); while (j) { Calendar newCal = Calendar.getInstance(); Date endTime = newCal.getTime(); if ((endTime.getTime() - startTime.getTime()) < 5000) { if (inputStream.available() > 0) { // Log.d( "BluetoothPlugin", "inputStream.available="+inputStream.available()); cal = Calendar.getInstance(); startTime = cal.getTime(); //byte [] buf = new byte[inputStream.available()]; k = inputStream.read(buf, 0, inputStream.available()); //Log.d( "BluetoothPlugin", "buf[0]="+buf[0]); if ((writetoFile == 0)) { if ((buf[0] & 0xFF) == 0x52) { if (k > 1) { if ((buf[1] & 0xFF) == 0x49) { writetoFile = 1; i = 0; } } else { startdetect = true; } } else if (((buf[0] & 0xFF) == 0x49) && startdetect == true) { fos.write(firstChar, 0, 1); writetoFile = 1; i = 0; } else { startdetect = false; } } if (writetoFile == 1) { i += k; //Log.d( "BluetoothPlugin", "i="+i); //Log.d( "BluetoothPlugin", "k="+k); fos.write(buf, 0, k); //if (k>1)Log.d( "BluetoothPlugin", "buf[k-2]="+Integer.toHexString(buf[k-2]&0xFF)); //Log.d( "BluetoothPlugin", "buf[k-1]="+Integer.toHexString(buf[k-1]&0xFF)); if ((k > 1) && ((buf[k - 2] & 0xFF) == 0xAA) && ((buf[k - 1] & 0xFF) == 0xBB)) { endofFileDetect = 2; // Log.d( "BluetoothPlugin", "EoF Detected Multibyte"); } else if ((k == 1) && ((buf[0] & 0xFF) == 0xAA)) { endofFileDetect = 1; // Log.d( "BluetoothPlugin", "EoF Detected Firstbyte"); } else if (((buf[0] & 0xFF) == 0xBB) && (endofFileDetect == 1)) { endofFileDetect += 1; // Log.d( "BluetoothPlugin", "EoF Detected Sectbyte"); } else { endofFileDetect = 0; } if (endofFileDetect == 2) { Log.d("BluetoothPlugin", "File Write Complete"); //Log.d( "BluetoothPlugin", "i="+i); fos.flush(); fos.close(); j = false; //i++; recvdString = steth.getPath(); } } // DatagramPacket p = new DatagramPacket(buf, k,local,server_port); // s.send(p);// DataInputStream dataInputStream = new DataInputStream(inputStream); } //Log.d( "BluetoothPlugin", "i="+dataInputStream); //inputStream.close(); } else { j = false; //timeOut=true; Log.d("BluetoothPlugin", "Steth Read TimeOut"); //bluetoothSocket.close(); // recvdString= "Aborted"; fos.flush(); fos.close(); recvdString = steth.getPath(); } } pluginResult = new PluginResult(PluginResult.Status.OK, recvdString); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } //--change--// else if (ACTION_READ4.equals(action)) { try { start(); // int socketId = args.getInt(0); Log.d("BluetoothPlugin", "Make Discoverable"); BluetoothAdapter mBluetoothAdapter = null; ctx.startActivityForResult(this, new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE), 1); m_discoverable = true; Calendar cal = Calendar.getInstance(); Date startTime = cal.getTime(); Calendar newCal = Calendar.getInstance(); String recvdString = ""; Date endTime = newCal.getTime(); while (m_discoverable && ((endTime.getTime() - startTime.getTime()) < 32000)) { newCal = Calendar.getInstance(); endTime = newCal.getTime(); } if (m_discoverable) { recvdString = "No Device"; } else { Log.d("BluetoothPlugin", "Connected with Remote Device"); BluetoothSocket bluetoothSocket = bluetoothListenSocket; InputStream inputStream = bluetoothSocket.getInputStream(); int i = 0; int k = 0; boolean j = true; boolean measurementComplete = false; // boolean measurementOngoing = false; boolean measurementStart = false; float decweight = 0; int[] buf = new int[100]; while (!measurementComplete) { buf[i] = inputStream.read(); if ((i > 5) && (buf[i] == 0x02) && (buf[i - 6] == 0x93) && (buf[i - 1] == 0x00) && !measurementStart) { measurementStart = true; } if (measurementStart && (buf[i - 1] == 0x04) && (buf[i - 7] == 0x93) && (buf[i - 2] == 0x0)) { measurementComplete = true; measurementStart = false; // measurementOngoing = false; decweight = (buf[i - 10] << 8) + buf[i - 9]; } i++; Log.d("BluetoothPlugin", "i=" + i); } // String recvdString= new String(buf,0,i,"ISO-8859-1");;//new String(buf,0,i,"ISO-8859-1");//.toString();//"KBytes" + byteCnt; float weight = decweight / 100; //weight += decweight/100; recvdString = "" + weight; bluetoothSocket.close(); Log.d("BluetoothPlugin", "Disconnected with Remote Device"); } pluginResult = new PluginResult(PluginResult.Status.OK, recvdString); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else if (ACTION_WRITE.equals(action)) { try { int socketId = args.getInt(0); byte[] value = { 0x11, 0x0d, 0x44, 0x4d, 0x50 }; // byte[] value = {(byte)0x11,(byte)0x0D, (byte)0x0A, (byte)0x44, (byte)0x4D, (byte)0x46}; String string = new String(value); char sendCmd = 'g'; byte sendCmdByte = (byte) sendCmd;//.getBytes("UTF-16LE"); byte[] data = args.getString(1).getBytes("UTF-8"); if (data[0] == sendCmdByte) { data = value; Log.d("BluetoothPlugin", "Sending Onetouch Ultra2 Commands..."); } else if (data[0] == 'e') { data = args.getString(1).getBytes("UTF-8"); //Log.d( "BluetoothPlugin", "Sending +tronic Commands..." + args.getString(1)); } else { data = args.getString(1).getBytes("UTF-16LE"); //Log.d( "BluetoothPlugin", "Sending +tronic Commands..." + args.getString(1)); } //Log.d( "BluetoothPlugin", "Write Data..." + string ); BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId); OutputStream outputStream = bluetoothSocket.getOutputStream(); outputStream.write(data); outputStream.flush(); //outputStream.close(); //Log.d( "BluetoothPlugin", "Buffer: " + String.valueOf(buffer) ); pluginResult = new PluginResult(PluginResult.Status.OK, "Success"); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else if (ACTION_DISCONNECT.equals(action)) { try { int socketId = args.getInt(0); // Fetch socket & close it BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId); bluetoothSocket.close(); // Remove socket from internal list m_bluetoothSockets.remove(socketId); // Everything went fine... pluginResult = new PluginResult(PluginResult.Status.OK, "OK"); } catch (Exception e) { Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage()); pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } } else { pluginResult = new PluginResult(PluginResult.Status.INVALID_ACTION, "Action '" + action + "' not supported"); } } return pluginResult; }
From source file:com.lauszus.launchpadflightcontrollerandroid.app.LaunchPadFlightControllerActivity.java
@Override public void onStart() { super.onStart(); if (D)/*from www .j a v a2 s . c o m*/ Log.d(TAG, "++ ON START ++"); // If BT is not on, request that it be enabled. // setupChat() will then be called during onActivityResult if (!mBluetoothAdapter.isEnabled()) { if (D) Log.d(TAG, "Request enable BT"); Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } else setupBTService(); // Otherwise, setup the chat session }
From source file:com.bushstar.htmlcoin_android_wallet.ui.RequestCoinsFragment.java
@Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.request_coins_fragment, container, false); qrView = (ImageView) view.findViewById(R.id.request_coins_qr); qrView.setOnClickListener(new OnClickListener() { @Override//from w ww . j a v a 2 s. co m public void onClick(final View v) { BitmapFragment.show(getFragmentManager(), qrCodeBitmap); } }); final CurrencyAmountView HTML5AmountView = (CurrencyAmountView) view .findViewById(R.id.request_coins_amount_html5); HTML5AmountView.setCurrencySymbol(config.getHTML5Prefix()); HTML5AmountView.setInputPrecision(config.getHTML5MaxPrecision()); HTML5AmountView.setHintPrecision(config.getHTML5Precision()); HTML5AmountView.setShift(config.getHTML5Shift()); final CurrencyAmountView localAmountView = (CurrencyAmountView) view .findViewById(R.id.request_coins_amount_local); localAmountView.setInputPrecision(Constants.LOCAL_PRECISION); localAmountView.setHintPrecision(Constants.LOCAL_PRECISION); amountCalculatorLink = new CurrencyCalculatorLink(HTML5AmountView, localAmountView); acceptBluetoothPaymentView = (CheckBox) view.findViewById(R.id.request_coins_accept_bluetooth_payment); acceptBluetoothPaymentView .setVisibility(ENABLE_BLUETOOTH_LISTENING && bluetoothAdapter != null ? View.VISIBLE : View.GONE); acceptBluetoothPaymentView .setChecked(ENABLE_BLUETOOTH_LISTENING && bluetoothAdapter != null && bluetoothAdapter.isEnabled()); acceptBluetoothPaymentView.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) { if (ENABLE_BLUETOOTH_LISTENING && bluetoothAdapter != null && isChecked) { if (bluetoothAdapter.isEnabled()) { startBluetoothListening(); } else { // ask for permission to enable bluetooth startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), REQUEST_CODE_ENABLE_BLUETOOTH); } } else { stopBluetoothListening(); } updateView(); } }); initiateRequestView = (TextView) view.findViewById(R.id.request_coins_fragment_initiate_request); return view; }