2017-04-13 67 views
-2

我已經爲Android編寫了一個網絡(JSch)異步任務。出於某種原因,AsyncTask永遠不會結束,直到我再次調用buttonClick()。這裏是我的代碼:Android - AsyncTask永無止境

public class MainActivity extends AppCompatActivity 

{ @覆蓋 保護無效的onCreate(捆綁savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }

protected void buttonClick(View view) 
    { 
      System.out.println(" --------------------------------- "); 
      System.out.println(" CONNECT BUTTON CLICKED!"); 
      System.out.println(" --------------------------------- "); 
      new AsyncTask<Void, Void, Void>() { 
        @Override 
        protected Void doInBackground(Void... params) 
        { 
          connect(); 
          System.out.println("Connect done"); 
          return null; 
        } 
        protected Void onPostExecute() 
        { 
          System.out.println("PostExec done"); 
          return null; 
        } 
      }.execute(); 
      System.out.println("Done with ASyncTask"); 
      String text = output; 
      TextView tv = (TextView)findViewById(R.id.ayy); 
      tv.setText(text); 
    } 

    private int d; 
    private String output; 
    private void debug() 
    { 
      System.out.println("Debug" + d); 
      d++; 
    } 

    private void connect() 
    { 
      d = 1; 
      debug(); 
      JSch jsch = new JSch(); 
      String host = "[edited out]"; 
      String user = "[edited out]"; 
      String password = "[edited out for obvious reasons]"; 
      String command = "uname -a"; 
      int port = 2223; 
      try { 
        debug(); 
        Session session = jsch.getSession(user, host, port); 
        debug(); 
        UserInfo ui = new MyUserInfo(); 
        debug(); 
        session.setUserInfo(ui); 
        debug(); 
        session.connect(); 
        debug(); 
        Channel channel = session.openChannel("exec"); 
        debug(); 
        ((ChannelExec) channel).setCommand(command); 
        debug(); 
        channel.setInputStream(null); 
        debug(); 
        ((ChannelExec) channel).setErrStream(System.err); 
        debug(); 
        InputStream in = channel.getInputStream(); 
        debug(); 
        channel.connect(); 
        debug(); 
        byte[] tmp = new byte[1024]; 
        while(true) { 
          while(in.available() > 0) { 
            int i = in.read(tmp, 0, 1024); 
            if(i < 0) break; 
            output = output + new String(tmp, 0, i); 
          } 
          if(channel.isClosed()) { 
            if(in.available() > 0) continue; 
            System.out.println("exit-status: " + channel.getExitStatus()); 
            break; 
          } 
          try { 
            Thread.sleep(1000); 
          } catch(Exception ee) { 

          } 
        } 
        channel.disconnect(); 
        session.disconnect(); 
      } catch(Exception e) { 
        System.err.println("Exception: " + e); 
        e.printStackTrace(); 
      } 
    } 
    } 

    class MyUserInfo implements UserInfo, UIKeyboardInteractive 
    { 
    public String getPassword() 
    { 
      return passwd; 
    } 

    public boolean promptYesNo(String str) 
    { 
        /*Object[] options = {"yes", "no"}; 
        int foo = JOptionPane.showOptionDialog(null, 
          str, 
          "Warning", 
          JOptionPane.DEFAULT_OPTION, 
          JOptionPane.WARNING_MESSAGE, 
          null, options, options[0]); 
        return foo == 0; */ 
      return true; 
    } 

    String passwd; 

    public String getPassphrase() 
    { 
      return null; 
    } 

    public boolean promptPassphrase(String message) 
    { 
      return true; 
    } 

    public boolean promptPassword(String message) 
    { 
      passwd = "[edited out]"; 
      return true; 
    } 

    public void showMessage(String message) 
    { 
      System.out.println("MSG: " + message); 
    } 

    /* 
    final GridBagConstraints gbc = 
      new GridBagConstraints(0, 0, 1, 1, 1, 1, 
        GridBagConstraints.NORTHWEST, 
        GridBagConstraints.NONE, 
        new Insets(0, 0, 0, 0), 0, 0); 
    private Container panel; 
    */ 
    public String[] promptKeyboardInteractive(String destination, 
               String name, 
               String instruction, 
               String[] prompt, 
               boolean[] echo) 
    { System.out.println("promptKeyboardInteractive");/* 
      panel = new JPanel(); 
      panel.setLayout(new GridBagLayout()); 

      gbc.weightx = 1.0; 
      gbc.gridwidth = GridBagConstraints.REMAINDER; 
      gbc.gridx = 0; 
      panel.add(new JLabel(instruction), gbc); 
      gbc.gridy++; 

      gbc.gridwidth = GridBagConstraints.RELATIVE; 

      JTextField[] texts = new JTextField[prompt.length]; 
      for(int i = 0; i < prompt.length; i++) { 
        gbc.fill = GridBagConstraints.NONE; 
        gbc.gridx = 0; 
        gbc.weightx = 1; 
        panel.add(new JLabel(prompt[i]), gbc); 

        gbc.gridx = 1; 
        gbc.fill = GridBagConstraints.HORIZONTAL; 
        gbc.weighty = 1; 
        if(echo[i]) { 
          texts[i] = new JTextField(20); 
        } else { 
          texts[i] = new JPasswordField(20); 
        } 
        panel.add(texts[i], gbc); 
        gbc.gridy++; 
      } 

      if(JOptionPane.showConfirmDialog(null, panel, 
        destination + ": " + name, 
        JOptionPane.OK_CANCEL_OPTION, 
        JOptionPane.QUESTION_MESSAGE) 
        == JOptionPane.OK_OPTION) { 
        String[] response = new String[prompt.length]; 
        for(int i = 0; i < prompt.length; i++) { 
          response[i] = texts[i].getText(); 
        } 
        return response; 
      } else { 
        return null; // cancel 
      } 
    */ 
      return null; 
     } 
} 

