麻烦在android中的ftp-client程序中使用asynctask

时间:2014-03-13 10:31:30

标签: android ftp android-asynctask

我正在使用android ftp项目。它只会在sdk以下或2.3上运行,为此我实施了asynctask并在jellybean上进行了测试但是它无法正常运行有人请帮助我将整个活动作为背景线程。

package com.example.ftptest;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.commons.net.ftp.FTPFile;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class UploadActivity extends Activity {

    private static final String TAG = "UploadActivity";
    private ListView maLV;
    private String pass, host, user;
    private int port;
    private MyFTPClient ftpClient;
    private FTPFile[] ftpFiles;
    private File fileLocal;
    public FTPFile fileServer, folderServer;
    Context context;
    ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        context = this;
        Button button1 = (Button) findViewById(R.id.button1);
        // retrieves donnéees
        Bundle extra = this.getIntent().getExtras();

        if (extra != null) {
            pass = extra.getString("pass");
            host = extra.getString("host");
            user = extra.getString("user");
            port = extra.getInt("port");
        }
        // connects to the FTP Server
        ftpClient = new MyFTPClient();
        Log.d(TAG, "HOST " + host);
        Log.d(TAG, "USER " + user);
        Log.d(TAG, "PASS " + pass);
        Log.d(TAG, "PORT " + port);
        ///////////////////// // use asynctask

        uploadRefresh();
        downloadRefresh();

        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                downloadRefresh();
            }

        });

        Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                uploadRefresh();
            }

        });

        Button upload = (Button) findViewById(R.id.upload);
        upload.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try {


                    uploadRefresh();
                } catch (Exception e) {

                    System.out.println("sarath:from upload");
                    e.printStackTrace();
                }
            }
        });

        Button download = (Button) findViewById(R.id.download);
        download.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try {

                    // Refresh list // use asynctask
                    downloadRefresh();

                } catch (Exception e) {
                    System.out.println("sarath:from upload");
                    e.printStackTrace();
                }
            }
        });

    }

    private File[] localFiles;

    public void localPrintFilesList(File dir, String header) {
        try {
            Log.d(TAG, "getting local data directories");
            maLV = (ListView) findViewById(R.id.listView1);
            localFiles = dir.listFiles();
            int length = localFiles.length;

            // Creating the ArrayList that will allow us to feed the listView
            ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();

            // It says HashMap that contains the information for an item
            HashMap<String, String> map;

            // String[] values = new String[length];
            Log.d(TAG, "number of file in the directory: " + length);
            for (int i = 0; i < length; i++) {
                // initialization of HashMap
                map = new HashMap<String, String>();

                String name = localFiles[i].getName();
                boolean isFile = localFiles[i].isFile();
                // values[i] = name;
                if (isFile) {
                    Log.i(TAG, "File : " + name);
                    map.put("img", String.valueOf(R.drawable.file));
                } else {
                    Log.i(TAG, "Directory : " + name);
                    map.put("img", String.valueOf(R.drawable.folder));
                }
                map.put("title", name);

                // Add to watchlist
                listItem.add(map);
            }

            // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            // R.layout.listviewitem, android.R.id.text1, values);
            SimpleAdapter mSchedule = new SimpleAdapter(this.getBaseContext(),
                    listItem, R.layout.listviewitem, new String[] { "img",
                            "title" }, new int[] { R.id.img, R.id.title });
            // TextView tv = new TextView(this);
            // tv.setText(header);
            // maLV.addHeaderView(tv);
            maLV.setAdapter(mSchedule);

            maLV.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    Log.i(TAG, "Position : " + position);
                    Log.i(TAG, "longueur liste : " + localFiles.length);
                    // On regarde si c'est un file ou un dossier
                    boolean isFile = localFiles[position].isFile();
                    if (isFile) {
                        fileLocal = localFiles[position];
                    } else {
                        localPrintFilesList(localFiles[position],
                                localFiles[position].getName());
                    }

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void serverPrintFilesList(String ftpDir, String header)// use
                                                                    // asynctask
    {
        try {
            maLV = (ListView) findViewById(R.id.ListView2);
            Log.d(TAG, "recuperation des données du repertoires");
            ftpFiles = ftpClient.mFTPClient.listFiles(ftpDir);
            for (FTPFile ftpliste : ftpFiles) {
                Log.d(TAG, "liste des repertoire : " + ftpliste.getName());
            }
            int length = ftpFiles.length;
            Log.d(TAG, "nombre de file dans le repertoire : " + length);
            // Création de la ArrayList qui nous permettra d'alimenter la
            // listView
            ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();

            // On déclare la HashMap qui contiendra les informations pour un
            // item
            HashMap<String, String> map;

            for (int i = 0; i < length; i++) {
                map = new HashMap<String, String>();

                String name = ftpFiles[i].getName();
                boolean isFile = ftpFiles[i].isFile();

                if (isFile) {
                    Log.i(TAG, "File : " + name);
                    map.put("img", String.valueOf(R.drawable.file));
                } else {
                    Log.i(TAG, "Directory : " + name);
                    map.put("img", String.valueOf(R.drawable.folder));
                }
                map.put("title", name);

                // Ajoute à la liste
                listItem.add(map);
            }

            // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            // R.layout.listviewitem, android.R.id.text1, values);
            SimpleAdapter mSchedule = new SimpleAdapter(this.getBaseContext(),
                    listItem, R.layout.listviewitem, new String[] { "img",
                            "title" }, new int[] { R.id.img, R.id.title });
            // TextView tv = new TextView(this);
            // tv.setText(header);
            // maLV.addHeaderView(tv);
            maLV.setAdapter(mSchedule);

            maLV.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    // On récupère le titre de l'Item dans un String
                    boolean isFile = ftpFiles[position].isFile();
                    if (isFile) {
                        fileServer = ftpFiles[position];
                    } else {
                        folderServer = ftpFiles[position];
                        serverPrintFilesList(ftpFiles[position].getName(),
                                ftpFiles[position].getName());// use asynctask
                    }

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void downloadRefresh() {
        // refresh the list
        Log.d(TAG, "before recovery of directory");
        File dir = Environment.getExternalStorageDirectory();
        Log.d(TAG, "after recovery of the directory");
        Log.d(TAG, dir.toString());
        localPrintFilesList(dir, "LOCAL FILES");

    }

    public void uploadRefresh() {
        // Refresh the uploadlist
        Log.d(TAG,
                "List directory of server1 : "
                        + ftpClient.ftpGetCurrentWorkingDirectory());
        try {
            serverPrintFilesList(ftpClient.ftpGetCurrentWorkingDirectory(),
                    "SERVER FILES");// use asynctask
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.d(TAG, "Unable to retrieve the list  ");
            e.printStackTrace();
        }

    }

    private class BackTask extends AsyncTask<String, String, String> {

        protected void onPreExecute() {
            super.onPreExecute();
            // show process dialog
            pd = new ProgressDialog(context);
            pd.setTitle("File operation");
            pd.setMessage("Please wait.");
            pd.setCancelable(true);
            pd.setIndeterminate(true);
            pd.show();

        }


        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub

            if(params[0] == "connect")
            {
                ftpClient.ftpConnect(host, user, pass, port);
            }
            else if(params[0] == "download")
            {
                Log.i(TAG, "download");
                Log.i(TAG, "file : " + fileServer.getName());
                // Log.i(TAG, "folder : " + folderLocal.getName());
                ftpClient.ftpDownload(fileServer.getName(), Environment
                        .getExternalStorageDirectory().getName()
                        + "/"
                        + fileServer.getName());
            }
            else if(params[0] == "upload")
            {
                Log.i(TAG, "upload");

                System.out
                        .println("--------------------------------------------------------------");

                System.out.println("srcFilePath = " + fileLocal.getPath());
                System.out.println("file = "
                        + fileLocal.getPath().replace("/mnt", ""));
                System.out.println("desDirectory = " + "/");

                ftpClient
                        .ftpUpload(fileLocal.getPath().replace("/mnt", ""));
            }
            else if(params[0] == "getdir")
            {
                uploadRefresh();
            }
            else
            {
                Log.d("Bingo! ", "Connected");
            }
            return null;
        }

        protected void onPostExecute(String c)
        {
            pd.cancel();
        }

    }

}

1 个答案:

答案 0 :(得分:0)

长时间运行操作应该从Service管理,而不是可以随时停止的活动(例如,另一个应用程序启动)。

理想情况下,AsyncTasks应该用于短操作(最多几秒钟。)

在你的情况下,我建议使用一个线程和一个处理程序来接收来自线程的消息:

public class BackTask extends Thread{
...
    public void run(){
        // do time consuming tasks

        Message messageToParent = new Message();
        Bundle messageData = new Bundle();
        messageToParent.what = 0;
        messageData.putString(".....", ".....");
        messageToParent.setData(messageData);
        ThreadHandler.sendMessage(messageToParent);
    }
}

消息处理程序:

public Handler HttpThreadHandler = new Handler(){

    public void handleMessage(android.os.Message msg){
        Bundle resBundle = msg.getData();
    }
}

希望它有所帮助。