List of usage examples for android.bluetooth BluetoothAdapter isEnabled
@RequiresPermission(Manifest.permission.BLUETOOTH) public boolean isEnabled()
From source file:io.v.android.libs.discovery.ble.BlePlugin.java
public BlePlugin(Context androidContext) { this.androidContext = androidContext; cachedDevices = new DeviceCache(Duration.standardMinutes(1)); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) { return;/* w w w .j av a 2 s. co m*/ } if (!hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION) && !hasPermission(Manifest.permission.ACCESS_FINE_LOCATION)) { return; } isEnabled = true; bluetoothLeAdvertise = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser(); bluetoothLeScanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner(); BluetoothManager manager = (BluetoothManager) androidContext.getSystemService(Context.BLUETOOTH_SERVICE); bluetoothGattServer = manager.openGattServer(androidContext, new BluetoothGattServerCallback() { @Override public void onConnectionStateChange(BluetoothDevice device, int status, int newState) { super.onConnectionStateChange(device, status, newState); } @Override public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) { super.onCharacteristicReadRequest(device, requestId, offset, characteristic); byte[] total = characteristic.getValue(); byte[] res = {}; // Only send MTU - 1 bytes. The first byte of all packets is the op code. if (offset < total.length) { int finalByte = offset + MTU - 1; if (finalByte > total.length) { finalByte = total.length; } res = Arrays.copyOfRange(total, offset, finalByte); bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, res); } else { // This should probably be an error, but a bug in the paypal/gatt code causes an // infinite loop if this returns an error rather than the empty value. bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, res); } } }); }
From source file:com.spondbob.bluetooth.BluetoothActivity.java
private void menuDiscover() { BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Toast.makeText(BluetoothActivity.this, "Device does not support Bluetooth", Toast.LENGTH_SHORT).show(); } else {//ww w.j av a 2s .c o m if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } else { doDiscovery(); } } }
From source file:com.sweetiepiggy.littlepro.LittleProActivity.java
private BluetoothDevice getBluetoothPair() { BluetoothDevice pairedDevice = null; BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { Toast.makeText(getApplicationContext(), new Error("Bluetooth not found").getMessage(), Toast.LENGTH_SHORT).show(); } else if (!bluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, ACTIVITY_ENABLE_BLUETOOTH); } else {//w w w . ja v a 2s. c om Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); Toast.makeText(getApplicationContext(), pairedDevices.size() + " paired devices found", Toast.LENGTH_SHORT).show(); switch (pairedDevices.size()) { case 0: // bluetoothAdapter.startDiscovery(); break; case 1: pairedDevice = pairedDevices.iterator().next(); break; /* choose device */ default: // for (pd : pairedDevices) { // } break; } } return pairedDevice; }
From source file:net.emilymaier.movebot.HeartFragment.java
@Override @SuppressWarnings("deprecation") public void onClick(View view) { Log.d("HeartFragment", "Scan button clicked"); final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { new NoBluetoothDialogFragment().show(act.getSupportFragmentManager(), "bluetooth"); return;/*from www . j av a2s . c o m*/ } if (!bluetoothAdapter.isEnabled()) { new BluetoothDisabledDialogFragment().show(act.getSupportFragmentManager(), "disabled"); return; } if (!act.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { new NoLeDialogFragment().show(act.getSupportFragmentManager(), "le"); return; } Log.d("HeartFragment", "Starting scan"); heartScan.setClickable(false); heartScan.setText("Scanning..."); for (HeartDevice device : heartDevices) { device.bluetoothGatt.disconnect(); device.bluetoothGatt.close(); } heartDevices.clear(); heartListAdapter.notifyDataSetChanged(); bluetoothAdapter.startLeScan(new UUID[] { UUID.fromString("0000180d-0000-1000-8000-00805f9b34fb") }, this); final HeartFragment t = this; new Handler().postDelayed(new Runnable() { @Override public void run() { Log.d("HeartFragment", "Stopping scan"); bluetoothAdapter.stopLeScan(t); heartScan.setText("Scan"); heartScan.setClickable(true); heartListAdapter.notifyDataSetChanged(); } }, 5000); }
From source file:org.jonblack.bluetrack.activities.LiveTrackingFragment.java
public boolean onOptionsItemSelected(MenuItem item) { // TODO: Bit odd that the LiveTrackingFragment is responsible for this. switch (item.getItemId()) { case R.id.menu_toggle_tracking: if (mTracking) { stopBluetoothLogService();//from w w w. jav a2 s. com } else { // Check that bluetooth is enabled. If it isn't, ask the user to // enable it. If the user enables it, the BluetoothLogService will be // started in the callback. BluetoothAdapter localBtAdapter = BluetoothAdapter.getDefaultAdapter(); assert (localBtAdapter != null); if (!localBtAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } else { startBluetoothLogService(); } } // Cause the action bar menu to be updated so the button text can change. ((SherlockFragmentActivity) getActivity()).invalidateOptionsMenu(); break; case R.id.menu_settings: Intent intent = new Intent(getActivity(), SettingsActivity.class); startActivity(intent); break; default: assert (false); } return true; }
From source file:project.cs.lisa.application.html.NetInfWebViewClient.java
/** * Returns a NetInfPublish request object that can be used in order * to publish an IO./* w ww . j a v a2 s . co m*/ * * @param file The file corresponding to the IO * @param url The url where that file was downloaded from * @param hash The hash identifying the file * @param contentType The content type of the file * @return Returns a publish request object * @throws IOException Thrown, if Bluetooth is not available */ private NetInfPublish createPublishRequest(File file, URL url, String hash, String contentType) throws IOException { // Create metadata Metadata metadata = new Metadata(); metadata.insert("filesize", String.valueOf(file.length())); metadata.insert("filepath", file.getAbsolutePath()); metadata.insert("time", Long.toString(System.currentTimeMillis())); metadata.insert("url", url.toString()); // Try to get the Bluetooth MAC BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter == null) { throw new IOException("Error: Bluetooth not supported"); } else if (!adapter.isEnabled()) { throw new IOException("Error: Bluetooth not enabled"); } else { // Create Locator set to be used in the publish HashSet<Locator> locators = new HashSet<Locator>(); locators.add(new Locator(Locator.Type.BLUETOOTH, adapter.getAddress())); // Create the publish, adding locators, content type, and metadata NetInfPublish publishRequest = new NetInfPublish(HASH_ALG, hash, locators); publishRequest.setContentType(contentType); publishRequest.setMetadata(metadata); // Check for full put SharedPreferences sharedPref = PreferenceManager .getDefaultSharedPreferences(MainApplicationActivity.getActivity().getApplicationContext()); boolean isFullPutAvailable = sharedPref.getBoolean("pref_key_fullput", false); if (isFullPutAvailable) { publishRequest.setFile(file); } return publishRequest; } }
From source file:org.imdea.panel.MainActivity.java
public void enableBt() { BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter(); if (!mAdapter.isEnabled()) mAdapter.enable(); //Turn On Bluetooth without Permission /*if (!mAdapter.isEnabled()) startActivity(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE));*/ while (!mAdapter.isEnabled()) { }/*from w ww. j a v a 2 s. c o m*/ String restoredMAC = SP.getString("MAC", null); if (restoredMAC != null) { Global.DEVICE_ADDRESS = restoredMAC; if (restoredMAC.equals("00:00:00:00:00:00")) { Global.DEVICE_ADDRESS = mAdapter.getAddress(); SharedPreferences.Editor editor = SP.edit(); editor.putString("MAC", Global.DEVICE_ADDRESS); editor.apply(); } } else { Global.DEVICE_ADDRESS = mAdapter.getAddress(); SharedPreferences.Editor editor = SP.edit(); editor.putString("MAC", Global.DEVICE_ADDRESS); editor.apply(); } Log.w("MAC", Global.DEVICE_ADDRESS); if (mAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0); startActivity(discoverableIntent); } }
From source file:com.lge.helloFriendsCamera.ConnectionActivity.java
/** * Ask permissions and start scan if all permissions are granted *//*from ww w . j av a 2 s .c o m*/ private void checkBleScanPermissionAndStartScan() { Log.d(TAG, "PERMISSION_REQUEST: BLUETOOTH AND ACCESS_FINE_LOCATION"); int loc_permissionCheck = ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION); //Enable wifi if (!mWifiManager.isWifiEnabled()) mWifiManager.setWifiEnabled(true); //Enable bt BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (!bluetoothAdapter.isEnabled()) { Log.d(TAG, "Request bluetooth enable"); Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); return; } //Get permission (ACCESS_FINE_LOCATION) if (loc_permissionCheck != PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "Request ACTION_FINE_LOCATION permission"); ActivityCompat.requestPermissions((Activity) mContext, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); return; } startScanDevice(); }
From source file:samples.piggate.com.piggateCompleteExample.Activity_Logged.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); _piggate = new Piggate(this, null); //Initialize the Piggate object setContentView(R.layout.activity_logged); getSupportActionBar().setTitle(PiggateUser.getEmail()); startService(new Intent(getApplicationContext(), Service_Notify.class)); //Start the service //Initialize and set all the left navigation drawer fields mDrawer = new Drawer().withActivity(this).withTranslucentStatusBar(false).withHeader(R.layout.drawerheader) .addDrawerItems( /* Add drawer items with this method */) .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { @Override// w ww.ja v a2s .c om public void onItemClick(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem) { // Open the exchange activity for the selected item Intent slideactivity = new Intent(Activity_Logged.this, Activity_Exchange.class); slideactivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); //Send the current offer information to the exchange activity slideactivity.putExtra("offerName", exchangeOfferList.get(position).getName().toString()); slideactivity.putExtra("offerDescription", exchangeOfferList.get(position).getDescription().toString()); slideactivity.putExtra("offerImgURL", exchangeOfferList.get(position).getImgURL().toString()); slideactivity.putExtra("exchangeID", exchangeOfferList.get(position).getExchangeID().toString()); Bundle bndlanimation = ActivityOptions.makeCustomAnimation(Activity_Logged.this, R.anim.slidefromright, R.anim.slidetoleft).toBundle(); startActivity(slideactivity, bndlanimation); } }).withSliderBackgroundColor(Color.parseColor("#FFFFFF")).withSelectedItem(-1).build(); //Initialize recycler view mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); mRecyclerView.setHasFixedSize(true); mRecyclerView.setLayoutManager(new LinearLayoutManager(Activity_Logged.this)); mRecyclerView.setItemAnimator(new DefaultItemAnimator()); newBeaconsLayout = (LinearLayout) findViewById(R.id.newBeaconsLayout); //Initialize swipe layout mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container); mSwipeLayout.setOnRefreshListener(this); errorDialog = new AlertDialog.Builder(this).create(); errorDialog.setTitle("Logout error"); errorDialog.setMessage("There is an error with the logout"); errorDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); successPaymentDialog = new AlertDialog.Builder(this).create(); successPaymentDialog.setTitle("Successful payment"); successPaymentDialog.setMessage("Now you can exchange your purchased product"); successPaymentDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); errorBuyDialog = new AlertDialog.Builder(this).create(); errorBuyDialog.setTitle("Payment failed"); errorBuyDialog.setMessage("There is an error with your payment"); errorBuyDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); successExchangeDialog = new AlertDialog.Builder(this).create(); successExchangeDialog.setTitle("Offer successfully exchanged"); successExchangeDialog.setMessage("The offer has been purchased and exchanged"); successExchangeDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); errorExchangeDialog = new AlertDialog.Builder(this).create(); errorExchangeDialog.setTitle("Exchange error"); errorExchangeDialog.setMessage("There is an error with the exchange"); errorExchangeDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); networkErrorDialog = new AlertDialog.Builder(this).create(); networkErrorDialog.setTitle("Network error"); networkErrorDialog.setMessage("There is an error with the network connection"); networkErrorDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); fadeIn = AnimationUtils.loadAnimation(Activity_Logged.this, R.anim.fadein); fadeOut = AnimationUtils.loadAnimation(Activity_Logged.this, R.anim.fadeout); //Check if the bluetooth is switched on BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } if (getIntent().hasExtra("payment")) { if (getIntent().getExtras().getBoolean("payment") == true) { successPaymentDialog.show(); //Show success payment dialog mDrawer.openDrawer(); //Open the left panel } else { errorBuyDialog.show(); //Show payment error dialog } } else if (getIntent().hasExtra("exchanged")) { if (getIntent().getExtras().getBoolean("exchanged") == true) { successExchangeDialog.show(); //Show exchange success dialog } else { errorExchangeDialog.show(); //Show exchange error dialog } } }
From source file:com.example.RITW.Ble.BleProfileServiceReadyActivity.java
protected boolean isBLEEnabled() { final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); final BluetoothAdapter adapter = bluetoothManager.getAdapter(); return adapter != null && adapter.isEnabled(); }