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:com.improvelectronics.sync.android.SyncStreamingService.java

@Override
public void onCreate() {
    super.onCreate();
    if (DEBUG)/*from   w  ww. j  a v a  2s  .  co m*/
        Log.d(TAG, "onCreate");

    // Set the default properties.
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    mMessageHandler = new MessageHandler(Looper.getMainLooper());
    mPairedDevices = new ArrayList<BluetoothDevice>();
    mPaths = new ArrayList<SyncPath>();
    mListeners = new ArrayList<SyncStreamingListener>();
    mState = STATE_DISCONNECTED;
    mMode = MODE_NONE;
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationBuilder = new NotificationCompat.Builder(this);
    mNotificationBuilder.setSmallIcon(R.drawable.ic_stat_notify_default);
    removeNotification();
    setupIntentFilter();

    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        // Bluetooth adapter isn't available.  The client of the service is supposed to
        // verify that it is available and activate before invoking this service.
        Log.e(TAG,
                "stopping sync streaming service, device does not have Bluetooth or Bluetooth is turned off");
        stopSelf();
    } else {
        updatePairedDevices();
        start();
    }
}

From source file:de.schildbach.wallet.ui.AlertDialogsFragment.java

private boolean handleProperty(final String key, final String value) {
    if (key.equalsIgnoreCase("min.security_patch.bluetooth")) {
        final String minSecurityPatchLevel = value;
        log.info("according to \"{}\", minimum security patch level for bluetooth is {}", versionUrl,
                minSecurityPatchLevel);/*from   w w w . ja  v a 2  s .co  m*/
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                && Build.VERSION.SECURITY_PATCH.compareTo(minSecurityPatchLevel) < 0) {
            final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (bluetoothAdapter != null && BluetoothAdapter.getDefaultAdapter().isEnabled()) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (isAdded())
                            createInsecureBluetoothAlertDialog(minSecurityPatchLevel).show();
                    }
                });
                return true;
            }
        }
    } else {
        log.info("Ignoring key: {}", key);
    }
    return false;
}

From source file:org.deviceconnect.android.deviceplugin.sphero.SpheroDeviceService.java

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

    EventManager.INSTANCE.setController(new MemoryCacheController());
    SpheroManager.INSTANCE.setService(this);
    registerBluetoothFilter();//from w  ww.  ja  v  a 2s.c  o  m
    registerDConnectServiceFilter();
    addProfile(new SpheroServiceDiscoveryProfile(getServiceProvider()));
    getServiceProvider().addServiceListener(this);
    //?Sphero????????
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
    for (BluetoothDevice device : pairedDevices) {
        if (device.getName() != null && device.getName().contains("Sphero")) {
            PermissionUtility.requestPermissions(SpheroDeviceService.this, mHandler, BleUtils.BLE_PERMISSIONS,
                    new PermissionUtility.PermissionRequestCallback() {
                        @Override
                        public void onSuccess() {
                            SpheroManager.INSTANCE.setDiscoveryListener(SpheroDeviceService.this);
                            SpheroManager.INSTANCE.startDiscovery(SpheroDeviceService.this);
                        }

                        @NonNull
                        @Override
                        public void onFail(final String deniedPermission) {
                        }
                    });
            break;
        }
    }
}

From source file:com.evothings.BLE.java

private void startScan(final CordovaArgs args, final CallbackContext callbackContext) {
    final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    final LeScanCallback self = this;
    checkPowerState(adapter, callbackContext, new Runnable() {
        @Override//from   ww w .j  a va  2  s . co  m
        public void run() {
            if (!adapter.startLeScan(self)) {
                callbackContext.error("Android function startLeScan failed");
                return;
            }
            mScanCallbackContext = callbackContext;
        }
    });
}

From source file:com.pdmanager.views.patient.TechnicianActivity.java

private void enableBluetooth() {
    boolean bluetoothEnabled = isBluetoothEnabled();

    if (!bluetoothEnabled) {

        try {// w  w  w . j a v  a 2  s  .  c o m
            BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
            mAdapter.enable();
            Thread.sleep(3000);

            //  LogInfo("Bluetooth activated by service");
            //LogInfo("Bluetooth activated by service");
        } catch (Exception ex) {

            //   LogError("Cannot activate bluetooth Band Sensors");
            //LogInfoError("Cannot activate bluetooth Band Sensors");

        }

        //requireBluetooth();

    }

}