我完全知道該代碼是一塌糊塗,但是我將它清理乾淨,一旦我得到這個工作。

輸出後1個按鈕點擊:按鈕點擊

輸出後2
04-13 15:45:33.451 26826-26826/com.example.ryan.jschtest I/System.out: --------------------------------- 
04-13 15:45:33.451 26826-26826/com.example.ryan.jschtest I/System.out: CONNECT BUTTON CLICKED! 
04-13 15:45:33.451 26826-26826/com.example.ryan.jschtest I/System.out: --------------------------------- 
04-13 15:45:33.452 26826-26826/com.example.ryan.jschtest I/System.out: Done with Asynctask 
04-13 15:45:33.452 26826-26925/com.example.ryan.jschtest I/System.out: Debug1 
04-13 15:45:33.457 26826-26925/com.example.ryan.jschtest I/System.out: Debug2 
04-13 15:45:33.470 26826-26925/com.example.ryan.jschtest I/System.out: Debug3 
04-13 15:45:33.470 26826-26925/com.example.ryan.jschtest I/System.out: Debug4 
04-13 15:45:33.470 26826-26925/com.example.ryan.jschtest I/System.out: Debug5 
04-13 15:45:33.472 26826-26925/com.example.ryan.jschtest I/System.out: Connecting: 192.168.1.18:2223 
04-13 15:45:34.008 26826-26925/com.example.ryan.jschtest I/System.out: Debug6 
04-13 15:45:34.013 26826-26925/com.example.ryan.jschtest I/System.out: Debug7 
04-13 15:45:34.013 26826-26925/com.example.ryan.jschtest I/System.out: Debug8 
04-13 15:45:34.013 26826-26925/com.example.ryan.jschtest I/System.out: Debug9 
    04-13 15:45:34.013 26826-26925/com.example.ryan.jschtest I/System.out: Debug10 
    04-13 15:45:34.014 26826-26925/com.example.ryan.jschtest I/System.out: Debug11 
04-13 15:45:34.076 26826-26925/com.example.ryan.jschtest I/System.out: Debug12 
04-13 15:45:35.112 26826-26925/com.example.ryan.jschtest I/System.out: exit-status: 0 
04-13 15:45:35.115 26826-26925/com.example.ryan.jschtest I/System.out:  Connect done 

