packages\apps\Settings\src\com\android\settings\bluetooth\BluetoothEnabler.java

    @Override
public boolean onSwitchToggled(boolean isChecked) {
if (maybeEnforceRestrictions()) {
return true;
}
// 显示toast,如果飞行模式不允许蓝牙打开
// Show toast message if Bluetooth is not allowed in airplane mode
if (isChecked &&
!WirelessUtils.isRadioAllowed(mContext, Settings.Global.RADIO_BLUETOOTH)) {
Toast.makeText(mContext, R.string.wifi_in_airplane_mode, Toast.LENGTH_SHORT).show();
// Reset switch to off
mSwitch.setChecked(false);
return false;
} mMetricsFeatureProvider.action(mContext, mMetricsEvent, isChecked); if (mLocalAdapter != null) {
// 打开或者关闭蓝牙
boolean status = mLocalAdapter.setBluetoothEnabled(isChecked);
// If we cannot toggle it ON then reset the UI assets:
// a) The switch should be OFF but it should still be togglable (enabled = True)
// b) The switch bar should have OFF text.
if (isChecked && !status) {
mSwitch.setChecked(false);
mSwitch.setEnabled(true);
mSwitchWidget.updateTitle(false);
return false;
}
}
// 切换蓝牙开关switch的状态
mSwitchWidget.setEnabled(false);
return true;
} frameworks\base\packages\SettingsLib\src\com\android\settingslib\bluetooth\LocalBluetoothAdapter.java
public boolean setBluetoothEnabled(boolean enabled) {
// 打开或者关闭蓝牙
boolean success = enabled
? mAdapter.enable()
: mAdapter.disable(); if (success) {
setBluetoothStateInt(enabled
? BluetoothAdapter.STATE_TURNING_ON
: BluetoothAdapter.STATE_TURNING_OFF);
} else {
if (Utils.V) {
Log.v(TAG, "setBluetoothEnabled call, manager didn't return " +
"success for enabled: " + enabled);
} syncBluetoothState();
}
return success;
} frameworks\base\core\java\android\bluetooth\BluetoothAdapter.java
@RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
public boolean enable() {
android.util.SeempLog.record(56);
if (isEnabled()) {
if (DBG) Log.d(TAG, "enable(): BT already enabled!");
return true;
}
try {
// 打开蓝牙
return mManagerService.enable(ActivityThread.currentPackageName());
} catch (RemoteException e) {Log.e(TAG, "", e);}
return false;
} frameworks\base\services\core\java\com\android\server\BluetoothManagerService.java
public boolean enable(String packageName) throws RemoteException {
final int callingUid = Binder.getCallingUid();
final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID; if (isBluetoothDisallowed()) {
if (DBG) {
Slog.d(TAG,"enable(): not enabling - bluetooth disallowed");
}
return false;
} if (!callerSystem) {
if (!checkIfCallerIsForegroundUser()) {
Slog.w(TAG, "enable(): not allowed for non-active and non system user");
return false;
}
// 检查是否具有操作蓝牙的权限
mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH ADMIN permission"); if (!isEnabled() && mPermissionReviewRequired
&& startConsentUiIfNeeded(packageName, callingUid,
BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
return false;
}
}
if (isStrictOpEnable()) {
AppOpsManager mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
String packages = mContext.getPackageManager().getNameForUid(Binder.getCallingUid());
if ((Binder.getCallingUid() >= Process.FIRST_APPLICATION_UID)
&& (packages.indexOf("android.uid.systemui") != 0)
&& (packages.indexOf("android.uid.system") != 0)) {
int result = mAppOpsManager.noteOp(AppOpsManager.OP_BLUETOOTH_ADMIN,
Binder.getCallingUid(), packages);
if (result == AppOpsManager.MODE_IGNORED) {
return false;
}
}
}
if (DBG) {
Slog.d(TAG,"enable(" + packageName + "): mBluetooth =" + mBluetooth +
" mBinding = " + mBinding + " mState = " +
BluetoothAdapter.nameForState(mState));
} synchronized(mReceiver) {
mQuietEnableExternal = false;
mEnableExternal = true;
// waive WRITE_SECURE_SETTINGS permission check
// 发送消息
sendEnableMsg(false, packageName);
}
if (DBG) Slog.d(TAG, "enable returning");
return true;
} private void sendEnableMsg(boolean quietMode, String packageName) {
mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
quietMode ? 1 : 0, 0));
addActiveLog(packageName, true);
} case MESSAGE_ENABLE:
if (DBG) {
Slog.d(TAG, "MESSAGE_ENABLE(" + msg.arg1 + "): mBluetooth = " + mBluetooth);
}
mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
mEnable = true; // Use service interface to get the exact state
try {
mBluetoothLock.readLock().lock();
if (mBluetooth != null) {
int state = mBluetooth.getState();
if (state == BluetoothAdapter.STATE_BLE_ON) {
Slog.w(TAG, "BT Enable in BLE_ON State, going to ON");
mBluetooth.onLeServiceUp();
persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
break;
}
}
} catch (RemoteException e) {
Slog.e(TAG, "", e);
} finally {
mBluetoothLock.readLock().unlock();
} mQuietEnable = (msg.arg1 == 1);
if (mBluetooth == null) {
// 处理打开状态
handleEnable(mQuietEnable);
} else {
//
// We need to wait until transitioned to STATE_OFF and
// the previous Bluetooth process has exited. The
// waiting period has three components:
// (a) Wait until the local state is STATE_OFF. This
// is accomplished by "waitForMonitoredOnOff(false, true)".
// (b) Wait until the STATE_OFF state is updated to
// all components.
// (c) Wait until the Bluetooth process exits, and
// ActivityManager detects it.
// The waiting for (b) and (c) is accomplished by
// delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
// message. On slower devices, that delay needs to be
// on the order of (2 * SERVICE_RESTART_TIME_MS).
//
// Wait for (a) is required only when Bluetooth is being
// turned off.
int state;
try {
state = mBluetooth.getState();
} catch (RemoteException e) {
Slog.e(TAG, "getState()", e);
break;
}
if(state == BluetoothAdapter.STATE_TURNING_OFF || state == BluetoothAdapter.STATE_BLE_TURNING_OFF)
waitForMonitoredOnOff(false, true);
Message restartMsg = mHandler.obtainMessage(
MESSAGE_RESTART_BLUETOOTH_SERVICE);
mHandler.sendMessageDelayed(restartMsg,
2 * SERVICE_RESTART_TIME_MS);
}
break; private void handleEnable(boolean quietMode) {
mQuietEnable = quietMode; try {
mBluetoothLock.writeLock().lock();
if ((mBluetooth == null) && (!mBinding)) {
//Start bind timeout and bind
Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
// bind 超时时间
mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Intent i = new Intent(IBluetooth.class.getName());
if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
UserHandle.CURRENT)) {
mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
} else {
mBinding = true;
}
} else if (mBluetooth != null) {
//Enable bluetooth
try {
if (!mQuietEnable) {
// 打开蓝牙
if(!mBluetooth.enable()) {
Slog.e(TAG,"IBluetooth.enable() returned false");
}
}
else {
if(!mBluetooth.enableNoAutoConnect()) {
Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
}
}
} catch (RemoteException e) {
Slog.e(TAG,"Unable to call enable()",e);
}
}
} finally {
mBluetoothLock.writeLock().unlock();
}
} packages\apps\Bluetooth\src\com\android\bluetooth\btservice\AdapterService.java
private static class AdapterServiceBinder extends IBluetooth.Stub {
public boolean enable() {
if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
(!Utils.checkCaller())) {
Log.w(TAG, "enable() - Not allowed for non-active user and non system user");
return false;
}
AdapterService service = getService();
if (service == null) return false;
return service.enable();
} public synchronized boolean enable(boolean quietMode) {
enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH ADMIN permission"); // Enforce the user restriction for disallowing Bluetooth if it was set.
if (mUserManager.hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM)) {
debugLog("enable() called when Bluetooth was disallowed");
return false;
} debugLog("enable() - Enable called with quiet mode status = " + mQuietmode);
mQuietmode = quietMode;
Message m = mAdapterStateMachine.obtainMessage(AdapterState.BLE_TURN_ON);
// 发送消息
mAdapterStateMachine.sendMessage(m);
mBluetoothStartTime = System.currentTimeMillis();
return true;
} packages\apps\Bluetooth\src\com\android\bluetooth\btservice\AdapterState.java switch(msg.what) {
case BLE_TURN_ON:
notifyAdapterStateChange(BluetoothAdapter.STATE_BLE_TURNING_ON);
mPendingCommandState.setBleTurningOn(true);
transitionTo(mPendingCommandState);
sendMessageDelayed(BLE_START_TIMEOUT, BLE_START_TIMEOUT_DELAY);
adapterService.BleOnProcessStart();
break; packages\apps\Bluetooth\src\com\android\bluetooth\btservice\AdapterService.java
void BleOnProcessStart() {
debugLog("BleOnProcessStart()"); if (getResources().getBoolean(
R.bool.config_bluetooth_reload_supported_profiles_when_enabled)) {
Config.init(getApplicationContext());
} Class[] supportedProfileServices = Config.getSupportedProfiles();
//Initialize data objects
for (int i=0; i < supportedProfileServices.length;i++) {
mProfileServicesState.put(supportedProfileServices[i].getName(),BluetoothAdapter.STATE_OFF);
} debugLog("BleOnProcessStart() - Make Bond State Machine"); mJniCallbacks.init(mBondStateMachine,mRemoteDevices); try {
mBatteryStats.noteResetBleScan();
} catch (RemoteException e) {
// Ignore.
}
// 启动蓝牙
//Start Gatt service
setGattProfileServiceState(supportedProfileServices,BluetoothAdapter.STATE_ON);
}

Android 8 蓝牙打开过程的更多相关文章

  1. Android 8 蓝牙 连接过程

    packages\apps\Settings\src\com\android\settings\bluetooth\BluetoothPairingDetail.java @Override void ...

  2. ZT Android 4.2 BT系统之蓝牙关闭过程全跟踪

    Android 4.2 BT系统之蓝牙关闭过程全跟踪 分类: android 2013-08-03 00:34 2252人阅读 评论(10) 收藏 举报 代码位置:       frameworks/ ...

  3. 【转】Android bluetooth介绍(二): android blueZ蓝牙代码架构及其uart 到rfcomm流程

    原文网址:http://blog.sina.com.cn/s/blog_602c72c50102uzoj.html 关键词:蓝牙blueZ  UART  HCI_UART H4  HCI  L2CAP ...

  4. Android无线蓝牙总结

    一.基础知识: ①蓝牙的四层协议: 蓝牙协议分为4层,即核心协议层.电缆替代协议层.电话控制协议层和采纳的其它协议层.这4种协议中最重要的是核心协议.蓝牙的核心协议包括基带.链路管理.逻辑链路控制和适 ...

  5. Android 串口蓝牙通信开发Java版本

    Android串口BLE蓝牙通信Java版 0. 导语 Qt on Android 蓝牙通信开发 我们都知道,在物联网中,BLE蓝牙是通信设备的关键设备.在传统的物联网应用中,无线WIFI.蓝牙和Zi ...

  6. Android中蓝牙的基本使用----BluetoothAdapter类简介

    天气逐渐热了,自己也越来越懒了,虽然看着了很多东西,解决了很多问题,有些收获却不想写着.主要有一下两方面原因: 第一.以前写的一些关于Android知识的Blog,都是在学习过程中发现网络上没有相关知 ...

  7. Android Studio 蓝牙开发实例——基于Android 6.0

    因项目需要做一个Android 的蓝牙app来通过手机蓝牙传输数据以及控制飞行器,在此,我对这段时间里写的蓝牙app的代码进行知识梳理和出现错误的总结. 该应用的Compile Sdk Version ...

  8. ubuntu16.04连接android手机蓝牙共享网络热点

    最近的想要用android手机蓝牙共享wifi网络给ubuntu16.04系统用,查了好多资料,发现网上很少有有用的.自己实践后分享如下. 第一步:手机与电脑配对:         该步骤比较简单,网 ...

  9. Android BLE 蓝牙编程(一)

    最近在研究这个,等我有时间来写吧! 终于在端午节给自己放个假,现在就来说说关于android蓝牙ble的 最近的学习成果吧!! 需要材料(写个简单教程吧--关于小米手环的哦!嘿嘿) Android 手 ...

随机推荐

  1. go知识点和注意事项

    bin目录下面存的是编译之后可执行的文件,pkg下面存放的是应用包,src下面保存的是应用源代码 Go 语言不支持函数重载特性的主要原因是函数重载需要进行多余的类型匹配影响性能: 目前 Go 没有泛型 ...

  2. nodejs+koa2微信app支付,小程序支付

    企业付款到零钱文档:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2 1,搞微信支付,先看流程图 https: ...

  3. Alpha冲刺(4/10)——2019.4.27

    所属课程 软件工程1916|W(福州大学) 作业要求 Alpha冲刺(4/10)--2019.4.27 团队名称 待就业六人组 1.团队信息 团队名称:待就业六人组 团队描述:同舟共济扬帆起,乘风破浪 ...

  4. openstack 之~keystone之HTTP协议

    第一:为什么学习HTTP协议? 1.http协议就是通信的双方共同遵守的规则.无规矩不成方圆 2.openstack中各组件是基于restful api通信的,restful api可以单纯的理解为一 ...

  5. [转]开源.net 混淆器ConfuserEx介绍

    今天给大家介绍一个开源.net混淆器——ConfuserEx http://yck1509.github.io/ConfuserEx/ 由于项目中要用到.net 混淆器,网上搜寻了很多款,比如Dotf ...

  6. Siamese网络

    1.       对比损失函数(Contrastive Loss function) 孪生架构的目的不是对输入图像进行分类,而是区分它们.因此,分类损失函数(如交叉熵)不是最合适的选择,这种架构更适合 ...

  7. AssemblyInfo.cs文件详解

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/qq395537505/article/details/49661555 一.前言 .net工程的Pr ...

  8. Elasticsearch集群运维

    一.索引管理 1. 创建索引 PUT test-2019-03 { "settings": { "index": { "number_of_shard ...

  9. python3 “POST data should be bytes or an iterable of bytes...”的解决方法

    urllib.parse.urlencode({}).encode(encoding='utf8') 参考了:dushu990

  10. bootstrap响应式前端页面

    技术:HTML+CSS+JS+bootstrap   概述 这套代码响应式前端页面基本写完了,适合初学前端的同学,里面主要运用了HTML+CSS布局和动画,js逻辑较少,页面都是静态,未接入接口.响应 ...