我现在正试图通过蓝牙在Android设备之间传输文件。我已经实现了我的发送方。我没有使用InputStream / OutputStream。我正在使用Intent.ACTION_SEND。发送方的所有内容都可以正常工作,但是当涉及到接收方时,我面临两个问题。
似乎可以使用InputStream / OutputStream解决这两个问题,但我真的不想使用它们。也许监听蓝牙的监听器或BluetoothAdapter / BluetoothDevice中的某些功能可以做到这一点?
感谢您的帮助。我的代码如下所示:(在我的MainActivity.java中)
public void beginBT() {
if (isSender) {
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/log.txt");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
if (!findBluetoothForIntent(intent)){
Toast.makeText(this, "Bluetooth Not Found.", Toast.LENGTH_SHORT).show();
} else {
//intent will send the file via bluetooth
startActivity(intent);
}
} else { //receiver side
//make device be discoverable
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
public boolean findBluetoothForIntent(Intent intent){
List appsList = getPackageManager().queryIntentActivities(intent, 0);
String packageName = null;
String className = null;
for (Object info: appsList){
if (info instanceof ResolveInfo) {
packageName = ((ResolveInfo) info).activityInfo.packageName;
if (packageName.equals("com.android.bluetooth")){
className = ((ResolveInfo) info).activityInfo.name;
break;
}
}
}
if (className != null) {
intent.setClassName(packageName, className);
return true;
} else {
return false;
}
}
答案 0 :(得分:3)
回答我自己的问题总是那么有趣!!
不知道以下代码是否对任何人有帮助,:))
MainActivity.java
private static final String BT_DISCONNECTED = "android.bluetooth.device.action.ACL_DISCONNECTED";
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action == BT_DISCONNECTED) {
//now file transmitting has finished, can do something to the file
//if you know the file name, better to check if the file is actually there
// - make sure this disconnection not initiated by any other reason.
}
}
IntentFileter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter);
警告:请务必在退出活动时取消注册此接收器,或者只是在您不需要时取消注册