@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); // mBluetoothAdapterの取得 mBluetoothAdapter = bluetoothManager.getAdapter(); // mBluetoothLeScannerの初期化 mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); Uri.Builder builder = new Uri.Builder(); AsyncHttpRequest task = new AsyncHttpRequest(this); task.execute(builder); scan(true); }
private void setupBLE() { if (!isBLESupported(this)) { Toast.makeText(this, "device not support ble", Toast.LENGTH_SHORT).show(); finish(); return; } BluetoothManager manager = getManager(this); if (manager != null) { mBTAdapter = manager.getAdapter(); } if ((mBTAdapter == null) || (!mBTAdapter.isEnabled())) { Toast.makeText(this, "bluetooth not open", Toast.LENGTH_SHORT).show(); Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); return; } }
@Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // initialize the right scan callback for the current API level if (Build.VERSION.SDK_INT >= 21) { mScanCallback = new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); mRecyclerViewAdapter.addDevice(result.getDevice().getAddress()); } }; } else { mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) { mRecyclerViewAdapter.addDevice(bluetoothDevice.getAddress()); } }; } // initialize bluetooth manager & adapter BluetoothManager manager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = manager.getAdapter(); }
static public boolean checkBluetooth(Context context){ BluetoothManager bm = (BluetoothManager) context.getSystemService(BLUETOOTH_SERVICE); BluetoothAdapter ba = bm.getAdapter(); if (ba == null) { //Bluetooth is disabled Log.e(TAG, "BluetoothAdapter not available!"); return false; } if(!ba.isEnabled()) { Log.w(TAG, "BluetoothAdapter not enabled!"); ba.enable(); } if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Log.e(TAG, "Bluetooth LE is not supported"); return false; } if(!ba.isMultipleAdvertisementSupported()){ Log.i(TAG, "No Multiple Advertisement Support!"); } return ba.isEnabled(); }
public BLEClient.BtError checkBluetooth(){ btManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); btAdapter = btManager.getAdapter(); if(!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) return BLEClient.BtError.NoBluetooth; if(!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) return BLEClient.BtError.NoBLE; if(btAdapter == null || !btAdapter.isEnabled()) return BLEClient.BtError.Disabled; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && useNewMethod){ if((ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) && (ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED)){ return BtError.NoLocationPermission; } LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); if(!(lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) && !(lm.isProviderEnabled(LocationManager.GPS_PROVIDER))){ return BtError.LocationDisabled; } } return BLEClient.BtError.None; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // We set the content View of this Activity setContentView(R.layout.activity_main); // Get all the TextViews deviceAddressTextView = (TextView) findViewById(R.id.device_address); actionTextView = (TextView) findViewById(R.id.action); rssiTextView = (TextView) findViewById(R.id.rssi); // Get the descriptions of the actions actionDescriptions = getResources().getStringArray(R.array.action_descriptions); // Get the BluetoothManager so we can get the BluetoothAdapter final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = bluetoothManager.getAdapter(); }
public void onCreate(Context context, GattServerListener listener) throws RuntimeException { mContext = context; mListener = listener; mBluetoothManager = (BluetoothManager) context.getSystemService(BLUETOOTH_SERVICE); BluetoothAdapter bluetoothAdapter = mBluetoothManager.getAdapter(); if (!checkBluetoothSupport(bluetoothAdapter)) { throw new RuntimeException("GATT server requires Bluetooth support"); } // Register for system Bluetooth events IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); mContext.registerReceiver(mBluetoothReceiver, filter); if (!bluetoothAdapter.isEnabled()) { Log.d(TAG, "Bluetooth is currently disabled... enabling"); bluetoothAdapter.enable(); } else { Log.d(TAG, "Bluetooth enabled... starting services"); startAdvertising(); startServer(); } }
private void prepareForScan() { if (isBleSupported()) { // Ensures Bluetooth is enabled on the device BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter btAdapter = btManager.getAdapter(); if (btAdapter.isEnabled()) { // Prompt for runtime permission if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { startLeScan(); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSION_LOCATION); } } else { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } } else { Toast.makeText(this, "BLE is not supported", Toast.LENGTH_LONG).show(); finish(); } }
public void onCreate(Context context, String deviceAddress, OnCounterReadListener listener) throws RuntimeException { mContext = context; mListener = listener; mDeviceAddress = deviceAddress; mBluetoothManager = (BluetoothManager) context.getSystemService(BLUETOOTH_SERVICE); mBluetoothAdapter = mBluetoothManager.getAdapter(); if (!checkBluetoothSupport(mBluetoothAdapter)) { throw new RuntimeException("GATT client requires Bluetooth support"); } // Register for system Bluetooth events IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); mContext.registerReceiver(mBluetoothReceiver, filter); if (!mBluetoothAdapter.isEnabled()) { Log.w(TAG, "Bluetooth is currently disabled... enabling"); mBluetoothAdapter.enable(); } else { Log.i(TAG, "Bluetooth enabled... starting client"); startClient(); } }
@Override public int onStartCommand(final Intent intent, final int flags, final int startId) { if (intent == null || !intent.hasExtra(EXTRA_DEVICE_ADDRESS)) throw new UnsupportedOperationException("No device address at EXTRA_DEVICE_ADDRESS key"); mDeviceAddress = intent.getStringExtra(EXTRA_DEVICE_ADDRESS); // notify user about changing the state to CONNECTING final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE); broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_CONNECTING); LocalBroadcastManager.getInstance(BleProfileService.this).sendBroadcast(broadcast); final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); final BluetoothAdapter adapter = bluetoothManager.getAdapter(); final BluetoothDevice device = adapter.getRemoteDevice(mDeviceAddress); mDeviceName = device.getName(); mBleManager.connect(device); return START_REDELIVER_INTENT; }
@Override public int onStartCommand(final Intent intent, final int flags, final int startId) { if (intent == null || !intent.hasExtra(EXTRA_DEVICE_ADDRESS)) throw new UnsupportedOperationException("No device address at EXTRA_DEVICE_ADDRESS key"); final Uri logUri = intent.getParcelableExtra(EXTRA_LOG_URI); mLogSession = Logger.openSession(getApplicationContext(), logUri); mDeviceAddress = intent.getStringExtra(EXTRA_DEVICE_ADDRESS); Logger.i(mLogSession, "Service started"); // notify user about changing the state to CONNECTING final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE); broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_CONNECTING); LocalBroadcastManager.getInstance(BleProfileService.this).sendBroadcast(broadcast); final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); final BluetoothAdapter adapter = bluetoothManager.getAdapter(); final BluetoothDevice device = adapter.getRemoteDevice(mDeviceAddress); mDeviceName = device.getName(); onServiceStarted(); mBleManager.connect(device); return START_REDELIVER_INTENT; }
@Override public void connect(final BluetoothDevice device) { // Should we use the GATT Server? final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext()); final boolean useGattServer = preferences.getBoolean(ProximityActivity.PREFS_GATT_SERVER_ENABLED, true); if (useGattServer) { // Save the device that we want to connect to. First we will create a GATT Server mDeviceToConnect = device; final BluetoothManager bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE); try { DebugLogger.d(TAG, "[Server] Starting Gatt server..."); Logger.v(mLogSession, "[Server] Starting Gatt server..."); openGattServer(getContext(), bluetoothManager); addImmediateAlertService(); // the BluetoothGattServerCallback#onServiceAdded callback will proceed further operations } catch (final Exception e) { // On Nexus 4&7 with Android 4.4 (build KRT16S) sometimes creating Gatt Server fails. There is a Null Pointer Exception thrown from addCharacteristic method. Logger.e(mLogSession, "[Server] Gatt server failed to start"); Log.e(TAG, "Creating Gatt Server failed", e); } } else { super.connect(device); } }
/** * enable bluetooth */ private void initBluetooth() { //get Bluetooth service mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); //get Bluetooth Adapter mBluetoothAdapter = mBluetoothManager.getAdapter(); if (mBluetoothAdapter == null) {//platform not support bluetooth Log.d(Tag, "Bluetooth is not support"); } else{ int status = mBluetoothAdapter.getState(); //bluetooth is disabled if (status == BluetoothAdapter.STATE_OFF) { // enable bluetooth mBluetoothAdapter.enable(); } } }
/** * Initializes bluetooth adapter * * @return <code>true</code> if initialization was successful */ private boolean initialize() { // For API level 18 and above, get a reference to BluetoothAdapter through // BluetoothManager. final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); if (bluetoothManager == null) { loge("Unable to initialize BluetoothManager."); return false; } mBluetoothAdapter = bluetoothManager.getAdapter(); if (mBluetoothAdapter == null) { loge("Unable to obtain a BluetoothAdapter."); return false; } return true; }
boolean setupBleController() { boolean retvalue = true; if(bluetoothAdapter == null) { final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = bluetoothManager.getAdapter(); retvalue = false; } if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && leScanner == null) { if(bluetoothAdapter == null) { retvalue = false; } else { leScanner = bluetoothAdapter.getBluetoothLeScanner(); if(leScanner == null) retvalue = false; } } return retvalue; }
/** * Finds all bonded devices and tries to unbond it. */ private void unPairDevice() { ConnectedDevice connectedDevice = BluetoothUtils.getPairedMicrobit(this); String addressToDelete = connectedDevice.mAddress; // Get the paired devices and put them in a Set BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) getSystemService(BLUETOOTH_SERVICE)).getAdapter(); Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); for(BluetoothDevice bt : pairedDevices) { logi("Paired device " + bt.getName()); if(bt.getAddress().equals(addressToDelete)) { try { Method m = bt.getClass().getMethod("removeBond", (Class[]) null); m.invoke(bt, (Object[]) null); } catch(NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { Log.e(TAG, e.toString()); } } } }
public static BluetoothDevice getPairedDeviceMicroBit(Context context) { SharedPreferences pairedDevicePref = context.getApplicationContext().getSharedPreferences(PREFERENCES_KEY, Context.MODE_MULTI_PROCESS); if(pairedDevicePref.contains(PREFERENCES_PAIREDDEV_KEY)) { String pairedDeviceString = pairedDevicePref.getString(PREFERENCES_PAIREDDEV_KEY, null); Gson gson = new Gson(); sConnectedDevice = gson.fromJson(pairedDeviceString, ConnectedDevice.class); //Check if the microbit is still paired with our mobile BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) MBApp.getApp().getSystemService(Context .BLUETOOTH_SERVICE)).getAdapter(); if(mBluetoothAdapter.isEnabled()) { Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); for(BluetoothDevice bt : pairedDevices) { if(bt.getAddress().equals(sConnectedDevice.mAddress)) { return bt; } } } } return null; }
@TargetApi(18) public void onReceive(Context context, Intent intent) { if (VERSION.SDK_INT >= 18) { if (QNApiImpl.this.mBluetoothAdapter == null) { BluetoothManager bluetoothManager = (BluetoothManager) QNApiImpl.this .mContext.getSystemService("bluetooth"); QNApiImpl.this.mBluetoothAdapter = bluetoothManager.getAdapter(); } if (QNApiImpl.this.mBluetoothAdapter != null && !QNApiImpl.this.mBluetoothAdapter .isEnabled()) { QNApiImpl.this.bleScan.onBleClosed(QNApiImpl.this.mBluetoothAdapter); for (QNBleHelper bleHelper : QNApiImpl.this.helperMap.values()) { if (!(bleHelper == null || bleHelper.bleCallback == null)) { bleHelper.bleCallback.onCompete(7); } } } } }
public void startLeScan(String deviceName, String mac, QNBleScanCallback callback) { if (isAppIdReady(callback)) { if (this.mBluetoothAdapter == null) { this.mBluetoothAdapter = ((BluetoothManager) this.mContext.getSystemService ("bluetooth")).getAdapter(); } if (this.mBluetoothAdapter == null) { callback.onCompete(4); } else if (!this.mContext.getPackageManager().hasSystemFeature("android.hardware" + ".bluetooth_le")) { callback.onCompete(6); } else if (this.mBluetoothAdapter.isEnabled()) { this.bleScan.start(this.mBluetoothAdapter, deviceName, mac, callback); } else { callback.onCompete(7); } } }
private boolean isBluetoothEnabled() { final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter(); if (bluetoothAdapter == null) { Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_LONG).show(); finish(); } boolean enabled = true; if (!bluetoothAdapter.isEnabled()) { enabled = false; Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, ENABLE_BLUETOOTH); } return enabled; }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setTitle(R.string.title_devices); mHandler = new Handler(); // 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, R.string.ble_not_supported, Toast.LENGTH_SHORT).show(); finish(); } // Initializes a Bluetooth adapter. For API level 18 and above, get a reference to // BluetoothAdapter through BluetoothManager. final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); // Checks if Bluetooth is supported on the device. if (mBluetoothAdapter == null) { Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show(); finish(); return; } }
/** * Check if Bluetooth LE device supported on the running environment. * * @param context the context * @return true if supported */ public static boolean isBleSupported(@NonNull final Context context) { try { if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE) == false) { return false; } final BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); final BluetoothAdapter bluetoothAdapter; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { bluetoothAdapter = bluetoothManager.getAdapter(); } else { bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); } if (bluetoothAdapter != null) { return true; } } catch (final Throwable ignored) { // ignore exception } return false; }
/** * Check if bluetooth function enabled * * @param context the context * @return true if bluetooth enabled */ public static boolean isBluetoothEnabled(@NonNull final Context context) { final BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); if (bluetoothManager == null) { return false; } final BluetoothAdapter bluetoothAdapter; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { bluetoothAdapter = bluetoothManager.getAdapter(); } else { bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); } if (bluetoothAdapter == null) { return false; } return bluetoothAdapter.isEnabled(); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDevices = (ListView) findViewById(R.id.lv_devices); BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); if (mBluetoothAdapter == null) { Toast.makeText(getApplicationContext(), "Bluetooth device unavailable!",Toast.LENGTH_SHORT).show(); finish(); } mHandler = new Handler(); }
/** * Start the CurrentTimeService GATT server * @return true if the GATT server starts successfully or is already running */ public static boolean startServer(Context context) { if (sGattServer == null) { BluetoothManager manager = (BluetoothManager) context.getSystemService(BLUETOOTH_SERVICE); CurrentTimeCallback callback = new CurrentTimeCallback(); sGattServer = manager.openGattServer(context, callback); if (sGattServer == null) { Log.e(TAG, "Unable to start GATT server"); return false; } sGattServer.addService(GATT_SERVICE); callback.setGattServer(sGattServer); } else { Log.w(TAG, "Already started"); } return true; }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) public void startAdvertise(Context context) { mContext = context; //BLE設定,Advertiser負責廣播被其他裝置搜尋,GattServer負責連線上後的資料傳輸 BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter adapter = manager.getAdapter(); mAdvertiser = getAdvertiser(adapter); mGattServer = getGattServer(context, manager); Log.d(TAG, "mGattServer=>" + mGattServer); //初始化gatt server底下的service、service下放入Characteristic initService(); //Advertiser開始 mAdvertiser.startAdvertising(makeAdvertiseSetting(), makeAdvertiseData(), this); }
@Inject public BleManager(@ForApplication Context context, PreferenceManager prefsManager) { this.context = context; // the app manifest requires support for BLE, no need to check explicitly bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = bluetoothManager.getAdapter(); preferenceManager = prefsManager; gattManager = new GattManager(prefsManager, this); // Beaconing beaconManager = org.altbeacon.beacon.BeaconManager.getInstanceForApplication(context); beaconManager.getBeaconParsers().clear(); beaconManager.getBeaconParsers().add(new BeaconParser(). setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25")); Timber.d("setting up background monitoring for beacons and power saving"); Identifier id1 = Identifier.parse(ThunderBoardDevice.THUNDER_BOARD_REACT_UUID_STRING); Region region = new Region("backgroundRegion", id1, null, null); regionBootstrap = new ThunderBoardBootstrap(context, this, region); backgroundPowerSaver = new ThunderBoardPowerSaver(context, preferenceManager); beaconManager.setBackgroundBetweenScanPeriod(ThunderBoardPowerSaver.DELAY_BETWEEN_SCANS_INACTIVE); }
@Override public boolean load(@ValidData @NonNull BluetoothOperationData data) { Boolean state = data.get(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter adapter = bluetoothManager.getAdapter(); if (adapter == null) { Logger.w("no BluetoothAdapter"); return true; } if (state) { return adapter.enable(); } else { return adapter.disable(); } } Logger.wtf("System version lower than min requirement"); return false; }
public boolean init(ConnectionListener connectionListener) { this.connectionListener = connectionListener; BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); if (bluetoothManager == null) { Config.loge("Unable to initialize BluetoothManager."); return false; } bluetoothAdapter = bluetoothManager.getAdapter(); if (bluetoothAdapter == null) { Config.loge("Unable to obtain a BluetoothAdapter."); return false; } Intent gattServiceIntent = new Intent(context, BluetoothLeService.class); context.bindService(gattServiceIntent, serviceConnection, Activity.BIND_AUTO_CREATE); Config.loge("startScan to Bind service."); final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED); intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED); intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED); intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE); intentFilter.addAction(BluetoothLeService.ACTION_READ_RSSI); intentFilter.addAction(BluetoothLeService.ACTION_CHARACTERISTIV_WRITE); context.registerReceiver(mGattUpdateReceiver, intentFilter); return true; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mLogSession = Logger.newSession(this, "Hello", "BleUARTPeripheral"); setContentView(R.layout.activity_main); ListView list = new ListView(this); setContentView(list); mConnectedDevices = new ArrayList<BluetoothDevice>(); mConnectedDevicesAdapter = new ArrayAdapter<BluetoothDevice>(this, android.R.layout.simple_list_item_1, mConnectedDevices); list.setAdapter(mConnectedDevicesAdapter); mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); mBluetoothAdapter = mBluetoothManager.getAdapter(); Logger.log(mLogSession, LogContract.Log.Level.DEBUG, "In on create"); }
@Inject DisconnectOperation( RxBleGattCallback rxBleGattCallback, BluetoothGattProvider bluetoothGattProvider, @Named(DeviceModule.MAC_ADDRESS) String macAddress, BluetoothManager bluetoothManager, @Named(ClientComponent.NamedSchedulers.BLUETOOTH_INTERACTION) Scheduler bluetoothInteractionScheduler, @Named(DeviceModule.DISCONNECT_TIMEOUT) TimeoutConfiguration timeoutConfiguration, ConnectionStateChangeListener connectionStateChangeListener) { this.rxBleGattCallback = rxBleGattCallback; this.bluetoothGattProvider = bluetoothGattProvider; this.macAddress = macAddress; this.bluetoothManager = bluetoothManager; this.bluetoothInteractionScheduler = bluetoothInteractionScheduler; this.timeoutConfiguration = timeoutConfiguration; this.connectionStateChangeListener = connectionStateChangeListener; }
@Override public void onCreate() { super.onCreate(); bleDevices = new BleDevices(); handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { if (MSG_PRUNE == msg.what && bleDevices != null) { Log.v(TAG, "Pruning devices"); BluetoothManager manager = (BluetoothManager) getSystemService( Context.BLUETOOTH_SERVICE); bleDevices.pruneOldDevices(manager.getConnectedDevices(BluetoothProfile.GATT)); } return false; } }); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setProgressBarIndeterminate(true); /* * We are going to display all the device beacons that we discover * in a list, using a custom adapter implementation */ ListView list = new ListView(this); mAdapter = new BeaconAdapter(this); list.setAdapter(mAdapter); setContentView(list); /* * Bluetooth in Android 4.3 is accessed via the BluetoothManager, rather than * the old static BluetoothAdapter.getInstance() */ BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); mBluetoothAdapter = manager.getAdapter(); mBeacons = new HashMap<String, TemperatureBeacon>(); }
public void onCreate() { final BluetoothManager bluetoothManager = (BluetoothManager) activity.getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = bluetoothManager.getAdapter(); if (bluetoothAdapter == null) { Toast.makeText(activity, R.string.bluetooth_must_be_supported, Toast.LENGTH_SHORT).show(); activity.finish(); return; } int permissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION); if(permissionCheck == PackageManager.PERMISSION_GRANTED) { hasCoarsePermission = true; } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) activity.requestPermissions( new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, COARSE_REQUEST_CODE); } }
public ACSUtility(Context context, IACSUtilityCallback cb) { // TODO Auto-generated constructor stub this.context = context; userCallback = cb; _lengthOfPackage = 10; bScanning = false; Log.d(TAG, "acsUtility 1"); bluetoothManager = (BluetoothManager) context.getSystemService(context.BLUETOOTH_SERVICE); mBtAdapter = bluetoothManager.getAdapter(); if (mBtAdapter == null) { Log.d(TAG, "error, mBtAdapter == null"); return; } //after andrioid m, must request Permission on runtime // getPermissions(context); //context.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter()); Intent intent = new Intent(); intent.setClass(context, ACSUtilityService.class); context.startService(intent); context.bindService(intent, conn, Context.BIND_AUTO_CREATE); }
public void startCentralManager(BLEUtilCallback callback) { this.mCallback = callback; if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { runCallbackWithErrorCode(BLEUtilErrorCode.E_NO_BLE_FEATURE); } // Initializes Bluetooth adapter. final BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); // Ensures Bluetooth is available on the device and it is enabled. If not, // displays a dialog requesting user permission to enable Bluetooth. if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { requestOpenBT(); } else { runCallback(CENTRAL, BLEUtilEvent.EV_BT_POWER_ON); } }
private void check_and_enable_bluetooth() { if (Build.VERSION.SDK_INT > 17) { try { final BluetoothManager bluetooth_manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); if (!bluetooth_manager.getAdapter().isEnabled()) { if (Pref.getBoolean("automatically_turn_bluetooth_on", true)) { JoH.setBluetoothEnabled(getApplicationContext(), true); //Toast.makeText(this, "Trying to turn Bluetooth on", Toast.LENGTH_LONG).show(); //} else { //Toast.makeText(this, "Please turn Bluetooth on!", Toast.LENGTH_LONG).show(); } } } catch (Exception e) { UserError.Log.e(TAG, "Error checking/enabling bluetooth: " + e); } } }