我正在尝试通过ftp从我的Android设备上传一个名为"advancedsettings.xml"的文件,该文件位于路径"/storage/emulated/0/advancedsettings.xml"中。它似乎不起作用;文件未上传,并引发以下异常:
01-06 17:56:17.498 28084-28084/com.name.example.appname E/SmsReceiver: android.os.NetworkOnMainThreadException
我发现基本上,应用程序不能尝试"在其主线程上"执行网络操作。
我是Java的新手,但我明白,从这个开始,我必须实现"ASync";我不明白如何实现它。有人可以帮助我描述这一点以及我如何在以下代码中实现它吗?
我的代码如下:
public class FtpUpload {
// use this method to upload the file using file path global var and ftp code,
//then return the link string.
//TO DO: UID file name to prevent file already exists overwrite on server?
public void total() {
FTPClient con = null;
String dest_fname = "advancedsettings.xml"; // Added to create a destination file with a dynamically created name (same as the file name in /sdcard/ftp/)
try
{
con = new FTPClient();
con.connect("ftp.domain.co.uk");
// Check your USERNAME e.g myuser@mywebspace.com and check your PASSWORD to ensure they are OK.
if (con.login("username", "password"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "/storage/emulated/0/advancedsettings.xml";
FileInputStream in = new FileInputStream(data);
boolean result = con.storeFile(dest_fname, in);
in.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
} else { // This Error Log was created
// Create error log as a file
File log_file = new File("/storage/emulated/0/error.txt");
try {
FileWriter lfw = new FileWriter(log_file);
BufferedWriter lout = new BufferedWriter(lfw);
// Continue
lout.write("Upload Connection Failed!");
lout.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
Log.e("SmsReceiver", e1.toString());
}
}
}
catch (Exception e)
{
Log.e("SmsReceiver", e.toString());
}
}
提前谢谢你。
K
可惜的是,我最初并没有在异步任务上遇到这个文档,它已被证明是无价的。
不过,通过一些即兴表演,我让它工作了。我只是这样修改了我的类:
private class FtpUpload extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
//code here
}
并使用以下方法调用上述异步方法:
new FtpUpload().execute();
当然,如果不在清单文件中声明以下用户权限(在"应用程序"标记之外),您将不会在 FTP 网络方面走得太远:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>