我正在尝试通过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());
}
}
提前谢谢。
ķ
答案 0 :(得分:0)
可耻地我最初没有遇到this documentation on Async Tasks,这已被证明是无价之宝。
虽然有一点改进,但我还是运作了。我刚刚修改了我的课程:
private class FtpUpload extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
//code here
}
并使用以下方法调用上述异步方法:
new FtpUpload().execute();
当然,如果没有在清单文件中声明以下用户权限(在&#34;应用程序&#34;标记之外),您将无法使用FTP网络:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>