android -- 蓝牙 bluetooth (四)OPP文件传输
在前面android -- 蓝牙 bluetooth (一) 入门文章结尾中提到了会按四个方面来写这系列的文章,前面已写了蓝牙打开和蓝牙搜索,这次一起来看下 蓝牙文件分享的流程,也就是蓝牙应用opp目录下的代码,作为蓝牙最基本的一个功能,这部分的代码在之前的版本中就已经有了,新旧版本代码对比很多类名都 是一样的,这一部分新东西不多,写在这里帮助大家梳理下流程吧。
有没有这种感觉,智能手机的普及让我们提高了一点对蓝牙的关注,手机间使用蓝牙互传文件应该是最常用的应用之一,手机与电脑也可以通过蓝牙做同样的事情, 大部分笔记本都支持蓝牙功能,本本上蓝牙芯片多数是broadcom的,也有其它厂商(比如东芝)不过数量不多,毕竟broadcom在BT这方面是老 大。不过本本上蓝牙一般只支持蓝牙耳机听歌,并没实现对opp的支持,如果体验下手机与电脑的蓝牙文件传输怎么办呢,安装一个叫bluesoleil(中 文名好像是千月)软件就可以了,这个软件对蓝牙功能的支持还是比较全的。可能需要卸载本本自带蓝牙驱动。扯淡结束,本文还是要关注手机间蓝牙opp的代码 流程,这段的废话也许能帮助你提高下对蓝牙的体验。
蓝牙发送文件时发送端先来到这里packages/apps/Bluetooth/src/com/android/bluetooth/opp /BluetoothOppLauncherActivity.java,一个没有界面只是提取下文件信息的中转站,源码的注释写的很清楚了,两个分支 action.equals(Intent.ACTION_SEND)和 action.equals(Intent.ACTION_SEND_MULTIPLE)
- if (action.equals(Intent.ACTION_SEND) || action.equals(Intent.ACTION_SEND_MULTIPLE)) {
- //Check if Bluetooth is available in the beginning instead of at the end
- if (!isBluetoothAllowed()) {
- Intent in = new Intent(this, BluetoothOppBtErrorActivity.class);
- in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- in.putExtra("title", this.getString(R.string.airplane_error_title));
- in.putExtra("content", this.getString(R.string.airplane_error_msg));
- startActivity(in);
- finish();
- return;
- }
- if (action.equals(Intent.ACTION_SEND)) {
- .......
- Thread t = new Thread(new Runnable() {
- public void run() {
- BluetoothOppManager.getInstance(BluetoothOppLauncherActivity.this)
- .saveSendingFileInfo(type,fileUri.toString(), false);
- //Done getting file info..Launch device picker
- //and finish this activity
- launchDevicePicker();
- finish();
- }
- }); ......
- } else if (action.equals(Intent.ACTION_SEND_MULTIPLE)) {
- .......
- }
最前面那个isBluetoothAllowed()会判断是否处于飞行模式,如果是会禁止发送的。在launchDevicePicker()里还会 判断蓝牙是否已经打开,就是下面这个条件语句 (!BluetoothOppManager.getInstance(this).isEnabled())。如果已经打开了蓝牙,如果蓝牙打开了就进 入设备选择界面DeviceListPreferenceFragment(DevicePickerFragment)选择设备,这个跳转过程简单说明 下,注意这个new Intent(BluetoothDevicePicker.ACTION_LAUNCH)里字符串,完整定义public static final String ACTION_LAUNCH = "android.bluetooth.devicepicker.action.LAUNCH";路径frameworks/base/core /java/android/bluetooth/BluetoothDevicePicker.java,你会在setting应用的 manifest.xml里发现
- <activity android:name=".bluetooth.DevicePickerActivity"
- android:theme="@android:style/Theme.Holo.DialogWhenLarge"
- android:label="@string/device_picker"
- android:clearTaskOnLaunch="true">
- <intent-filter>
- <action android:name="android.bluetooth.devicepicker.action.LAUNCH" />
- <category android:name="android.intent.category.DEFAULT" />
- </intent-filter>
- </activity>
- <fragment
- android:id="@+id/bluetooth_device_picker_fragment"
- android:name="com.android.settings.bluetooth.DevicePickerFragment"
- android:layout_width="match_parent"
- android:layout_height="0dip"
- android:layout_weight="1" />
- void onDevicePreferenceClick(BluetoothDevicePreference btPreference) {
- mLocalAdapter.stopScanning();
- LocalBluetoothPreferences.persistSelectedDeviceInPicker(
- getActivity(), mSelectedDevice.getAddress());
- if ((btPreference.getCachedDevice().getBondState() ==
- BluetoothDevice.BOND_BONDED) || !mNeedAuth) {
- sendDevicePickedIntent(mSelectedDevice);
- finish();
- } else {
- super.onDevicePreferenceClick(btPreference);
- }
- }<div> public static final String ACTION_LAUNCH = "android.bluetooth.devicepicker.action.LAUNCH";
- private void sendDevicePickedIntent(BluetoothDevice device) {
- Intent intent = new Intent(BluetoothDevicePicker.ACTION_DEVICE_SELECTED);
- intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
- if (mLaunchPackage != null && mLaunchClass != null) {
- intent.setClassName(mLaunchPackage, mLaunchClass);
- }
- getActivity().sendBroadcast(intent);}
- </div>
- else if (action.equals(BluetoothDevicePicker.ACTION_DEVICE_SELECTED)) {
- BluetoothOppManager mOppManager = BluetoothOppManager.getInstance(context);
- BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- // Insert transfer session record to database
- mOppManager.startTransfer(remoteDevice);
- // Display toast message
- String deviceName = mOppManager.getDeviceName(remoteDevice);
- .......
- }
- public void startTransfer(BluetoothDevice device) {
- if (V) Log.v(TAG, "Active InsertShareThread number is : " + mInsertShareThreadNum);
- InsertShareInfoThread insertThread;
- synchronized (BluetoothOppManager.this) {
- if (mInsertShareThreadNum > ALLOWED_INSERT_SHARE_THREAD_NUMBER) {
- ...........
- return;
- }
- insertThread = new InsertShareInfoThread(device, mMultipleFlag, mMimeTypeOfSendingFile,
- mUriOfSendingFile, mMimeTypeOfSendingFiles, mUrisOfSendingFiles,
- mIsHandoverInitiated);
- if (mMultipleFlag) {
- mfileNumInBatch = mUrisOfSendingFiles.size();
- }
- }
- insertThread.start();
- }
- public void run() {
- Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
- ..........
- if (mIsMultiple) {
- insertMultipleShare();
- } else {
- insertSingleShare();
- }
- .......... }
以insertSingleShare() 为例,在它的实现会看到mContext.getContentResolver().insert,不多想了,要去provider里找到insert()函数了,
对应的代码在BluetoothOppProvider.java (bluetoothsrccomandroidluetoothopp),insert的函数实现如下,里面又拉起 BluetoothOppService,开始还以为只是针对数据库的操作,差点错过了风景。路径/packages/apps/Bluetooth /src/com/android/bluetooth/opp/BluetoothOppService.java
- public Uri insert(Uri uri, ContentValues values) {
- if (rowID != -1) {
- context.startService(new Intent(context, BluetoothOppService.class));
- ret = Uri.parse(BluetoothShare.CONTENT_URI + "/" + rowID);
- context.getContentResolver().notifyChange(uri, null);
- } else {
- if (D) Log.d(TAG, "couldn't insert into btopp database");
- }
在BluetoothOppService的onStartCommand方法中会看到updateFromProvider(),这里又开启了一个线 程UpdateThread,后续代码当然是看它的run方法了,这里面内容不少,好在这部分代码注释比较多,理解起来不难。先暂时只关心发送的动作 insertShare方法,代码也不少,只贴出了告诉我们接下来去哪里的代码和有关的逻辑注释,在下面的代码我们可以看 到 BluetoothOppTransfer.java的对象,下一站就是它了。
- private void insertShare(Cursor cursor, int arrayPos) {
- .........
- /*
- * Add info into a batch. The logic is
- * 1) Only add valid and readyToStart info
- * 2) If there is no batch, create a batch and insert this transfer into batch,
- * then run the batch
- * 3) If there is existing batch and timestamp match, insert transfer into batch
- * 4) If there is existing batch and timestamp does not match, create a new batch and
- * put in queue
- */
- if (info.isReadyToStart()) {
- .............
- if (mBatchs.size() == 0) {
- ........
- mBatchs.add(newBatch);
- if (info.mDirection == BluetoothShare.DIRECTION_OUTBOUND) {
- mTransfer = new BluetoothOppTransfer(this, mPowerManager, newBatch);
- } else if (info.mDirection == BluetoothShare.DIRECTION_INBOUND) {
- mServerTransfer = new BluetoothOppTransfer(this, mPowerManager, newBatch,
- mServerSession);
- }
- if (info.mDirection == BluetoothShare.DIRECTION_OUTBOUND && mTransfer != null) {
- mTransfer.start();
- } else if (info.mDirection == BluetoothShare.DIRECTION_INBOUND
- && mServerTransfer != null) {
- mServerTransfer.start();
- }
- } else {
- .........
- }}
- public void start() {
- ....这里省略未贴的代码是检查蓝牙是否打开,一个很谨慎的判断。看似无用,不过还是安全第一。
- if (mHandlerThread == null) {
- ........
- if (mBatch.mDirection == BluetoothShare.DIRECTION_OUTBOUND) {
- /* for outbound transfer, we do connect first */
- startConnectSession();
- } else if (mBatch.mDirection == BluetoothShare.DIRECTION_INBOUND) {
- /*
- * for inbound transfer, it's already connected, so we start
- * OBEX session directly
- */
- startObexSession();
- }
- }
- }
上面的代码是分发送文件和接收文件的,看下这两行代码就很清楚了,如果分享给别人是OUTBOUND,先执行 startConnectSession(),这个函数最后还是要跑到startObexSession()这里的,如果收文件直接 startObexSession,所以后面就只看startObexSession方法了
- // This transfer is outbound, e.g. share file to other device.
- public static final int DIRECTION_OUTBOUND = 0;
- // This transfer is inbound, e.g. receive file from other device.
- public static final int DIRECTION_INBOUND = 1;
- private void startObexSession() {
- if (mBatch.mDirection == BluetoothShare.DIRECTION_OUTBOUND) {
- if (V) Log.v(TAG, "Create Client session with transport " + mTransport.toString());
- mSession = new BluetoothOppObexClientSession(mContext, mTransport);
- } else if (mBatch.mDirection == BluetoothShare.DIRECTION_INBOUND) {
- if (mSession == null) {
- markBatchFailed();
- mBatch.mStatus = Constants.BATCH_STATUS_FAILED;
- return;
- }
- if (V) Log.v(TAG, "Transfer has Server session" + mSession.toString());
- }
- mSession.start(mSessionHandler);
- processCurrentShare();
- }
- private void doSend() {
- int status = BluetoothShare.STATUS_SUCCESS;
- ........关于status值的判断
- if (status == BluetoothShare.STATUS_SUCCESS) {
- /* do real send */ //看到这个注释了没,它才是真家伙sendFile
- if (mFileInfo.mFileName != null) {
- status = sendFile(mFileInfo);
- } else {
- /* this is invalid request */
- status = mFileInfo.mStatus;
- }
- waitingForShare = true;
- } else {
- Constants.updateShareStatus(mContext1, mInfo.mId, status);
- }
- if (status == BluetoothShare.STATUS_SUCCESS) {
- Message msg = Message.obtain(mCallback);
- msg.what = BluetoothOppObexSession.MSG_SHARE_COMPLETE;
- msg.obj = mInfo;
- msg.sendToTarget();
- } else {
- Message msg = Message.obtain(mCallback);
- msg.what = BluetoothOppObexSession.MSG_SESSION_ERROR;
- mInfo.mStatus = status;
- msg.obj = mInfo;
- msg.sendToTarget();
- }
- }
代码路径在frameworks/base/obex/javax/obex/HeaderSet.java。这个sendFile方法行数虽然 多,不过逻辑还是比较清晰的,在这里就不贴了。到这蓝牙发送文件流程也就此结束。由于发送文件时长肯定是不确定,所以在这个流程我们看到了很多开启线程代 码也是很正常的,对于这线程,直接看对应的run方法就是了。
对于蓝牙接收文件时会收到MSG_INCOMING_BTOPP_CONNECTION消息,收到这个消息是由于在蓝牙打开,即蓝牙状态是 BluetoothAdapter.STATE_ON时会执行
startSocketListener(),在这个函数开启了监听程序,看下面贴在一起的代码就明白了,
- if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
- switch (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) {
- case BluetoothAdapter.STATE_ON:
- if (V) Log.v(TAG,"Receiver BLUETOOTH_STATE_CHANGED_ACTION, BLUETOOTH_STATE_ON");
- startSocketListener();
- break;
- private void startSocketListener() {
- if (V) Log.v(TAG, "start RfcommListener");
- mSocketListener.start(mHandler);
- if (V) Log.v(TAG, "RfcommListener started");
- }
- mSocketListener.start(mHandler);这个的实现在这里,比较长,没有贴上来
- /packages/apps/Bluetooth/src/com/android/bluetooth/opp/BluetoothOppRfcommListener.java
- private void createServerSession(ObexTransport transport) {
- mServerSession = new BluetoothOppObexServerSession(this, transport);
- mServerSession.preStart();
- }
- 9楼 syngalon螳螳 2013-11-05 09:58发表 [回复]
- 请问蓝牙手机接收文件后存储路径在哪里设置呢
- Re: balmy 2013-11-05 12:01发表 [回复]
- 回复hypersmart:默认好像不能手动设置吧,在代码里写好了,应该可以在下面的代码里改,要试验下确认
packages/apps/Bluetooth/src/com/android/bluetooth/opp/BluetoothOppReceiveFileInfo.java
generateFileInfo方法
packages/apps/Bluetooth/src/com/android/bluetooth/opp/Constants.java
public static final String DEFAULT_STORE_SUBDIR = "/bluetooth";
- Re: syngalon螳螳 2013-11-11 08:55发表 [回复]
- 回复baimy1985:谢谢呀,就是想找到定义蓝牙文件存储位置的地方,原来在这里
- 8楼 syngalon螳螳 2013-10-24 16:06发表 [回复]
- 请问一下,台式机接usb蓝牙适配器,然后用bluesoleil怎么连接不了手机呢,需要什么配置吗-
我是之前坐你后面的 *航
- Re: balmy 2013-10-24 19:56发表 [回复]
- 回复hypersmart:台式机一般是需要额外蓝牙发射器的,有的笔记本可能自带了就不用了,好像还要处理下驱动,如果之前有默认的蓝牙驱动,还要卸载掉相冲突的蓝牙驱动才可以
- Re: syngalon螳螳 2013-10-25 15:33发表 [回复]
- 回 复baimy1985:非常感谢,蓝牙发射器不是插在台式机上的蓝牙适配器么,已经插上了,不用千月还能找到蓝牙手机,装上就发现不了手机,卸载后也能发 现手机,很奇怪,设备管理器里面有三个“bluetooth外围设备”上打了感叹号,安装了蓝牙驱动(Widcomm.v5.0.1.801)也不行,有 木有其他的蓝牙客户端呀,想看看ftp传输文件功能
- Re: syngalon螳螳 2013-10-26 14:12发表 [回复]
- 回复baimy1985:恩恩,我问问,谢谢!
- 7楼 gordon1986 2013-09-30 10:12发表 [回复]
- 不错,支持一个
- 3楼 imwhite 2013-08-05 13:58发表 [回复]
- 博主研究得还挺深入的。不过我有个疑问:
程序可以利用调用系统蓝牙的Provider来实现发送和接受文件,但是程序是如何得知发送或者接受文件的状况呢?
如果是通过Receiver,那么注册的action是什么?
- Re: balmy 2013-08-05 21:38发表 [回复]
- 回复q376420785:你看看这个函数updateActiveNotification() 是不是你想要的
路径:
/packages/apps/Bluetooth/src/com/android/bluetooth/opp/BluetoothOppNotification.java
- Re: imwhite 2013-08-06 18:18发表 [回复]
- 回复baimy1985:我发现最后还是调用INotificationManager的enqueueNotificationWithTag方法,不能跟踪下去了。
我还遇到一个问题:
我 想调用蓝牙的opp传输文件,于是就使用intent的ACTION_SEND共享方式来打开,但是会出现选择设备界面(Bluetooth device picker),但是我想自己设计设备列表,然后点击设备就可以发送文件,不知道怎样才能不显示系统的选择界面而直接发送文件呢?