Java Code Examples for android.bluetooth.BluetoothAdapter#getState()

The following examples show how to use android.bluetooth.BluetoothAdapter#getState() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BluetoothRadioStatusListener.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Constructor for the listener, if desired as a convenience can start listening immediately
 *
 * @param context                   The android context
 * @param shouldInitializeListening Whether to attach to the global broadcast immediately
 */

BluetoothRadioStatusListener(Context context, boolean shouldInitializeListening) {
    this.context = context;
    BluetoothAdapter adapter = new GattUtils().getBluetoothAdapter(context);
    // if we are in this condition, something is seriously wrong
    this.currentState = (adapter != null) ? adapter.getState() : BluetoothAdapter.STATE_OFF;
    // this handler is to deliver the callbacks in the same way as they would usually
    // be delivered, but we want to avoid flapping ( user toggling on and off quickly )
    // so that our protocol stacks do not get set up in a half state
    this.mainHandler = new Handler(Looper.getMainLooper());
    if (shouldInitializeListening) {
        Timber.d("Starting listener");
        startListening();
    }
}
 
Example 2
Source File: BaseScanner.java    From neatle with MIT License 6 votes vote down vote up
private void conditionalStart() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter == null) {
        NeatleLogger.e("Bluetooth LE scan failed to start. No bluetooth adapter found");
        return;
    }
    int adapterState = adapter.getState();
    if (adapterState != BluetoothAdapter.STATE_ON) {
        NeatleLogger.e("Bluetooth off, will start scanning when it turns on.");
        pause();
        return;
    }

    onStart(adapter, scanMode);
    doStarted = true;
    if (scanDuration > 0) {
        handler.postDelayed(pauseCallback, scanDuration);
    }
}
 
Example 3
Source File: BaseScanner.java    From neatle with MIT License 6 votes vote down vote up
private void pause() {
    handler.removeCallbacks(pauseCallback);
    handler.removeCallbacks(resumeCallback);

    if (!scanning) {
        NeatleLogger.i("called pause, but there is no scanning in progress");
        return;
    }

    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (doStarted) {
        doStarted = false;
        onStop(adapter);
    }


    if (scanInterval > 0 && adapter.getState() == BluetoothAdapter.STATE_ON) {
        NeatleLogger.i("scanning paused, will resume in " + scanInterval + " milliseconds");
        handler.postDelayed(resumeCallback, scanInterval);
    } else {
        NeatleLogger.i("no scan interval set or bluetooth off, stopping scanning");
    }
}
 
Example 4
Source File: BaseScanner.java    From neatle with MIT License 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (!action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
        return;
    }
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    int state = adapter.getState();
    if (state == BluetoothAdapter.STATE_ON) {
        NeatleLogger.i("BluetoothAdapter turned on");
        resume();
    } else {
        NeatleLogger.i("BluetoothAdapter state changed to " + state  +", turning off");
        pause();
    }
}
 
Example 5
Source File: SystemIconController.java    From GravityBox with Apache License 2.0 6 votes vote down vote up
private void updateBtIconVisibility() {
    if (mSbService == null || mBtMode == null) return;

    try {
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        if (btAdapter != null) {
            boolean enabled = btAdapter.getState() == BluetoothAdapter.STATE_ON;
            boolean connected = (Integer) XposedHelpers.callMethod(btAdapter, "getConnectionState") ==
                    BluetoothAdapter.STATE_CONNECTED;
            boolean visible;
            switch (mBtMode) {
                default:
                case DEFAULT: visible = enabled; break;
                case CONNECTED: visible = connected; break;
                case HIDDEN: visible = false; break;
            }
            if (DEBUG) log("updateBtIconVisibility: enabled=" + enabled + "; connected=" + connected +
                    "; visible=" + visible);
            XposedHelpers.callMethod(mSbService, "setIconVisibility", "bluetooth", visible);
        }
    } catch (Throwable t) {
        XposedBridge.log(t);
    }
}
 
