Example usage for android.bluetooth BluetoothAdapter getDefaultAdapter

List of usage examples for android.bluetooth BluetoothAdapter getDefaultAdapter

Introduction

In this page you can find the example usage for android.bluetooth BluetoothAdapter getDefaultAdapter.

Prototype

public static synchronized BluetoothAdapter getDefaultAdapter() 

Source Link

Document

Get a handle to the default local Bluetooth adapter.

Usage

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  w w  w . j  av a 2s.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:com.example.android.BluetoothChat.BluetoothChat.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (D)//from www  . j a va2s .  c o  m
        Log.e(TAG, "+++ ON CREATE +++");

    // Set up the window layout
    setContentView(R.layout.main);

    // 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;
    }
}

From source file:com.sorin.cloudcog.car.obd2.RubyBluetoothChatActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (D)//from   w w w  . j  a va 2s  .  c  om
        Log.e(TAG, "+++ ON CREATE +++");

    // Set up the window layout
    setContentView(R.layout.car_pager_main_ruby);
    // toast message at begining of activity start
    Toast.makeText(this, "Ruby Red Style OBD2 data console", Toast.LENGTH_SHORT).show();
    mRubyAdapter = new CarTabFragmentHandlerRuby(getSupportFragmentManager());
    mRubyPager = (ViewPager) findViewById(R.id.pager_ruby);
    mRubyPager.setAdapter(mRubyAdapter);

    mRubyIndicator = (TitlePageIndicator) findViewById(R.id.indicator_ruby);
    mRubyIndicator.setViewPager(mRubyPager);

    // When shacked it will return to main activity initialization
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mShakeDetector = new ShakeDetectorActivity();
    mShakeDetector.setOnShakeListener(new OnShakeListener() {
        // shake handler
        @Override
        public void onShake(int count) {

            RubyBluetoothChatActivity.this.finish();

        }
    });
    // 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;
    }
}

From source file:org.physical_web.physicalweb.FatBeaconBroadcastService.java

@Override
public void onCreate() {
    super.onCreate();
    mBluetoothLeAdvertiser = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
    mNotificationManager = NotificationManagerCompat.from(this);
    mBluetoothManager = (BluetoothManager) this.getSystemService(Context.BLUETOOTH_SERVICE);
}

From source file:com.javadog.bluetoothproximitylock.BluetoothFragment.java

/**
 * Initializes object references and performs some other set-up tasks.
 *///from w  w  w.j  av a2s  .c om
private void initialize() {
    //Get a reference to the user preferences editor
    userPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());

    //Get fresh references to our views
    serviceToggle = new BetterCompoundButton<>(getActivity(),
            (Switch) getView().findViewById(R.id.button_bt_service_start_stop));
    signalStrengthView = (TextView) getView().findViewById(R.id.bt_signal_strength);
    deviceChooser = (Spinner) getView().findViewById(R.id.bt_device_chooser);
    lockDistance = (Spinner) getView().findViewById(R.id.bt_lock_distances); //TODO: This doesn't do anything yet.
    lockInstantly = new BetterCompoundButton<>(getActivity(),
            (CheckBox) getView().findViewById(R.id.bt_lock_instantly));
    refreshIntervalSpinner = (Spinner) getView().findViewById(R.id.bt_refresh_interval);

    //Get a reference to the local broadcast manager, and specify which intent actions we want to listen for
    LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity().getApplicationContext());
    IntentFilter filter = new IntentFilter();
    filter.addAction(SignalReaderService.ACTION_SIGNAL_STRENGTH_UPDATE);
    filter.addAction(SignalReaderService.ACTION_UNBIND_SERVICE);

    //Instantiate the ssReceiver if it's not already, then register it with the broadcast manager
    if (ssReceiver == null) {
        ssReceiver = new LocalBroadcastReceiver();
    }
    manager.registerReceiver(ssReceiver, filter);

    //Check whether device admin privileges are active, and show a dialog if not
    DevicePolicyManager dpm = (DevicePolicyManager) getActivity()
            .getSystemService(Context.DEVICE_POLICY_SERVICE);
    if (!dpm.isAdminActive(new ComponentName(getActivity().getApplicationContext(), DeviceLockManager.class))) {
        AdminDialogFragment adminDialogFragment = new AdminDialogFragment();
        adminDialogFragment.setCancelable(false);
        adminDialogFragment.show(getFragmentManager(), "needsAdmin");
    }

    populateBtDevices();

    //Start the device chooser in a disabled state if Bluetooth is disabled
    if (BluetoothAdapter.getDefaultAdapter().isEnabled()) {
        deviceChooser.setEnabled(true);
    } else {
        deviceChooser.setEnabled(false);
    }

    //Register a listener with the system to get updates about changes to Bluetooth state
    if (btStateReceiver == null) {
        btStateReceiver = new BluetoothStateReceiver();
    }
    IntentFilter btFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    getActivity().registerReceiver(btStateReceiver, btFilter);

    /**
     * Will attach the Activity to the Service as soon as the service is started.
     */
    serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            serviceBound = true;
            updateBtServiceUI();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            //This should never be called because our service resides in the same process.
        }
    };
}

