0

我使用 FTPClient 将文件(由用户选择)上传到我的 FTPServer。并且用于上传的代码正在工作。:) 但是当我为“上传...”对话框添加 AsyncTask 时,该对话框向用户显示它正在上传。它在我的应用程序中显示了上传对话框,然后它崩溃了,并且上传对话框没有消失....

来自 LogCat 的以下错误:

11-06 12:01:05.153: I/System.out(27121):    ARGUMENT :: /storage/sdcard0/data-app/Z29sb2NrZXJpbmRlcGVuZGVudHZlcnNpb24
11-06 12:01:05.188: D/dalvikvm(27121):      GC_CONCURRENT freed 107K, 9% free 12896K/14151K, paused 1ms+1ms, total 13ms
11-06 12:01:13.923: I/System.out(27121):    status :: 211-Status of 'ProFTPD'

11-06 12:01:13.923: I/System.out(27121):    Connected from 109.164.221.167 (109.164.221.167)

11-06 12:01:13.923: I/System.out(27121):    Logged in as ftp031220

11-06 12:01:13.923: I/System.out(27121):    TYPE: BINARY, STRUcture: File, Mode: Stream

11-06 12:01:13.923: I/System.out(27121):    No data connection

11-06 12:01:13.923: I/System.out(27121):    211 End of status

11-06 12:01:25.988: W/System.err(27121):    java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
11-06 12:01:25.988: W/System.err(27121):    at android.os.Handler.<init>(Handler.java:121)
11-06 12:01:25.988: W/System.err(27121):    at android.app.Dialog.<init>(Dialog.java:107)
11-06 12:01:25.988: W/System.err(27121):    at android.app.AlertDialog.<init>(AlertDialog.java:114)
11-06 12:01:25.993: W/System.err(27121):    at android.app.AlertDialog$Builder.create(AlertDialog.java:913)
11-06 12:01:25.993: W/System.err(27121):    at android.app.AlertDialog$Builder.show(AlertDialog.java:931)
11-06 12:01:25.993: W/System.err(27121):    at com.mseiz.give.your.apps.upload.upload(upload.java:124)
11-06 12:01:25.993: W/System.err(27121):    at com.mseiz.give.your.apps.upload$DownloadFilesTask.doInBackground(upload.java:153)
11-06 12:01:25.993: W/System.err(27121):    at com.mseiz.give.your.apps.upload$DownloadFilesTask.doInBackground(upload.java:1)
11-06 12:01:25.993: W/System.err(27121):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-06 12:01:25.993: W/System.err(27121):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-06 12:01:25.993: W/System.err(27121):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-06 12:01:25.993: W/System.err(27121):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-06 12:01:25.993: W/System.err(27121):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-06 12:01:25.993: W/System.err(27121):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-06 12:01:25.993: W/System.err(27121):    at java.lang.Thread.run(Thread.java:856)

==== 点击项目... ====

     @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  // TODO Auto-generated method stub
  File file = new File(path.get(position));

  if (file.isDirectory())
  {
   if(file.canRead()){
    getDir(path.get(position));
   }else{
    new AlertDialog.Builder(this)
     .setIcon(R.drawable.ic_launcher)
     .setTitle("[" + file.getName() + "] folder can't be read!")
     .setPositiveButton("OK", null).show(); 
   } 
  }else {
      new DownloadFilesTask().execute(path.get(position), file.getName());   
    }
 }

==== 异步任务 ====

 private class DownloadFilesTask extends AsyncTask<String, Integer, String> {
     ProgressDialog dialog;

     @Override
     protected void onPreExecute() {
         dialog = new ProgressDialog(upload.this);
         dialog.setIcon(R.drawable.ic_launcher);
         dialog.setTitle("Datei wird hochgeladen...");
         dialog.setMessage("Bitte warten...");
         dialog.setIndeterminate(true);
         dialog.show();
     }

     protected String doInBackground(String... args){
         System.out.println("ARGUMENT :: " + args[0]);
         upload(args[0], args[1]);
         return root;

     }

    protected void onPostExecute(Void unused) {
         dialog.dismiss();
     }
 }

==== 上传功能 ====

    public void upload(String upload, String datei)
{
    try {
        connectFTP("176.28.25.46");

    // Prepare file to be uploaded to FTP Server
    File file = new File(upload);
    FileInputStream ifile = new FileInputStream(file);

    // Upload file to FTP Server
    if(ftpClient.storeFile("/subdomains/giveyourapps/httpdocs/apps/"+datei, ifile)){
        new AlertDialog.Builder(this)
        .setIcon(R.drawable.ic_launcher)
        .setTitle("Datei wurde hochgeladen!")
        .setPositiveButton("OK", null).show(); 
    } else {
        new AlertDialog.Builder(this)
        .setIcon(R.drawable.ic_launcher)
        .setTitle("Fehler!")
        .setPositiveButton("OK", null).show(); 
    }
    ftpClient.disconnect();
}catch (Exception e) {
    e.printStackTrace();
}
}
4