Example 6
Source File: BluetoothTetheringTile.java    From GravityBox with Apache License 2.0 6 votes vote down vote up
@Override
public void handleUpdateState(Object state, Object arg) {
    mState.visible = true;
    mState.booleanValue = false;

    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

    int btState = adapter == null ? BluetoothAdapter.ERROR : adapter.getState();
    if (isInErrorState(btState)) {
        mState.label = mGbContext.getString(R.string.qs_tile_bt_tethering_error);
        mState.icon = mGbContext.getDrawable(R.drawable.ic_qs_bt_tethering_off);
    } else if (btState == BluetoothAdapter.STATE_TURNING_ON ||
            btState == BluetoothAdapter.STATE_TURNING_OFF) {
        mState.label = "---";
        mState.icon = mGbContext.getDrawable(R.drawable.ic_qs_bt_tethering_off);
    } else if (btState == BluetoothAdapter.STATE_ON && isTetheringOn()) {
        mState.label = mGbContext.getString(R.string.qs_tile_bt_tethering_on);
        mState.icon = mGbContext.getDrawable(R.drawable.ic_qs_bt_tethering_on);
        mState.booleanValue = true;
    } else {
        mState.label = mGbContext.getString(R.string.qs_tile_bt_tethering_off);
        mState.icon = mGbContext.getDrawable(R.drawable.ic_qs_bt_tethering_off);
    }

    super.handleUpdateState(state, arg);
}
 
Example 7
Source File: BluetoothTetheringTile.java    From GravityBox with Apache License 2.0 6 votes vote down vote up
@Override
public void handleClick() {
    if (mBluetoothEnableForTether)
        return;

    if (isTetheringOn()) {
        setTethering(false);
    } else {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter != null) {
            if (adapter.getState() == BluetoothAdapter.STATE_OFF) {
                mBluetoothEnableForTether = true;
                adapter.enable();
            } else if (adapter.getState() == BluetoothAdapter.STATE_ON) {
                setTethering(true);
            }
        }
    }
    refreshState();
}
 
Example 8
Source File: BleManager.java    From react-native-ble-manager with Apache License 2.0 6 votes vote down vote up
@ReactMethod
public void checkState() {
	Log.d(LOG_TAG, "checkState");

	BluetoothAdapter adapter = getBluetoothAdapter();
	String state = "off";
	if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
		state = "unsupported";
	} else if (adapter != null) {
		switch (adapter.getState()) {
			case BluetoothAdapter.STATE_ON:
				state = "on";
				break;
			case BluetoothAdapter.STATE_OFF:
				state = "off";
		}
	}

	WritableMap map = Arguments.createMap();
	map.putString("state", state);
	Log.d(LOG_TAG, "state:" + state);
	sendEvent("BleManagerDidUpdateState", map);
}
 
Example 9
Source File: BluetoothTetheringTile.java    From GravityBox with Apache License 2.0 5 votes vote down vote up
private void registerServiceListener() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter != null && adapter.getState() == BluetoothAdapter.STATE_ON &&
            mBluetoothPan.get() == null) {
        adapter.getProfileProxy(mContext, mProfileServiceListener,
                BT_PROFILE_PAN);
        if (DEBUG) log("Service listener registered");
    }
}
 
Example 10
Source File: BluetoothUtil.java    From mirror with Apache License 2.0 5 votes vote down vote up
public static boolean isBluetoothAvailable() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (!adapter.isEnabled()) {
        if (adapter.getState() == BluetoothAdapter.STATE_OFF) {
            adapter.enable();
        }
    }
    return adapter.getState() == BluetoothAdapter.STATE_ON;
}
 
Example 11
Source File: StaticUtils.java    From Status with Apache License 2.0 5 votes vote down vote up
public static int getBluetoothState(Context context) {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter != null) return adapter.getState();
    else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
            adapter = ((BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
        if (adapter != null) return adapter.getState();
        else return BluetoothAdapter.STATE_OFF;
    }
}
 
Example 12
Source File: DeviceStatusUtil.java    From AndroidStudyDemo with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 获取蓝牙的状态
 * 
 * @return 取值为BluetoothAdapter的四个静态字段:STATE_OFF, STATE_TURNING_OFF,
 *         STATE_ON, STATE_TURNING_ON
 * @throws Exception
 *             没有找到蓝牙设备
 */
