简体   繁体   中英

Android Runtime.getRuntime().exec command causes app to freeze before getting an output

I'am trying to Build an app that can ping servers and get latency. For which

Process process = Runtime.getRuntime().exec(pingCommand);

command calls a system/bin/ping -c command.

So, when I press Calculate (A button that i use) from UI, it freezes the app until the exec is completed. How do i fix the freeze so that it can allow me to close my keyboard while the answer is fetched?

you are doing network request in UI thread, so it is freezing because of waiting for response (and keeping connection alive)

use any of async ways to do network stuff, best way for you will be AsyncTask (move your network-related method calls to doInBackground method, publish results in onPostExecute )

To avoid UI freezes run in thread

new Thread(new Runnable() {
        public void run() {

            try {
                // Send script into runtime process
                Process process = Runtime.getRuntime().exec(pingCommand);

                // ......

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // .....
            }
        }
    }).start();
}

Alternative

You can use AsyncTask like this:

private class YourTasksClass extends AsyncTask<Void, Void, String> {


    private String cmd;

    public YourTasksClass(String command) {
        this.cmd = command;
    }

    @Override
    protected String doInBackground(Void... voids) {


        try {
            Process process = Runtime.getRuntime().exec(cmd);

            // ....

            String someResult = "some kind of result";

            return someResult;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if(result != null) {
            Log.d("tag", "Result: " + result);
        }

    }
}

Later in your code, you can call this by:

new YourTasksClass(pingCommand).execute();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM