【发布时间】:2013-11-19 19:59:14
【问题描述】:
Obs:我知道这里有很多关于此的问题,但他们都没有做我想做的事,说真的,所以不要因为Duplicate 问题而否决它,谢谢。
好吧,我有一个应用程序,它具有所有必要的Bluetooth 类用于连接和管理等。我的应用程序是一个Chat 通过Bluetooth,我可以将字符串消息发送到另一台设备,而另一台设备可以也发给我。 Server 和 Client。
这是我发送Message(工作)的方法
public boolean sendMessageByBluetooth(String msg){
try {
if(dataOutputStream != null){
dataOutputStream.write(msg.getBytes());
dataOutputStream.flush();
return true;
}else{
sendHandler(ChatActivity.MSG_TOAST, context.getString(R.string.no_connection));
return false;
}
} catch (IOException e) {
LogUtil.e(e.getMessage());
sendHandler(ChatActivity.MSG_TOAST, context.getString(R.string.failed_to_send_message));
return false;
}
}
如果可能的话,我想要一个与该方法类似的方法,可以Send Files,这样我就可以使用相同的源来实现File Transfer。
但我需要在我的应用程序上有一个功能,即File Transfer,它有一个Browse 按钮来搜索您的Device 上的文件,然后选择它并发送到配对设备,就这么简单。
我也想看到ProgressBar 填写给用户,看看发送文件需要多长时间:)
我该怎么做?
--编辑--
我正在尝试File Transfer,这就是我所做的:
FileActivity.java
onCreate 连接事件:
verifyAndActivateBluetooth(); //this function is same used on ChatActivity it is working.
registerFilter(); //this function is same used on ChatActivity it is working.
chatBusinessLogic.startFoundDevices(); //this function is same used on ChatActivity and it is working.
然后我选择可见的另一台设备,它连接成功。
连接后然后..
按钮Browse -> 显示文件浏览器的意图:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, FILE_FOUND);
FileActivity onActivityResult switch(requestCode):
case FILE_FOUND:
filename = data.getData().getPath(); //here was the problem of error 1. now fixed
if(filename.trim().length() > 0){
if(chatBusinessLogic.sendFile(filename)){
lblFilename.setText(filename);
toastUtil.showToast("Success");
}
}else{
toastUtil.showToast("fail");
}
chatBusinessLogic.sendFile(filename):
public boolean sendFile(String file){
if(bluetoothComunication != null){
return bluetoothComunication.sendFileByBluetooth(file);
}else{
return false;
}
}
bluetoothComunication.sendFileByBluetooth(file):
public boolean sendFileByBluetooth(String fpath){
File f = new File(fpath);
int n = 0;
byte b[] = new byte[(int) f.length()];
try
{
FileInputStream fileInputStream = new FileInputStream(new File(fpath)); //ERROR FIXED
DataOutputStream dataOut = new DataOutputStream(dataOutputStream);
while (-1 != (n = fileInputStream.read(b))){
dataOutputStream.write(b, 0, n);
}
dataOut.flush();
fileInputStream.close();
dataOut.close();
return true;
}catch(IOException e)
{
LogUtil.e("Error converting file");
LogUtil.e(e.getMessage());
return false;
}
我收到此错误(现已修复): 如果我为物理路径选择 android 本机方法:
/content:/com.estrongs.files/mnt/sdcard/calc-history.txt: open failed: ENOENT (No such file or directory)
如果我选择物理路径的替代方法:
/file:/mnt/sdcard/calc-history.txt: open failed: ENOENT (No such file or directory)
上面的错误是用filename = data.getData().getPath(); 修复FILE_FOUND而不是filename = data.getDataString();
现在我在这一行有另一个错误:
dataOutputStream.write(b, 0, n);
错误信息是:Transport endpoint is not connected,我该怎么办?
【问题讨论】:
标签: android file sockets bluetooth chat