public static int getBluetoothState() throws Exception {
	BluetoothAdapter bluetoothAdapter = BluetoothAdapter
			.getDefaultAdapter();
	if (bluetoothAdapter == null) {
		throw new Exception("bluetooth device not found!");
	} else {
		return bluetoothAdapter.getState();
	}
}
 
Example 13
Source File: NetworkUtil.java    From bither-android with Apache License 2.0 5 votes vote down vote up
public static boolean BluetoothIsConnected() {
    try {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        int state = adapter.getState();
        return state == BluetoothAdapter.STATE_ON;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 14
Source File: CycledLeScannerForLollipop.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
private boolean isBluetoothOn() {
    try {
        BluetoothAdapter bluetoothAdapter = getBluetoothAdapter();
        if (bluetoothAdapter != null) {
            return (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON);
        }
        LogManager.w(TAG, "Cannot get bluetooth adapter");
    }
    catch (SecurityException e) {
        LogManager.w(TAG, "SecurityException checking if bluetooth is on");
    }
    return false;
}
 
Example 15
Source File: BluetoothUtils.java    From Android-BluetoothKit with Apache License 2.0 4 votes vote down vote up
public static int getBluetoothState() {
    BluetoothAdapter adapter = getBluetoothAdapter();
    return adapter != null ? adapter.getState() : 0;
}
 
Example 16
Source File: BluetoothScanner.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
@SuppressLint("NewApi")
private int enableBluetooth(BluetoothAdapter bluetooth,
                            Handler bluetoothChangeHandler,
                            boolean forLE)
{
    //PPApplication.logE("$$$B BluetoothScanner.enableBluetooth","xxx");

    int bluetoothState = bluetooth.getState();
    int forceScan;
    if (!forLE)
        forceScan = ApplicationPreferences.prefForceOneBluetoothScan;
    else
        forceScan = ApplicationPreferences.prefForceOneBluetoothLEScan;

    //if ((!dataWrapper.getIsManualProfileActivation()) || forceScan)
    //{
    boolean isBluetoothEnabled = bluetoothState == BluetoothAdapter.STATE_ON;
    if (!isBluetoothEnabled)
    {
        boolean applicationEventBluetoothScanIfBluetoothOff = ApplicationPreferences.applicationEventBluetoothScanIfBluetoothOff;
        if (applicationEventBluetoothScanIfBluetoothOff || (forceScan != FORCE_ONE_SCAN_DISABLED))
        {
            //boolean bluetoothEventsExists = DatabaseHandler.getInstance(context).getTypeEventsCount(DatabaseHandler.ETYPE_BLUETOOTH_NEARBY, false) > 0;
            boolean scan = ((/*bluetoothEventsExists &&*/ applicationEventBluetoothScanIfBluetoothOff) ||
                    (forceScan == FORCE_ONE_SCAN_FROM_PREF_DIALOG));
            if (scan)
            {
                //PPApplication.logE("$$$B BluetoothScanner.enableBluetooth","set enabled");
                BluetoothScanWorker.setBluetoothEnabledForScan(context, true);
                if (!forLE)
                    BluetoothScanWorker.setScanRequest(context, true);
                else
                    BluetoothScanWorker.setLEScanRequest(context, true);
                final BluetoothAdapter _bluetooth = bluetooth;
                bluetoothChangeHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        //PPApplication.logE("PPApplication.startHandlerThread", "START run - from=BluetoothScanner.doScan.1");

                        if (Permissions.checkBluetoothForEMUI(context)) {
                            //lock(); // lock is required for enabling bluetooth
                            //if (Build.VERSION.SDK_INT >= 26)
                            //    CmdBluetooth.setBluetooth(true);
                            //else
                                _bluetooth.enable();
                        }

                        //PPApplication.logE("PPApplication.startHandlerThread", "END run - from=BluetoothScanner.doScan.1");
                    }
                });
                return BluetoothAdapter.STATE_TURNING_ON;
            }
        }
    }
    else
    {
        //PPApplication.logE("$$$B BluetoothScanner.enableBluetooth","already enabled");
        return bluetoothState;
    }
    //}

    return bluetoothState;
}