使用AsynTask显示进度条,当试图SSH到服务器 [英] Using AsynTask to show progress bar while attempting to SSH to Server

查看:236
本文介绍了使用AsynTask显示进度条,当试图SSH到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我要声明,我一般和功放是新来的Java; Android系统。然而,我有基础,或者至少到达那里。

First of all, i have to state that i am new to Java in general & Android. I do however have the basics, or at least getting there.

我的应用程序的目的:在公司,我们有我们SSH连接到远程服务器,并做了一些工作。在某些时候,服务器无法访问,因此破坏了我们的工作。

The Purpose of my Application: At the company, we have a Remote server that we SSH to, and do some work. At some times, the server is unreachable and therefore disrupts our work.

我的应用程序是假设做到以下几点:

My application is suppose to do the following:

1使用Jsch,我ssh到服务器上,如果有反应,那么,我将再次在15分钟内尝试,如果没有反应,我想通知。

1- Using Jsch, i SSH to the server, if there is a response, then, i will attempt again in 15 minutes, if there is no response, i want to notify.

我已经成功地做​​到在Java中的非Android版本以上,并且是能够做到这一点在Android版本,但在主线程,因此,我无法更新在用户界面上任何东西。本质上,进度栏..
在普通版本中,UI冻结,并在AsyncTask的版本提供如下。我尽快得到一个例外,因为我打的按钮

i have successfully done the above in non android version of Java, and was able to do it in Android version, however on the main thread, thus i cannot update anything on the UI. In essence the Progress Bar.. In the regular version, the UI freezes, and in the AsyncTask version provided below. i get an exception as soon as i hit the button

下面是code我使用,说实话,我读遍,最好的解决办法是AsyncTask的,但因为我是新来的,我不知道是我错了就是。老实说,我认为它可能是在AsyncTask的和AsyncTask的。

Below is the code i am using, to be honest, i read all over that the best solution is AsyncTask, but since i am new to that, i am not sure were my wrong is. I honestly assume its may be in the AsyncTask and AsyncTask .

我不知道用什么有...
下面是我的code,希望有人能指出我的错误。

I am not sure what to use there... Below is my code, hopefully someone can point out my mistake.

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);
        }

    }

}

安卓×194760

android× 194760

推荐答案

有一些调整,你需要在 doInBackground()进行。但在此之前,一个小细节有关的AsyncTask

There are some correction that you need to make in the doInBackground(). But before that a small detailing about the AsyncTask.

的AsyncTask 如果您有任何非UI回地面活动进行使用。功能上preExecute()是用来显示任何UI操作
(在大多数情况下,它表现出对话),然后进入后台线程。功能 doInBackground()用于执行非UI操作(在大多数情况下,从服务器获取数据)。虽然这样做在的背景活动doInBackground()你不妨表现出你使用做了一定的进展 publishProgress()这将在内部调用 onProgressUpdate()方法。在后台活动的完成doInBackground()返回活动的结果,如果您有任何。当您从 doInBackground()方法返回内部还有就是做呼叫 onPostExecute()将接收的结果您在 doInBackground()作为参数。现在 onPostExecute()将运行在UI线程和大多数UI动作像preExecute对话框,在所示的解聘() ,在某些UI组件等显示结果发生在这个方法。

AsyncTask is used when you have any non-UI back ground activity to perform. The function onPreExecute() is used to show any UI action (in most cases its showing of a dialog) before you enter the background thread. The function doInBackground() is used to perform the non-ui action (in most cases fetching data from server). While doing the background activity in doInBackground() you may wish to show some progress which you do by using publishProgress() which will internally call the onProgressUpdate() method. On completion of the background activity in doInBackground() you return the result of the activity, if you have any. After you return from the doInBackground() method internally there is call made to the onPostExecute() which will receive the result you have returned in doInBackground() as a parameter. Now onPostExecute() will run on a UI thread and most of the UI action like dismissing of dialog which was shown in onPreExecute(), displaying the result on some UI component etc. happens in this method.

现在你在你正在做code错误:
你这是面包的通知根据您的服务器数据的结果读取使用函数通知但你仍然在后台非UI线程。现在,这个结果应该理想地返回,并在 onPostExecute(),并根据其值可以显示敬酒的UI组件的通知

Now to the mistake you are doing in you code: You are showing a toast or a notification based on the result of your server data fetch using a function notify but you are still in the background non-ui thread. Now this result should ideally be returned and checked in the onPostExecute() and based on its value you can show the UI component of toastor notification.

我希望这可以帮助解释您解决您的问题。

I hope this explanation helps you in solving your problem.

修改

在你的情况,因为你可以发送布尔类型的结果变量确定 onPostExecute()。对于您需要进行以下更改:

In your case since you can send the boolean type result variable ok to onPostExecute(). For that you need to make the following changes:

在类声明:

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;

 }

这篇关于使用AsynTask显示进度条,当试图SSH到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