From source file:it.iziozi.iziozi.gui.IOBoardActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_board);

    this.mDecorView = getWindow().getDecorView();

    this.mActiveConfig = IOConfiguration.getSavedConfiguration();

    if (this.mActiveConfig == null) {
        this.mActiveConfig = new IOConfiguration();
        showHintAlert();//from   w w  w . j a va  2  s. co m
    } else {
        lockUI();
    }

    mActualLevel = mActiveConfig.getLevel();

    mFrameLayout = (FrameLayout) findViewById(R.id.mainLayoutTableContainer);

    FragmentManager fm = getSupportFragmentManager();

    fm.beginTransaction().add(mFrameLayout.getId(), IOPaginatedBoardFragment.newInstance(mActualLevel))
            .commit();
    setupNavButtons();

    /*
    * Neurosky Mindwave support
    * */
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    if (btAdapter != null) {
        tgDevice = new TGDevice(btAdapter, handler);
    }

    this.tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int i) {
            if (tts.isLanguageAvailable(Locale.getDefault()) >= 0)
                tts.setLanguage(Locale.getDefault());
            else
                tts.setLanguage(Locale.ENGLISH);

            tts.speak(getResources().getString(R.string.tts_ready), TextToSpeech.QUEUE_FLUSH, null);
            mCanSpeak = true;
        }
    });

    this.mDecorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {

        @Override
        public void onSystemUiVisibilityChange(int visibility) {
            // Note that system bars will only be "visible" if none of the
            // LOW_PROFILE, HIDE_NAVIGATION, or FULLSCREEN flags are set.
            if (visibility == View.VISIBLE && IOBoardActivity.this.mUnlockAlert == null) {
                // TODO: The system bars are visible.
                if (mUILocked && !IOGlobalConfiguration.isEditing && canGoImmersive())
                    showUnlockAlert();

            } else {
                // TODO: The system bars are NOT visible.
            }
        }
    });
}

From source file:de.sauernetworks.stm32_bluetooth_flashloader.BluetoothUpdaterFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);/* w  ww  .  j av  a  2s  .c om*/
    // Get local Bluetooth adapter
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getActivity());

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        FragmentActivity activity = getActivity();
        Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        activity.finish();
    }
}

From source file:com.diy.blelib.profile.BleProfileService.java

@SuppressWarnings("unchecked")
@Override/*from   w w w .  j a va  2 s . co  m*/
public void onCreate() {
    super.onCreate();
    serviceLife = true;
    mHandler = new Handler();

    // initialize the manager
    mBleManager = initializeManager();
    mBleManager.setGattCallbacks(this);
    mBlutoothAdapter = BluetoothAdapter.getDefaultAdapter();

    EventBus.getDefault().register(this);
}

