2012-06-24 3 views
0

우선, 나는 Java에 대해 일반적으로 & 안드로이드가 처음임을 언급해야합니다. 나는 기초를 가지고있다, 또는 적어도 거기에 도착한다.AsynTask를 사용하여 서버에 SSH를 시도하는 동안 진행률 표시 줄을 표시

내 응용 프로그램의 목적 : 회사에서 우리는 SSH를 사용하는 원격 서버를 보유하고 있습니다. 때로는 서버에 도달 할 수 없으므로 작업이 중단됩니다. , Jsch를 사용

1, 난 응답이있는 경우 응답이 없을 경우, 다음, 내가 15 분 후에 다시 시도합니다 서버에 SSH :

내 응용 프로그램은 다음을 수행한다고 가정한다 나는 알리고 싶다.

위의 작업을 Java의 Android 버전이 아니고 Android 버전에서 수행 할 수 있지만 기본 스레드에서 수행 할 수 있으므로 UI에서 아무 것도 업데이트 할 수 없습니다. 본질적으로 진행률 막대. 일반 버전에서는 UI가 정지되고 아래에 제공된 AsyncTask 버전에 있습니다. 버튼을 누르 자마자 예외가 발생합니다.

아래 코드는 제가 사용하고있는 코드입니다. 솔직히 말해서, 최선의 해결책은 AsyncTask이지만, 새로운 것이므로 잘 모르겠습니다. 내 잘못이야. 솔직히 AsyncTask와 AsyncTask에 있다고 가정합니다.

여기에 무엇을 사용해야할지 모르겠다 ... 다음은 내 코드이며, 누군가 내 실수를 지적 할 수 있습니다.

package com.example.myapp; 

import java.io.IOException; 

import android.app.Activity; 
import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.content.ComponentName; 
import android.content.Context; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.HandlerThread; 
import android.os.StrictMode; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ProgressBar; 
import android.widget.Toast; 
import android.os.Handler; 

public class VedasServerMonitorActivity extends Activity { 
    /** Called when the activity is first created. */ 


    Button button; 
    EditText IP; 
    EditText UserName; 
    EditText Password; 
    EditText Port; 
    ProgressBar progressBar1; 

    String UserStr; 
    String PassStr; 
    String IPStr; 
    int PortInt; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     button = (Button) findViewById(R.id.button1); 
     IP = (EditText) findViewById(R.id.serverIp); 
     UserName = (EditText) findViewById(R.id.userName); 
     Password = (EditText) findViewById(R.id.password); 
     Port = (EditText) findViewById(R.id.port); 
     progressBar1 = (ProgressBar) findViewById(R.id.progressBar1); 

     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
       .permitAll().build(); 

     StrictMode.setThreadPolicy(policy); 

     button.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 



       new asyncTaskUpdateProgress().execute(); 

      } 

     }); 

    } 

    public class asyncTaskUpdateProgress extends AsyncTask<Void, Void, Void> { 



     @Override 
     protected void onPostExecute(Void result) { 
      // TODO Auto-generated method stub 







     } 

     @Override 
     protected void onPreExecute() { 
      // TODO Auto-generated method stub 
      progressBar1.setVisibility(View.VISIBLE); 
      UserStr = UserName.getText().toString(); 
      PassStr = Password.getText().toString(); 
      IPStr = IP.getText().toString(); 
      PortInt = Integer.parseInt(Port.getText().toString()); 

      button.setClickable(true); 
      progressBar1.setVisibility(View.INVISIBLE); 



     } 

     @Override 
     protected void onProgressUpdate(Void... values) { 
      // TODO Auto-generated method stub 
      progressBar1.setVisibility(View.INVISIBLE); 

     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      boolean ok = false; 


try { 


      SSHTest sshtest = new SSHTest(); 
      ok = sshtest.sshconnect(UserStr, PassStr, IPStr, PortInt); 
      } 

     catch (Exception e) { 
       e.printStackTrace(); 
       Log.i("ERROR HERE", "doInBackground: IOException");} 
if (ok) { 

    Toast.makeText(getApplicationContext(), 
    "Connection Susccessfull", Toast.LENGTH_LONG) 
    .show(); 

} else { 

    Toast.makeText(getApplicationContext(), 
    "Unable to connect", Toast.LENGTH_LONG).show(); 
    notify(getApplicationContext(), true); 

} 
return null; 


     } 


     protected void notify(Context context, Boolean on) { 
      NotificationManager nm = (NotificationManager) context 
        .getSystemService(Context.NOTIFICATION_SERVICE); 
      ComponentName comp = new ComponentName(context.getPackageName(), 
        getClass().getName()); 
      Intent intent = new Intent().setComponent(comp); 
      PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, 
        intent, Intent.FLAG_ACTIVITY_NEW_TASK); 
      Notification n = new Notification(R.drawable.warning, "Message", 
        System.currentTimeMillis()); 
      n.setLatestEventInfo(context, "Vedas Server Monitor", 
        "Port Un-rechable", pendingIntent); 
      nm.notify(22, n); 
     } 

    } 

} 

