我对android开发很新 我编写了以下代码将我的android连接到ftp服务器
package com.example.test1;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.apache.commons.net.ftp.*;
public class MainActivity extends Activity {
public FTPClient mFTPClient = null;
Button but;
public boolean ftpConnect(String host, String username, String password, int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// Now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// Login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch(Exception e) {
CharSequence c = ""+e;
int d = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),c,d);
toast.show();
}
return false;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
but=(Button)findViewById(R.id.button1);
but.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ftpConnect("127.0.0.1","userName","Password",21);
}
});
}
}
但这会给出networkOnMainThread异常,所以搜索后我发现我必须使用AsyncTask
,但我不知道如何实现它!
答案 0 :(得分:2)
public void onClick(View v) {
new AsyncTask() {
publc Object doInBackground(Object...) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// Now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// Login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch(Exception e) {
return e;
}
}
}
public void onPostExecute(Object res) {
if (res instanceof Exception) {
int d = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),""+res,d);
toast.show();
}
}
}.execute();
另一个临时'解决方法'是在AndroidManifest.xml中设置你的android:targetSdkVersion =“9”或更低版本,因为此异常是在API级别10中引入的。
答案 1 :(得分:0)
关于Android开发者的文档在如此重要的主题上非常丰富。你会完成它。 http://developer.android.com/reference/android/os/AsyncTask.html
答案 2 :(得分:0)
您可能需要参考Android SDK中的NetworkConnect示例。