From source file:au.gov.ga.worldwind.androidremote.client.Remote.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Normally one shouldn't instantiate all these objects in the onCreate method,
    //as onCreate is called every time a configuration change occurs (orientation,
    //keyboard hidden, screen size, etc). But we are handling configuration changes
    //ourselves./*  ww  w.  j  a v a 2 s .c o  m*/

    //hide the status bar
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    //get local Bluetooth adapter
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        Toast.makeText(this, R.string.bluetooth_unavailable, Toast.LENGTH_LONG).show();
        finish();
        return;
    }

    communicator = new AndroidCommunicator(this, bluetoothAdapter);
    communicator.addListener(this);

    remoteViewCommunicator = new SocketAndroidCommunicator(this);

    DatasetModelState datasetsState = new DatasetModelState(communicator, this);
    LayerModelState layersState = new LayerModelState(communicator, this);
    PlaceModelState placesState = new PlaceModelState(communicator, this);

    ItemModelState[] states = new ItemModelState[] { datasetsState, layersState, placesState };
    for (ItemModelState state : states) {
        itemModelStates.put(state.getModel().getId(), state);
        ItemModelFragmentMenuProvider menuProvider = new EmptyMenuProvider();
        if (state == placesState) {
            menuProvider = new PlacesMenuProvider(communicator);
        }
        menuProviders.put(state.getModel().getId(), menuProvider);
    }

    controlFragment = ControlFragment.newInstance(remoteViewCommunicator);
    datasetsFragment = ItemModelFragment.newInstance(datasetsState.getModel().getId(), false);
    layersFragment = ItemModelFragment.newInstance(layersState.getModel().getId(), false);
    flatLayersFragment = ItemModelFragment.newInstance(layersState.getModel().getId(), true);
    placesFragment = ItemModelFragment.newInstance(placesState.getModel().getId(), false);
    tabFragments = new Fragment[] { controlFragment, datasetsFragment, layersFragment, flatLayersFragment,
            placesFragment };

    //create the tabs
    getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    int[] tabIds = new int[] { R.string.controls_tab, R.string.datasets_tab, R.string.layers_tab,
            R.string.flat_layers_tab, R.string.places_tab };
    for (int i = 0; i < tabIds.length; i++) {
        ActionBar.Tab tab = getSupportActionBar().newTab();
        tab.setTag(tabIds[i]);
        tab.setText(tabIds[i]);
        tab.setTabListener(this);
        getSupportActionBar().addTab(tab);
    }

    getSupportActionBar().setDisplayShowTitleEnabled(false);
    getSupportActionBar().setHomeButtonEnabled(true);

    //setup the shake sensor
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    sensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {
        @Override
        public void onShake() {
            communicator.sendMessage(new ShakeMessage());
        }
    });

    // Acquire a reference to the system Location Manager
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // Define a listener that responds to location updates
    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            if (isSendLocation()) {
                communicator.sendMessage(new LocationMessage(location.getLatitude(), location.getLongitude(),
                        location.getAltitude(), location.getAccuracy(), location.getBearing()));
            }
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
        }
    };
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}

From source file:com.androidaq.AndroiDAQMain.java

@Override
public void onNewIntent(Intent intent) {
    if (D)//from   w w  w. j a  v a 2 s.  c o m
        Log.e(TAG, "+++ NEW INTENT +++");

    // Set up the window layout
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.main);
    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.right_title);
    mTitle = (TextView) findViewById(R.id.title_right_text);

    AndroiDAQAdapter adapter = new AndroiDAQAdapter(this);
    pager = (ViewPager) findViewById(R.id.viewpager);
    pager.setOffscreenPageLimit(6);
    indicator = (TitlePageIndicator) findViewById(R.id.indicator);
    pager.setAdapter(adapter);
    indicator.setViewPager(pager);
    mWaveform = (WaveFormView) findViewById(R.id.WaveformArea);
    //indicator.setOnPageChangeListener(this);
    // 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;
    }

}