BluetoothOpp共享文件(一)之蓝牙设备选择
当我们共享文件时都会弹出共享方式选择,我们选择蓝牙共享时就会根据蓝牙是否开启来进行不同的结果。接下来就默认蓝牙为开启的状态进行分析。
当我们点击蓝牙的时候就会显现蓝牙设备选择界面,即DevicePickerFragment.java
具体蓝牙列表是怎么显示出来的请自行分析。
1.共享文件就会选择一个要共享的设备,当我们点击共享的设备时,执行的代码如下:
@Override
void onDevicePreferenceClick(BluetoothDevicePreference btPreference) {
disableScanning();
LocalBluetoothPreferences.persistSelectedDeviceInPicker(
getActivity(), mSelectedDevice.getAddress());
if ((btPreference.getCachedDevice().getBondState() ==
BluetoothDevice.BOND_BONDED) || !mNeedAuth) {
sendDevicePickedIntent(mSelectedDevice);
finish();
} else {
super.onDevicePreferenceClick(btPreference);
}
}
2.根据设备状态会走不同的逻辑,这里假设设备已配对或无需授权,则
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);
}
该逻辑会发送一个ACTION_DEVICE_SELECTED的广播来存储要共享设备的信息
3.下面到接收广播的地方了BluetoothOppReceiver.java
在这里会首先创建一个opp manager,该管理器是一个单例,在里面会进行一些初始化工作以及把共享信息插入数据库,
private boolean init(Context context) {
if (mInitialized)
return true;
mInitialized = true;
mContext = context;
mAdapter = BluetoothAdapter.getDefaultAdapter();
if (mAdapter == null) {
if (V) Log.v(TAG, "BLUETOOTH_SERVICE is not started! ");
}
// Restore data from preference
restoreApplicationData();
return true;
}
/**
* Restore data from preference
*/
private void restoreApplicationData() {
SharedPreferences settings = mContext.getSharedPreferences(OPP_PREFERENCE_FILE, 0);
// All member vars are not initialized till now
mSendingFlag = settings.getBoolean(SENDING_FLAG, false);
mMimeTypeOfSendingFile = settings.getString(MIME_TYPE, null);
mUriOfSendingFile = settings.getString(FILE_URI, null);
mMimeTypeOfSendingFiles = settings.getString(MIME_TYPE_MULTIPLE, null);
mMultipleFlag = settings.getBoolean(MULTIPLE_FLAG, false);
if (V) Log.v(TAG, "restoreApplicationData! " + mSendingFlag + mMultipleFlag
+ mMimeTypeOfSendingFile + mUriOfSendingFile);
String strUris = settings.getString(FILE_URIS, null);
mUrisOfSendingFiles = new ArrayList<Uri>();
if (strUris != null) {
String[] splitUri = strUris.split(ARRAYLIST_ITEM_SEPERATOR);
for (int i = 0; i < splitUri.length; i++) {
mUrisOfSendingFiles.add(Uri.parse(splitUri[i]));
if (V) Log.v(TAG, "Uri in batch: " + Uri.parse(splitUri[i]));
}
}
mContext.getSharedPreferences(OPP_PREFERENCE_FILE, 0).edit().clear().apply();
}
startTransfer把共享信息插入数据库的代码请自行分析,谢谢!
若是感觉不错,请留步点赞,谢谢!