3 回答 3

3

您不能在任务中显示对话框。事实上,您不能在主 (UI) 线程之外执行任何 UI 更改。有关更多信息,请参阅进程和线程参考

在 youAsynctask中,您应该使用publishProgress()onProgressUpdate()来执行 UI 更新。

阅读AsyncTask 参考以获取更多详细信息。

于 2012-11-06T11:07:33.547 回答
0

尝试这个

public class loadVideo extends AsyncTask<Void, Integer, Void> {

    int progress = 0;
    long duration;
    Notification notification;
    NotificationManager notificationManager;
    int id = 10;
    long pk;
    protected void onPreExecute() {
        Toast.makeText(getApplicationContext(),
                "Check upload Status in the Notification Bar", 1).show();
        Intent intent = new Intent();
        final PendingIntent pendingIntent = PendingIntent.getActivity(
                getApplicationContext(), 0, intent, 0);
        notification = new Notification(R.drawable.ic_launcher,
                "Uploading file", System.currentTimeMillis());
        notification.flags = notification.flags
                | Notification.FLAG_ONGOING_EVENT;
        notification.contentView = new RemoteViews(getApplicationContext()
                .getPackageName(), R.layout.upload_progress_bar);
        notification.contentIntent = pendingIntent;
        notification.contentView.setImageViewResource(R.id.imageView1,
                R.drawable.ic_launcher);
        notification.contentView.setTextViewText(R.id.textView1,
                "Uploading...");
        // notification.contentView.setProgressBar(R.id.progressBar1, 100,
        // progress[0], false);
        getApplicationContext();
        notificationManager = (NotificationManager) getApplicationContext()
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(id, notification);
        System.out.println("DOMAIN...+" + str_edt_domain_name
                + "DOMAINPASSWORD..." + str_edt_username + "PASSOWRD"
                + str_edt_password);
    }