From source file:com.example.mego.adas.main.MainActivity.java

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

    //Get the MAC address from the Connect Device Activity
    Intent newIntent = getIntent();/*from   w  ww  .  j  a v a  2s. c o  m*/
    if (savedInstanceState == null) {
        address = newIntent.getStringExtra(ConnectFragment.EXTRA_DEVICE_ADDRESS);
    } else {
        address = savedInstanceState.getString(address_key);
    }
    setContentView(R.layout.activity_main);

    //Initialize the Firebase auth object
    mFirebaseAuth = FirebaseAuth.getInstance();

    //Set up the firebase
    mFirebaseDatabase = FirebaseDatabase.getInstance();

    //Get the current device token
    deviceToken = FirebaseInstanceId.getInstance().getToken();

    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    backgroundImageView = findViewById(R.id.start_program_imageView);

    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    View headerView = navigationView.inflateHeaderView(R.layout.nav_header_main);

    initializeScreen(headerView);

    //display current user image
    Bitmap userImageBitmap = AdasUtils
            .loadUserImageFromStorage(AdasUtils.getCurrentUserImagePath(MainActivity.this));
    if (userImageBitmap != null) {
        userImageView.setImageBitmap(userImageBitmap);
    } else {
        userImageView.setImageResource(R.drawable.car_profile_icon);
    }

    openEditAccountActivity();

    //check if the device has a bluetooth or not
    //and show Toast message if it does't have
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (mBluetoothAdapter == null) {
        if (toast != null) {
            toast.cancel();
        }
        toast = Toast.makeText(this, R.string.does_not_have_bluetooth, Toast.LENGTH_SHORT);
        toast.show();

    } else if (!mBluetoothAdapter.isEnabled()) {
        Intent enableIntentBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntentBluetooth, REQUEST_ENABLE_BT);
    }

    newConnectionFlag++;
    if (NetworkUtil.isAvailableInternetConnection(this)) {
        if (mFirebaseAuth.getCurrentUser().getUid() != null) {
            isPhoneAuthDatabaseReference = mFirebaseDatabase.getReference().child(FIREBASE_USERS)
                    .child(mFirebaseAuth.getCurrentUser().getUid()).child(Constants.FIREBASE_IS_VERIFIED_PHONE);

            getPhoneVerificationState();
        }
    } else {
        showToast(getString(R.string.no_internet_connection));
    }
    displayUserData();
    verifyUserData();
    AdasSyncUtils.scheduleAdvices(this);
}

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

