【问题标题】:Executing a Ping Task in Android Java在 Android Java 中执行 Ping 任务
【发布时间】:2017-06-27 19:14:59
【问题描述】:

我正在尝试将 Ping 实用程序实现为 Android 中的 AsyncTask。以下基本上是我的doInBackground函数。

mProcess = Runtime.getRuntime().exec("/system/bin/ping -c 6 " + url );
    try {
        InputStream in = mProcess.getInputStream();
        OutputStream out = mProcess.getOutputStream();
        byte[] buffer = new byte[ 1024 ];
        int count;

        while( ( count = in.read( buffer ) ) != -1 ){
            mPOut.write( buffer, 0, count );
            publishProgress();
            Log.d("PING TASK", "PING.... PING....");
            if( isCancelled() ) {
                return null;
            }
        }

        out.close();
        in.close();
        mPOut.close();
        mPIn.close();
    } finally {
        mProcess.destroy();
        mProcess = null;
        Log.d("PING TASK", "DONE");
    }
} catch( IOException e ) {
    Log.d("PING TASK", e.getMessage());
}
return null;

它按预期工作,但前提是我 ping 一个响应的地址,例如 android.com8.8.8.8。但如果我 ping 一个没有响应的地址,例如 intel.comlalalalalalalaandroid.com(我还没有完全检查那个),则不会。

如果我在我的电脑上执行ping -c 6 intel.com,我至少会得到第一行PING intel.com (13.91.95.74) 56(84) bytes of data.Ping request could not find host lalalalalalalaandroid.com Please check the name and try again.

但我的应用程序中没有这些...我在这里缺少什么?

【问题讨论】:

  • 请注意,Android 设备不需要具有ping 实用程序,更不用说在该特定文件系统位置。
  • 我知道,目前这不是问题。我只是在摆弄。
  • 如果您通过 adb shell 而不是您的 PC(可能运行不同的 ping 实现)运行命令,您会得到什么?

标签: java android android-asynctask ping runtime.exec


【解决方案1】:

根据文档,AsyncTasks 只能执行一次。尝试在您的可运行计时器中重新初始化它。

public void InitializeTimerTask() {
    timerPingTask = new timerPingTask() {
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    new PingAsyncTask().execute();
                }
            });
        }

【讨论】:

  • 谢谢,但在 Activity 的代码中已经处理好了。多次执行任务有效。
猜你喜欢
  • 2022-06-13
  • 1970-01-01
  • 2015-03-20
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多