    @Override
    protected Void doInBackground(Void... params) {
        int count = 0;
        FTPClient ObjFtpCon = new FTPClient();
        // Toast.makeText(con, "FTPasync doInBackground() is called"
        // ,Toast.LENGTH_SHORT).show();
        try {
            runOnUiThread(new Runnable() {
                public void run() {
                    System.out.println("man 0");
                    // bar.setProgress(0);
                    // real_time.setText(0 + " secs");
                    // test_avg.setText(0+ " kbps");
                    // peak.setText(0+" kbps");
                }
            });
            // updateUI(pp, R.drawable.pause);
            // ObjFtpCon.connect("ftp.customhdclips.com");
            ObjFtpCon.connect("domainname");
            // updateUI(status, "Connecting");
            System.out.println("man connecting");

            // if (ObjFtpCon.login("fstech@customhdclips.com", "fstech123"))
            // {
            if (ObjFtpCon.login("username", "password")) {
                // updateUI(status, "Connected");
                System.out.println("man CONNECTED");

                // toast("Connected to FTP Server : ftp.customhdclips.com");
                ObjFtpCon.enterLocalPassiveMode(); // important!
                //ObjFtpCon.cwd("/");// to send the FTP CWD command to the
                                    // server, receive the reply, and return
                                    // the reply code.

                // ObjFtpCon.connect("ftp."+map.get("url").toString());
                // updateUI(status, "Connecting");
                //
                // ObjFtpCon.login(map.get("username").toString(),
                // map.get("password").toString());
                // ObjFtpCon.enterLocalPassiveMode();
                // ObjFtpCon.cwd("/var/www/html/BevdogAnd");

                ObjFtpCon.setFileType(FTP.BINARY_FILE_TYPE);

                final long started = System.currentTimeMillis();
                long sleepingTime = 0;
                // String sourceFileUri
                // =extStorageDirectory+"/zkfile"+filename;
                File file = new File(path);
                long fileSize = file.length();
                int sentBytes = 0;
                InputStream inputStream = new FileInputStream(file);

                System.out.println("Start uploading second file");
                OutputStream outputStream = ObjFtpCon
                        .storeFileStream("Meera Nandan at 60th Filmfare Awards 2013 _99_.jpg");
                byte[] bytesIn = new byte[512];
                int read = 0;
                while ((read = inputStream.read(bytesIn)) != -1) {
                    //updateUI(status, "Uploading");
                    System.out.println("man Uploading");

                    outputStream.write(bytesIn, 0, read);
                    sentBytes += read;
                    final int progress = (int) ((sentBytes * 100) / fileSize);
                    final long speed = sentBytes;

                    duration = ((System.currentTimeMillis() - started) - sleepingTime) / 1000;
                    runOnUiThread(new Runnable() {
                        public void run() {

                        //  bar.setProgress(progress);
                            if (duration != 0) {
                                //   test_avg.setText((((speed /
                                // duration)*1000)*0.0078125) + " kbps");
  //                                    test_avg.setText((speed / duration) / 1024
//                                          + " kbps");
                            System.out.println("MAN spped"+(speed / duration) / 1024
                                        + " kbps"+"and "+progress);
                                if (pk <= (speed / duration) / 1024) {
                                    pk = (speed / duration) / 1024;
                                }
                                /*
                                 * if (pk <= ((speed /
                                 * duration)*1000)*0.0078125) { pk =
                                 * (long)(((speed /
                                 * duration)*1000)*0.0078125); }
                                 */
                                // peak.setText(pk + " kbps");

                            }
                        }
                    });
                }
                inputStream.close();
                outputStream.close();

                boolean completed = ObjFtpCon.completePendingCommand();
//                  updateUI(status, "Completed");
                System.out.println("MAN completed");
                if (completed) {

                }

            }

            /*-------------------------------------------------------------*/
            /*
             * URL url = new URL(map.get("url").toString()); URLConnection
             * conexion = url.openConnection(); conexion.connect();
             * updateUI(status, "Connected");
             * 
             * final int lenghtOfFile = conexion.getContentLength();
             * InputStream input = new
             * BufferedInputStream(url.openStream()); OutputStream output =
             * new FileOutputStream(
             * Environment.getExternalStorageDirectory() + File.separator +
             * Info.getInfo(con).HTTP_DOWNLOAD_FILE_NAME); byte data[] = new
             * byte[1024]; long total = 0; final long started =
             * System.currentTimeMillis(); long sleepingTime= 0;
             * System.out.println("started time --"+started);
             * updateUI(status, "Downloading"); while ((count =
             * input.read(data)) != -1) { while (sleep) {
             * Thread.sleep(1000); sleepingTime +=1000; } total += count;
             * final int progress = (int) ((total * 100) / lenghtOfFile);
             * final long speed = total; duration =
             * ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
             * runOnUiThread(new Runnable() { public void run() {
             * bar.setProgress(progress);
             */

            /*-----------------------------------------------------------------------*/

            else {
                System.out.println("password entered is incorrect");
                // Toast.makeText(con,
                // "Username or/and password is incorrect",
                // Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            // toast(e.getLocalizedMessage());
        }

        try {
            ObjFtpCon.logout();
            ObjFtpCon.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
            // toast(e.getLocalizedMessage());
        }
        return null;
    }

    // @Override
    // protected void onProgressUpdate(Integer... progress) {
    //
    // Intent intent = new Intent();
    // final PendingIntent pendingIntent = PendingIntent.getActivity(
    // getApplicationContext(), 0, intent, 0);
    // notification = new Notification(R.drawable.ic_launcher,
    // "Uploading file", System.currentTimeMillis());
    // notification.flags = notification.flags
    // | Notification.FLAG_ONGOING_EVENT;
    // notification.contentView = new RemoteViews(getApplicationContext()
    // .getPackageName(), R.layout.upload_progress_bar);
    // notification.contentIntent = pendingIntent;
    // notification.contentView.setImageViewResource(R.id.imageView1,
    // R.drawable.ic_launcher);
    // notification.contentView.setTextViewText(R.id.textView1,
    // "Uploading...");
    // notification.contentView.setProgressBar(R.id.progressBar1, 100,
    // progress[0], false);
    // getApplicationContext();
    // notificationManager = (NotificationManager) getApplicationContext()
    // .getSystemService(Context.NOTIFICATION_SERVICE);
    // notificationManager.notify(id, notification);
    // }

    protected void onPostExecute(Void result) {
        System.out.println("status_string.." + status_string);
        Notification notification = new Notification();
        Intent intent1 = new Intent(MainActivity.this, MainActivity.class);
        final PendingIntent pendingIntent = PendingIntent.getActivity(
                getApplicationContext(), 0, intent1, 0);
        int icon = R.drawable.ic_launcher; // icon from resources
        CharSequence tickerText = "Video Uploaded Successfully"; // ticker-text
        CharSequence contentTitle = getResources().getString(
                R.string.app_name); // expanded message
        // title
        CharSequence contentText = ""; // expanded
        if (upload_result == true && status_string.equals("1")) {

            contentText = "Video Uploaded Successfully";
            // message
        } else {
            contentText = "Video Uploaded Failed";

        }
        long when = System.currentTimeMillis(); // notification time
        Context context = getApplicationContext(); // application
                                                        // Context
        notification = new Notification(icon, tickerText, when);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.setLatestEventInfo(context, contentTitle, contentText,
                pendingIntent);
        String notificationService = Context.NOTIFICATION_SERVICE;
        notificationManager = (NotificationManager) context
                .getSystemService(notificationService);
        notificationManager.notify(id, notification);
    }
}
于 2013-08-25T19:45:43.510 回答
0

您不能在上传()中显示对话框。该方法是从 doInBackground 中调用的,并且该方法在后台线程中运行,而不是在 UI 线程中。

查看 AsyncTask 文档,了解哪些 AsyncTask 方法在哪个线程中执行以及在任一线程中允许和禁止什么。

于 2012-11-06T11:13:32.743 回答