List of usage examples for android.bluetooth BluetoothAdapter getDefaultAdapter
public static synchronized BluetoothAdapter getDefaultAdapter()
From source file:com.google.android.gcm.demo.app.BluetoothHDPActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Check for Bluetooth availability on the Android platform. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Toast.makeText(this, R.string.bluetooth_not_available, Toast.LENGTH_LONG); finish();// w ww .j a v a 2 s.c o m return; } setContentView(R.layout.console); mConnectIndicator = (TextView) findViewById(R.id.connect_ind); mStatusMessage = (TextView) findViewById(R.id.status_msg); mResultMessage = (TextView) findViewById(R.id.result_msg); mDataIndicator = (ImageView) findViewById(R.id.data_ind); mRes = getResources(); mHealthServiceBound = false; // Initiates application registration through {@link BluetoothHDPService}. Button registerAppButton = (Button) findViewById(R.id.button_register_app); registerAppButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { sendMessage(BluetoothHDPService.MSG_REG_HEALTH_APP, HEALTH_PROFILE_SOURCE_DATA_TYPE); Log.d(TAG, "register button pressed"); } }); // Initiates application unregistration through {@link BluetoothHDPService}. Button unregisterAppButton = (Button) findViewById(R.id.button_unregister_app); unregisterAppButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { sendMessage(BluetoothHDPService.MSG_UNREG_HEALTH_APP, 0); Log.d(TAG, "unregister button pressed"); } }); // Initiates channel creation through {@link BluetoothHDPService}. Some devices will // initiate the channel connection, in which case, it is not necessary to do this in the // application. When pressed, the user is asked to select from one of the bonded devices // to connect to. Button connectButton = (Button) findViewById(R.id.button_connect_channel); connectButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d(TAG, "clickConnect1"); mAllBondedDevices = (BluetoothDevice[]) mBluetoothAdapter.getBondedDevices() .toArray(new BluetoothDevice[0]); Log.d(TAG, "clickConnect2"); if (mAllBondedDevices.length > 0) { int deviceCount = mAllBondedDevices.length; if (mDeviceIndex < deviceCount) mDevice = mAllBondedDevices[mDeviceIndex]; else { mDeviceIndex = 0; mDevice = mAllBondedDevices[0]; } String[] deviceNames = new String[deviceCount]; int i = 0; for (BluetoothDevice device : mAllBondedDevices) { deviceNames[i++] = device.getName(); } SelectDeviceDialogFragment deviceDialog = SelectDeviceDialogFragment.newInstance(deviceNames, mDeviceIndex); deviceDialog.show(getFragmentManager(), "deviceDialog"); //sendMessage(BluetoothHDPService.MSG_CONNECT_CHANNEL, 0); //######### Log.d(TAG, "connect channel #####"); } } }); // Initiates channel disconnect through {@link BluetoothHDPService}. Button disconnectButton = (Button) findViewById(R.id.button_disconnect_channel); disconnectButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { disconnectChannel(); } }); registerReceiver(mReceiver, initIntentFilter()); }
From source file:com.example.smsquickform.Homescreen.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_homescreen); ActivityHelper.initialize(this); //This is to ensure that the rotation persists across activities and not just this one Log.d(TAG, "Created"); Intent intent = getIntent();//w ww . ja v a2 s. com mBtnSearch = (Button) findViewById(R.id.btnSearch); mBtnConnect = (Button) findViewById(R.id.btnConnect); mButtonAnak = (Button) findViewById(R.id.buttonAnak); mButtonIbu = (Button) findViewById(R.id.buttonIbu); heading = (TextView) findViewById(R.id.txtListHeading); mLstDevices = (ListView) findViewById(R.id.lstDevices); /* *Check if there is a savedInstanceState. If yes, that means the onCreate was probably triggered by a configuration change *like screen rotate etc. If that's the case then populate all the views that are necessary here */ if (savedInstanceState != null) { ArrayList<BluetoothDevice> list = savedInstanceState.getParcelableArrayList(DEVICE_LIST); if (list != null) { initList(list); MyAdapter adapter = (MyAdapter) mLstDevices.getAdapter(); int selectedIndex = savedInstanceState.getInt(DEVICE_LIST_SELECTED); if (selectedIndex != -1) { adapter.setSelectedIndex(selectedIndex); mBtnConnect.setEnabled(true); } } else { initList(new ArrayList<BluetoothDevice>()); } } else { initList(new ArrayList<BluetoothDevice>()); } //IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); //this.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery has finished //filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); //this.registerReceiver(mReceiver, filter); mBtnSearch.setOnClickListener(new OnClickListener() { List<BluetoothDevice> listDevices; @Override public void onClick(View arg0) { mBTAdapter = BluetoothAdapter.getDefaultAdapter(); heading.setText("Searching"); mBtnSearch.setEnabled(false); if (mBTAdapter == null) { Toast.makeText(getApplicationContext(), "Bluetooth not found", Toast.LENGTH_SHORT).show(); } else if (!mBTAdapter.isEnabled()) { Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBT, BT_ENABLE_REQUEST); } else { //listDevices = new ArrayList<BluetoothDevice>(); /*for (BluetoothDevice device : pairedDevices) { listDevices.add(device); }*/ new SearchDevices().execute(); } } }); mButtonIbu.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (mLstDevices != null) { ArrayList<BluetoothDevice> devices = (ArrayList<BluetoothDevice>) ((MyAdapter) (mLstDevices .getAdapter())).getEntireList(); Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.putExtra(DEVICES_LISTS, devices); try { } catch (NullPointerException ex) { } intent.putExtra(DEVICE_UUID, mDeviceUUID.toString()); intent.putExtra(BUFFER_SIZE, mBufferSize); startActivity(intent); } } }); mBtnConnect.setOnClickListener(new OnClickListener() { /** * connect to all paired devices */ @Override public void onClick(View arg0) { List<BluetoothDevice> devices = ((MyAdapter) (mLstDevices.getAdapter())).getEntireList(); for (int i = 0; i < devices.size(); i++) { BluetoothDevice device = devices.get(i); msg(device.getName()); Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.putExtra(DEVICE_EXTRA, device); intent.putExtra(DEVICE_UUID, mDeviceUUID.toString()); intent.putExtra(BUFFER_SIZE, mBufferSize); startActivity(intent); } } }); }
From source file:com.piusvelte.taplock.client.core.TapLockService.java
@Override public void onCreate() { super.onCreate(); int currVer = 0; try {/*from w ww. ja v a 2s . co m*/ currVer = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } SharedPreferences sp = (SharedPreferences) getSharedPreferences(KEY_PREFS, MODE_PRIVATE); if (!sp.contains(KEY_VERSION) || (currVer > sp.getInt(KEY_VERSION, 0))) { sp.edit().putInt(KEY_VERSION, currVer).commit(); (new BackupManager(this)).dataChanged(); } onSharedPreferenceChanged(getSharedPreferences(KEY_PREFS, MODE_PRIVATE), KEY_DEVICES); mBtAdapter = BluetoothAdapter.getDefaultAdapter(); }
From source file:org.envirocar.app.application.service.DeviceInRangeService.java
protected void startWithDelay(long d) { if (backgroundService != null && backgroundService.getServiceState() == ServiceState.SERVICE_STARTED) { return;/*from w ww.j a v a 2 s. c om*/ } discoveryEnabled = true; discoveryRunnable = new Runnable() { @Override public void run() { if (!discoveryEnabled) { return; } logger.info("starting device discovery..."); Intent intent = new Intent(AbstractBackgroundServiceStateReceiver.SERVICE_STATE); intent.putExtra(AbstractBackgroundServiceStateReceiver.SERVICE_STATE, ServiceState.SERVICE_DEVICE_DISCOVERY_RUNNING); sendBroadcast(intent); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter != null) { if (adapter.isDiscovering()) { adapter.cancelDiscovery(); } adapter.startDiscovery(); } try { Thread.sleep(5000); } catch (InterruptedException e) { logger.warn(e.getMessage(), e); } if (!discoveryEnabled) { /* * we are done, we found the device */ return; } /* * update the target time and send a broadcast */ intent = new Intent(AbstractBackgroundServiceStateReceiver.SERVICE_STATE); intent.putExtra(AbstractBackgroundServiceStateReceiver.SERVICE_STATE, ServiceState.SERVICE_DEVICE_DISCOVERY_PENDING); sendBroadcast(intent); targetSystemTime = System.currentTimeMillis() + DISCOVERY_PERIOD; /* * re-schedule ourselves */ invokeDiscoveryRunnable(DISCOVERY_PERIOD); } }; if (d > 0) { Intent intent = new Intent(AbstractBackgroundServiceStateReceiver.SERVICE_STATE); intent.putExtra(AbstractBackgroundServiceStateReceiver.SERVICE_STATE, ServiceState.SERVICE_DEVICE_DISCOVERY_PENDING); sendBroadcast(intent); } targetSystemTime = System.currentTimeMillis() + d; /* * do the actual invoking */ invokeDiscoveryRunnable(d); }
From source file:com.nonstop.android.SoC.BluetoothChat.BluetoothChat.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (D)/*from w w w . j ava 2 s . c om*/ Log.e(TAG, "+++ ON CREATE +++"); // Set up the window layout requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.bluetooth_chat); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title); // Set up the custom title mTitle = (TextView) findViewById(R.id.title_left_text); mTitle.setText(R.string.app_name); mTitle = (TextView) findViewById(R.id.title_right_text); // Get local Bluetooth adapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // If the adapter is null, then Bluetooth is not supported if (mBluetoothAdapter == null) { Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show(); finish(); return; } if (APP_ID == null) { com.facebook.android.Util.showAlert(this, "Warning", "Facebook Applicaton ID must be " + "specified before running this example: see FbAPIs.java"); return; } // setContentView(R.layout.main); mHandler_facebook = new Handler(); mText = (TextView) this.findViewById(R.id.txt); mUserPic = (ImageView) this.findViewById(R.id.user_pic); // Create the Facebook Object using the app id. Utility.mFacebook = new Facebook(APP_ID); // Instantiate the asynrunner object for asynchronous api calls. Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook); mLoginButton = (LoginButton) findViewById(R.id.login); // restore session if one exists SessionStore.restore(Utility.mFacebook, this); SessionEvents.addAuthListener(new FbAPIsAuthListener()); SessionEvents.addLogoutListener(new FbAPIsLogoutListener()); /* * Source Tag: login_tag */ mLoginButton.init(this, AUTHORIZE_ACTIVITY_RESULT_CODE, Utility.mFacebook, permissions); if (Utility.mFacebook.isSessionValid()) { requestUserData(); } }
From source file:com.authorwjf.bounce.BluetoothChat.java
private void setupChat() { // Initialize the array adapter for the conversation thread mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message); // Initialize the BluetoothChatService to perform bluetooth connections mChatService = new BluetoothChatService(this, mHandler); // Initialize the buffer for outgoing messages mOutStringBuffer = new StringBuffer(""); BluetoothAdapter myAdapter = BluetoothAdapter.getDefaultAdapter(); BluetoothDevice remoteDevice = myAdapter.getRemoteDevice(Main.macAddress); try {//from w w w . j av a2 s .c o m BluetoothSocket btSocket = remoteDevice .createRfcommSocketToServiceRecord(BluetoothChatService.MY_UUID_INSECURE); btSocket.connect(); } catch (IOException exc) { System.out.println("Error connecting"); stopSelf(); } new AutomaticQueryThread(mSendButton, this).start(); }
From source file:io.github.msc42.masterthemaze.GameActivity.java
private void initBluetoothAndStartGame() { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter != null) { enableBluetoothAndStartGame();/*from w w w . j a va2 s . com*/ } else { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.error).setMessage(R.string.noBluetoothExisting).setCancelable(false) .setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { finish(); } }); builder.create().show(); } }
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);/* ww w . ja va 2 s .c o m*/ // 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:it.scoppelletti.mobilepower.bluetooth.BTManager.java
/** * Collega il gestore dei dispositivi./* w w w. j a va 2s . com*/ */ private void attachAdapter() { myBTAdapter = BluetoothAdapter.getDefaultAdapter(); if (myBTAdapter == null) { myLogger.warn("Bluetooth not supported."); if (myOnListener != null) { myOnListener.onNotSupported(); } return; } if (myBTAdapter.isEnabled()) { onRun(); } else { onDisabled(); } }