/** Called when the activity is first created. */
@Override/*from w w w.j a  va 2 s  .co  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    fixScreenOrientation();

    DoCommand dc = new DoCommand(getApplication());

    Log.i("SUTAgentAndroid", dc.prgVersion);
    dc.FixDataLocalPermissions();

    // Get configuration settings from "ini" file
    File dir = getFilesDir();
    File iniFile = new File(dir, "SUTAgent.ini");
    String sIniFile = iniFile.getAbsolutePath();

    String lc = dc.GetIniData("General", "LogCommands", sIniFile);
    if (lc != "" && Integer.parseInt(lc) == 1) {
        SUTAgentAndroid.LogCommands = true;
    }
    SUTAgentAndroid.RegSvrIPAddr = dc.GetIniData("Registration Server", "IPAddr", sIniFile);
    SUTAgentAndroid.RegSvrIPPort = dc.GetIniData("Registration Server", "PORT", sIniFile);
    SUTAgentAndroid.HardwareID = dc.GetIniData("Registration Server", "HARDWARE", sIniFile);
    SUTAgentAndroid.Pool = dc.GetIniData("Registration Server", "POOL", sIniFile);
    SUTAgentAndroid.sTestRoot = dc.GetIniData("Device", "TestRoot", sIniFile);
    SUTAgentAndroid.Abi = android.os.Build.CPU_ABI;
    log(dc, "onCreate");

    dc.SetTestRoot(SUTAgentAndroid.sTestRoot);

    Log.i("SUTAgentAndroid", "Test Root: " + SUTAgentAndroid.sTestRoot);

    tv = (TextView) this.findViewById(R.id.Textview01);

    if (getLocalIpAddress() == null)
        setUpNetwork(sIniFile);

    String macAddress = "Unknown";
    if (android.os.Build.VERSION.SDK_INT > 8) {
        try {
            NetworkInterface iface = NetworkInterface
                    .getByInetAddress(InetAddress.getAllByName(getLocalIpAddress())[0]);
            if (iface != null) {
                byte[] mac = iface.getHardwareAddress();
                if (mac != null) {
                    StringBuilder sb = new StringBuilder();
                    Formatter f = new Formatter(sb);
                    for (int i = 0; i < mac.length; i++) {
                        f.format("%02x%s", mac[i], (i < mac.length - 1) ? ":" : "");
                    }
                    macAddress = sUniqueID = sb.toString();
                }
            }
        } catch (UnknownHostException ex) {
        } catch (SocketException ex) {
        }
    } else {
        // Fall back to getting info from wifiman on older versions of Android,
        // which don't support the NetworkInterface interface
        WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifiMan != null) {
            WifiInfo wifi = wifiMan.getConnectionInfo();
            if (wifi != null)
                macAddress = wifi.getMacAddress();
            if (macAddress != null)
                sUniqueID = macAddress;
        }
    }

    if (sUniqueID == null) {
        BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
        if ((ba != null) && (ba.isEnabled() != true)) {
            ba.enable();
            while (ba.getState() != BluetoothAdapter.STATE_ON) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            sUniqueID = ba.getAddress();

            ba.disable();
            while (ba.getState() != BluetoothAdapter.STATE_OFF) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (ba != null) {
                sUniqueID = ba.getAddress();
                sUniqueID.toLowerCase();
            }
        }
    }

    if (sUniqueID == null) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (mTelephonyMgr != null) {
            sUniqueID = mTelephonyMgr.getDeviceId();
            if (sUniqueID == null) {
                sUniqueID = "0011223344556677";
            }
        }
    }

    String hwid = getHWID(this);

    sLocalIPAddr = getLocalIpAddress();
    Toast.makeText(getApplication().getApplicationContext(), "SUTAgent [" + sLocalIPAddr + "] ...",
            Toast.LENGTH_LONG).show();

    String sConfig = dc.prgVersion + lineSep;
    sConfig += "Test Root: " + sTestRoot + lineSep;
    sConfig += "Unique ID: " + sUniqueID + lineSep;
    sConfig += "HWID: " + hwid + lineSep;
    sConfig += "ABI: " + Abi + lineSep;
    sConfig += "OS Info" + lineSep;
    sConfig += "\t" + dc.GetOSInfo() + lineSep;
    sConfig += "Screen Info" + lineSep;
    int[] xy = dc.GetScreenXY();
    sConfig += "\t Width: " + xy[0] + lineSep;
    sConfig += "\t Height: " + xy[1] + lineSep;
    sConfig += "Memory Info" + lineSep;
    sConfig += "\t" + dc.GetMemoryInfo() + lineSep;
    sConfig += "Network Info" + lineSep;
    sConfig += "\tMac Address: " + macAddress + lineSep;
    sConfig += "\tIP Address: " + sLocalIPAddr + lineSep;

    displayStatus(sConfig);

    sRegString = "NAME=" + sUniqueID;
    sRegString += "&IPADDR=" + sLocalIPAddr;
    sRegString += "&CMDPORT=" + 20701;
    sRegString += "&DATAPORT=" + 20700;
    sRegString += "&OS=Android-" + dc.GetOSInfo();
    sRegString += "&SCRNWIDTH=" + xy[0];
    sRegString += "&SCRNHEIGHT=" + xy[1];
    sRegString += "&BPP=8";
    sRegString += "&MEMORY=" + dc.GetMemoryConfig();
    sRegString += "&HARDWARE=" + HardwareID;
    sRegString += "&POOL=" + Pool;
    sRegString += "&ABI=" + Abi;

    String sTemp = Uri.encode(sRegString, "=&");
    sRegString = "register " + sTemp;

    pruneCommandLog(dc.GetSystemTime(), dc.GetTestRoot());

    if (!bNetworkingStarted) {
        Thread thread = new Thread(null, doStartService, "StartServiceBkgnd");
        thread.start();
        bNetworkingStarted = true;

        Thread thread2 = new Thread(null, doRegisterDevice, "RegisterDeviceBkgnd");
        thread2.start();
    }

    monitorBatteryState();

    // If we are returning from an update let'em know we're back
    Thread thread3 = new Thread(null, doUpdateCallback, "UpdateCallbackBkgnd");
    thread3.start();

    final Button goButton = (Button) findViewById(R.id.Button01);
    goButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
}

From source file:org.jonblack.bluetrack.services.BluetoothLogService.java

@Override
public void onCreate() {
    Log.d(TAG, "Creating BluetoothLogService");

    super.onCreate();

    mLocalBtAdapter = BluetoothAdapter.getDefaultAdapter();

    // Bluetooth should be available and enabled at this point.
    assert (mLocalBtAdapter != null);
    assert (mLocalBtAdapter.isEnabled());

    // Register broadcast receiver for finding bluetooth devices.
    registerReceiver(mBtDiscoveryReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));

    // Register broadcast receiver for when discovery finished.
    registerReceiver(mBtDiscoveryReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));

    // Setup the periodic handler which will do the discovery
    mPeriodicEventHandler = new Handler();
}

From source file:com.tkjelectronics.balanduino.BalanduinoActivity.java

@Override
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    activity = this;
    context = getApplicationContext();//from   w  w w . java 2s.  com

    if (!getResources().getBoolean(R.bool.isTablet))
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // Set portrait mode only - for small screens like phones
    else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_USER); // Full screen rotation
        else
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); // Full screen rotation
        new Handler().postDelayed(new Runnable() { // Hack to hide keyboard when the layout it rotated
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); // Hide the keyboard - this is needed when the device is rotated
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getApplicationWindowToken(), 0);
            }
        }, 1000);
    }

    setContentView(R.layout.activity_main);

    // Get local Bluetooth adapter
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
        mBluetoothAdapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
    else
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        showToast("Bluetooth is not available", Toast.LENGTH_LONG);
        finish();
        return;
    }

    // get sensorManager and initialize sensor listeners
    SensorManager mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mSensorFusion = new SensorFusion(getApplicationContext(), mSensorManager);

    // Set up the action bar.
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionBar.setDisplayHomeAsUpEnabled(true);

    // Create the adapter that will return a fragment for each of the primary sections of the app.
    ViewPagerAdapter mViewPagerAdapter = new ViewPagerAdapter(getApplicationContext(),
            getSupportFragmentManager());

    // Set up the ViewPager with the adapter.
    CustomViewPager mViewPager = (CustomViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mViewPagerAdapter);

    if (getResources().getBoolean(R.bool.isTablet))
        mViewPager.setOffscreenPageLimit(2); // Since two fragments is selected in landscape mode, this is used to smooth things out

    // Bind the underline indicator to the adapter
    mUnderlinePageIndicator = (UnderlinePageIndicator) findViewById(R.id.indicator);
    mUnderlinePageIndicator.setViewPager(mViewPager);
    mUnderlinePageIndicator.setFades(false);

    // When swiping between different sections, select the corresponding
    // tab. We can also use ActionBar.Tab#select() to do this if we have
    // a reference to the Tab.
    mUnderlinePageIndicator.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            if (D)
                Log.d(TAG, "ViewPager position: " + position);
            if (position < actionBar.getTabCount()) // Needed for when in landscape mode
                actionBar.setSelectedNavigationItem(position);
            else
                mUnderlinePageIndicator.setCurrentItem(position - 1);
        }
    });

    int count = mViewPagerAdapter.getCount();
    Resources mResources = getResources();
    boolean landscape = false;
    if (mResources.getBoolean(R.bool.isTablet)
            && mResources.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        landscape = true;
        count -= 1; // There is one less tab when in landscape mode
    }

    for (int i = 0; i < count; i++) { // For each of the sections in the app, add a tab to the action bar
        String text;
        if (landscape && i == count - 1)
            text = mViewPagerAdapter.getPageTitle(i) + " & " + mViewPagerAdapter.getPageTitle(i + 1); // Last tab in landscape mode have two titles in one tab
        else
            text = mViewPagerAdapter.getPageTitle(i).toString();

        // Create a tab with text corresponding to the page title defined by
        // the adapter. Also specify this Activity object, which implements
        // the TabListener interface, as the callback (listener) for when
        // this tab is selected.
        actionBar.addTab(actionBar.newTab().setText(text).setTabListener(this));
    }
    try {
        PackageManager mPackageManager = getPackageManager();
        if (mPackageManager != null)
            BalanduinoActivity.appVersion = mPackageManager.getPackageInfo(getPackageName(), 0).versionName; // Read the app version name
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:com.devwang.logcabin.LogCabinMainActivity.java

@SuppressLint("NewApi")
@Override/*from   w w  w  .j  av a 2 s.  com*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (D)
        Log.e(TAG, "+++ ON CREATE +++");
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // 
    isFirstInstallApp();
    diyTitle();
    viewInit();

    mTitleLeft.setText(R.string.app_name);//  
    soundMediaPlayer = new MediaPlayer();//  
    autoeditTextView.setAdapter(
            new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, autoedit_items));
    // appid http://open.voicecloud.cn/ appid:54202a57
    rd = new RecognizerDialog(this, getString(R.string.str_devwang_voice_key_appid));
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    isSupportBT();
    isNonConnBt();

    mLogCabinInfo = new LogCabinInfo("", "", "", "", "", "", "", "",
            "", "", "");

}