0

首先,我必须声明我是 Java 和 Android 的新手。但是,我确实有基础知识,或者至少可以到达那里。

我的应用程序的目的:在公司,我们有一个远程服务器,我们通过 SSH 连接到该服务器,并做一些工作。有时,服务器无法访问,因此会中断我们的工作。

我的应用程序应该执行以下操作:

1-使用Jsch,我SSH到服务器,如果有响应,那么,我会在15分钟内再次尝试,如果没有响应,我想通知。

我已经在非 android 版本的 Java 中成功完成了上述操作,并且能够在 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);
        }

    }

}

机器人× 194760

4

2 回答 2

1

您需要在doInBackground(). 但在此之前,关于AsyncTask.

AsyncTask当您有任何非 UI 后台活动要执行时使用。该函数onPreExecute()用于在您进入后台线程之前显示任何 UI 操作(在大多数情况下显示对话框)。该函数doInBackground()用于执行非 ui 操作(在大多数情况下从服务器获取数据)。在进行后台活动时,doInBackground()您可能希望显示一些您通过使用publishProgress()将在内部调用该onProgressUpdate()方法所做的进度。在后台活动完成后,doInBackground()您返回result活动的,如果有的话。在您从doInBackground()内部方法返回后,将调用onPostExecute()将接收result您返回的doInBackground()作为参数的方法。现在onPostExecute()将在 UI 线程上运行,并且大多数 UI 操作(如取消显示的对话框、在某些 UI 组件onPreExecute()上显示result等)都发生在此方法中。

现在,您在代码中犯的错误:您正在显示 atoast或 anotification基于使用函数获取服务器数据的结果,notify但您仍处于后台非 ui 线程中。现在,理想情况下应该返回并检查此结果,onPostExecute()并且根据其值,您可以显示toast或的 UI 组件notification

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

编辑

在您的情况下,因为您可以将布尔类型结果变量发送okonPostExecute(). 为此,您需要进行以下更改:

在类声明中:

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;

 }
于 2012-06-24T07:24:36.627 回答
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()。像

protected void onPostExecute(Void result) {
        progressBar.dismiss();
}
于 2012-06-24T08:00:03.763 回答