我對Android開發很陌生,在我的第一個嚴肅的項目的後期狀態。簡而言之,該程序將SSH入主機並執行命令。但是我發現自己真的被束縛在試圖完成這個的節點上。如何管理AsyncTask和對話需要
我正在使用ganymed-ssh2來執行ssh grunt-work。
當活動按鈕被擊中時,我希望程序啓動SSH會話,驗證主機指紋 - 在必要時提示接受,然後按程序發出遠程命令。但是,這個看似簡單的幾個步驟,都變得非常的複雜,下面:
- 的SSH不能在UI線程來執行,所以我必須要啓動的AsyncTask,因此所有的東西我在接下來的麻煩形容是不在前臺UI線程中。
要啓動SSH指紋識別代碼,我需要讓我的AsyncTask類中像這樣的電話:
@Override protected String doInBackground(String... command) { String result; result = ""; try { /* Create a connection instance */ Connection conn = new Connection(connect.getHost(), connect.getPort()); /* Now connect */ ConnectionInfo info = conn.connect(new AdvancedVerifier()); boolean isAuthenticated = false; // first try public key if defined if (connect.getPrivateKey() != null) isAuthenticated = conn.authenticateWithPublicKey (connect.getUserid(), connect.getPrivateKey(), null); // if failed, or not defined, try password if provide if (!isAuthenticated && connect.getPassword() != null) isAuthenticated = conn.authenticateWithPassword(connect.getUserid(), new String (connect.getPassword())); // all else, get out if (!isAuthenticated) throw new IOException("Authentication failed."); /* Create a session */ Session sess = conn.openSession(); sess.execCommand(command[0]); }
然而,conn.connect(新AdvancedVerifier())行導致回調接口類AdvancedVerifier的被調用,在連接調用中斷執行路徑調用這個類:
class AdvancedVerifier implements ServerHostKeyVerifier
{
public boolean verifyServerHostKey(String hostname, int port,
String serverHostKeyAlgorithm,
byte[] serverHostKey) throws Exception
{
final String host = hostname;
final String algo = serverHostKeyAlgorithm;
/* Check database - code removed*/
/* assuming fingerprint needs verification */
String hexFingerprint =
KnownHosts.createHexFingerprint(serverHostKeyAlgorithm,
serverHostKey);
String msg = "Hex Fingerprint: " + hexFingerprint;
/* right here, I need to display dialog of fingerprint,
and ask user for to continue;
If user accepts, return true, else return false.
If return true, the above class continues after connect(), if false
it is aborted.
*/
return UserAccepts? true : false;
}
}
嗯,這,在我有限的經驗,似乎引起很多忠實地亂碼。 首先,我需要重新連接到UI線程,顯示一個對話框,然後如果用戶選擇 OK,然後從verifyServerHostKey()返回「true」,分離UI線程,並允許ssh連接代碼恢復。所有都無法使用模態對話框。
坦率地說,我真的不知道從哪裏開始,我期待的想法,指導等