안드로이드 × 194,760

답변

1

당신이 doInBackground()에 확인해야합니다 약간의 수정이 있습니다. 그러나 그 전에는 AsyncTask에 대한 작은 세부 사항이 있습니다.

AsyncTask은 UI가 아닌 배경 작업을 수행 할 때 사용됩니다. onPreExecute()은 백그라운드 스레드에 들어가기 전에 모든 UI 동작 (대개 대화 상자 표시)을 표시하는 데 사용됩니다. doInBackground() 함수는 비 사용자 작업 (대부분의 경우 서버에서 데이터 가져 오기)을 수행하는 데 사용됩니다. doInBackground()에서 백그라운드 활동을 수행하는 동안 내부적으로 onProgressUpdate() 메소드를 호출하는 publishProgress()을 사용하여 진행 상황을 보여줄 수 있습니다. doInBackground()에서 백그라운드 활동이 완료되면 활동의 result을 반환합니다 (있는 경우). doInBackground() 메서드에서 내부적으로 돌아 오면 onPostExecute()에 전화가 걸려 result을 받고 doInBackground()을 매개 변수로 반환합니다. 이제 onPostExecute()는 UI 스레드에서 실행하고 onPreExecute()에 나타내었다 대화의 삭제 중 같은 UI 액션의 대부분을 일부 UI 구성 요소에 result 표시 등이 방법 일 것입니다.

지금 실수에 당신은 당신의 코드에서하고 있습니다 : 당신은 기능 notify를 사용하여 페치 toast 또는 서버 데이터의 결과에 따라 notification를 보이고 있지만 배경 비 UI 스레드에서 여전히. 이제이 결과는 onPostExecute()에서 반환되고 확인되어야하며 값에 따라 toast 또는 notification의 UI 구성 요소를 표시 할 수 있습니다.

이 설명이 문제를 해결하는 데 도움이되기를 바랍니다.

편집이 onPostExecute()-ok 변수 부울 유형의 결과를 보낼 수 있기 때문에 귀하의 경우에는

. 당신이
에서 시도 할 수 있습니다

public class asyncTaskUpdateProgress extends AsyncTask<Void, Void, Boolean> 

protected void onPostExecute(Boolean result){ 
if (ok) { 

Toast.makeText(getApplicationContext(), 
"Connection Susccessfull", Toast.LENGTH_LONG) 
.show(); 

} else { 

Toast.makeText(getApplicationContext(), 
"Unable to connect", Toast.LENGTH_LONG).show(); 
notify(getApplicationContext(), true); 

} 
} 

마지막

protected Void doInBackground(Void... arg0) { 
     boolean ok = false; 


try { 


     SSHTest sshtest = new SSHTest(); 
     ok = sshtest.sshconnect(UserStr, PassStr, IPStr, PortInt); 
     } 

    catch (Exception e) { 
      e.printStackTrace(); 
      Log.i("ERROR HERE", "doInBackground: IOException");} 

return ok; 

} 
+0

Arun, 고맙습니다. 정말 고맙습니다. 내 유일한 문제는 그러나 코드에 점점 :) ... 참으로 초보자입니다,하지만 당신이 토스트와 알림에 관한 언급에서, 나는 그들을 당분간 언급하면, 여전히 진행률 표시 줄을 보여줄까요? 문제가있는 다른 문제는 무엇을 전달하고 어떻게해야합니까? 예 : protected void Void doInBackground (Void ... arg0) void로 두어야합니까? args0? (이것은 잃어 버렸습니다. –

+0

AsyncTask를 확장하는 동안'AsyncTask 와 같은 3 개의 매개 변수 유형을 지정합니다. 여기서'Params'는'doInBackground()'에 보내는 매개 변수 유형이고, Progress '는'onProgressUpdate()'에 보내고'결과'는'onPreExecute()'에 대한 매개 변수 유형입니다. –

+0

내 편집 된 게시물 확인 –

1

에 :

클래스 선언에서 :이를 위해 다음과 같은 변경해야 protected void onPreExecute()
에 추가해야합니다.

progressBar = new ProgressDialog(v.getContext()); 
     progressBar.setCancelable(true); 
     progressBar.setMessage("File downloading ..."); 
     progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     progressBar.setProgress(0); 
     progressBar.setMax(100); 
     progressBar.show(); 

     //reset progress bar status 
     progressBarStatus = 0; 

protected void onProgressUpdate(Void... values) { 
    progressBarStatus= progressBarStatus + x; // x means any value 
     progressBar.setProgress(progressBarStatus); 

    } 



은 그 후 당신은 onPostExecute()에서의 ProgressBar를 완료해야합니다. like

protected void onPostExecute(Void result) { 
     progressBar.dismiss(); 
} 
관련 문제