我正在编写一个包含 jDroidlib 库的 Android 游戏。我想上传一个写在我的 SD 卡上的文件。我下载了适用于 Java 的 Apache FTPClient,我发现这段代码可以将其上传到我的服务器上:
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(InetAddress.getByName("server"));
ftpClient.enterLocalPassiveMode();
ftpClient.login("username", "password");
ftpClient.changeWorkingDirectory("android");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
BufferedInputStream buffIn=null;
buffIn=new BufferedInputStream(new FileInputStream("storage/sdcard0/Labyrinthal Quest/Scores.txt"));
ftpClient.enterLocalPassiveMode();
ftpClient.storeFile("Scores.txt", buffIn);
buffIn.close();
ftpClient.logout();
ftpClient.disconnect();
}
catch (Exception e) {
Context context = getApplicationContext();
CharSequence text = "Well, that failed!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
问题是:如果我在其中一个 jDroidLib-Activities 中运行此代码,它可以完美运行,但在正常的 Android Activity 中它不起作用(显示 Toast “嗯,失败了!”)。
我还在清单中为应用程序访问 Internet 设置了权限。
我真的不知道该怎么办。它适用于一个活动,但不适用于另一个......
我还需要设置其他设置吗?
有什么我必须设置的,因为它只能在一个特殊的子线程中执行吗?但是这段代码创建了一个子线程,不是吗:
FTPClient ftpClient = new FTPClient();
- - 更新 - -
323go 说,我可能得到了 NetworkOnMainThreadException,这一定是问题所在。网络线程必须是子级的。所以我只是用一个新线程包围了我的代码,它现在可以工作了:
new Thread(new Runnable() {
public void run() {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(InetAddress.getByName("server"));
ftpClient.enterLocalPassiveMode();
ftpClient.login("username", "password");
ftpClient.changeWorkingDirectory("android");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
BufferedInputStream buffIn=null;
buffIn=new BufferedInputStream(new FileInputStream("file directory"));
ftpClient.enterLocalPassiveMode();
ftpClient.storeFile("filename", buffIn);
buffIn.close();
ftpClient.logout();
ftpClient.disconnect();
}
catch (Exception e) {
Context context = getApplicationContext();
CharSequence text = "wurde net hochjeladn!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}).start();