04-13 15:45:33.451 26826-26826/com.example.ryan.jschtest I/System.out: --------------------------------- 
04-13 15:45:33.451 26826-26826/com.example.ryan.jschtest I/System.out: CONNECT BUTTON CLICKED! 
04-13 15:45:33.451 26826-26826/com.example.ryan.jschtest I/System.out: --------------------------------- 
04-13 15:45:33.452 26826-26826/com.example.ryan.jschtest I/System.out: Done with Asynctask 
04-13 15:45:33.452 26826-26925/com.example.ryan.jschtest I/System.out: Debug1 
04-13 15:45:33.457 26826-26925/com.example.ryan.jschtest I/System.out: Debug2 
04-13 15:45:33.470 26826-26925/com.example.ryan.jschtest I/System.out: Debug3 
04-13 15:45:33.470 26826-26925/com.example.ryan.jschtest I/System.out: Debug4 
04-13 15:45:33.470 26826-26925/com.example.ryan.jschtest I/System.out: Debug5 
04-13 15:45:34.008 26826-26925/com.example.ryan.jschtest I/System.out: Debug6 
04-13 15:45:34.013 26826-26925/com.example.ryan.jschtest I/System.out: Debug7 
04-13 15:45:34.013 26826-26925/com.example.ryan.jschtest I/System.out: Debug8 
04-13 15:45:34.013 26826-26925/com.example.ryan.jschtest I/System.out: Debug9 
04-13 15:45:34.013 26826-26925/com.example.ryan.jschtest I/System.out: Debug10 
04-13 15:45:34.014 26826-26925/com.example.ryan.jschtest I/System.out: Debug11 
04-13 15:45:34.076 26826-26925/com.example.ryan.jschtest I/System.out: Debug12 
04-13 15:45:35.112 26826-26925/com.example.ryan.jschtest I/System.out: exit-status: 0 
04-13 15:45:35.115 26826-26925/com.example.ryan.jschtest I/System.out: Connect done 
04-13 15:47:32.784 26826-26826/com.example.ryan.jschtest I/System.out: --------------------------------- 
04-13 15:47:32.784 26826-26826/com.example.ryan.jschtest I/System.out: CONNECT BUTTON CLICKED! 
04-13 15:47:32.784 26826-26826/com.example.ryan.jschtest I/System.out: --------------------------------- 
04-13 15:47:32.785 26826-26826/com.example.ryan.jschtest I/System.out: Done with Asynctask 
04-13 15:47:32.785 26826-28694/com.example.ryan.jschtest I/System.out: Debug1 
04-13 15:47:32.786 26826-28694/com.example.ryan.jschtest I/System.out: Debug2 
04-13 15:47:32.786 26826-28694/com.example.ryan.jschtest I/System.out: Debug3 
04-13 15:47:32.786 26826-28694/com.example.ryan.jschtest I/System.out: Debug4 
04-13 15:47:32.786 26826-28694/com.example.ryan.jschtest I/System.out: Debug5 
04-13 15:47:33.370 26826-28694/com.example.ryan.jschtest I/System.out: Debug6 
04-13 15:47:33.370 26826-28694/com.example.ryan.jschtest I/System.out: Debug7 
04-13 15:47:33.370 26826-28694/com.example.ryan.jschtest I/System.out: Debug8 
04-13 15:47:33.370 26826-28694/com.example.ryan.jschtest I/System.out: Debug9 
04-13 15:47:33.370 26826-28694/com.example.ryan.jschtest I/System.out: Debug10 
04-13 15:47:33.371 26826-28694/com.example.ryan.jschtest I/System.out: Debug11 
04-13 15:47:33.436 26826-28694/com.example.ryan.jschtest I/System.out: Debug12 
04-13 15:47:34.467 26826-28694/com.example.ryan.jschtest I/System.out: exit-status: 0 
04-13 15:47:34.468 26826-28694/com.example.ryan.jschtest I/System.out: Connect done 
+0

您的代碼無法讀取 –

+0

@IvanMilisavljevic此代碼非常糟糕,但肯定沒那麼糟糕? – Lightn1ng

回答

-1

解決:

public boolean connectComplete = false; 

protected void buttonClick(View view) 
{ 
    ConnectTask ayy = new ConnectTask(); 
    ayy.execute(); 
    while(!connectComplete) { 
     try { Thread.sleep(100); } catch(Exception e) {System.out.println(e); e.printStackTrace; } 
    } 
    ayy.cancel(true); 
    connectComplete = false; 
} 
在ConnectTask

@Override 
protected Void doInBackground(Void... params) 
{ 
     MainActivity.connect(); 
     cancel(true); 
     System.out.println("Connect done"); 
     connectComplete = true; 
     return null; 
} 
+0

這看起來像一個不好的解決方案。您正在主線程中休眠,這會阻塞應用程序的整個UI,並且正在等待異步任務完成,從而導致其異步運行的整個目的失敗。 – RobCo

+0

@RobCo任務從未花費超過半秒鐘,並在應用程序啓動時運行。它使用網絡,所以我被迫運行是異步的。有更好的解決方案來使用嗎? – Lightn1ng

+0

更好的辦法是將回調傳遞給它可以在完成時調用的任務,或者只需要在MainActivity中調用一個單獨的方法。這應該在'onPostExecute'中完成,以便在主線程上再次調用它。這樣主線程可以在doInBackground執行時做其他事情 – RobCo