прогресс jsoup.connect / jsoup.parse - PullRequest
5 голосов
/ 22 марта 2011

Я использую Jsoup в своем приложении для Android для анализа данных с веб-страницы. Я хочу показать прогресс

Jsoup.connect(...).get();

или

Jsoup.parse(....);

Как это сделать? Есть ли метод, который вызывается автоматически, когда прогресс изменяется как веб-просмотр. Пожалуйста, дайте мне идею, как выполнить задачу.

Ответы [ 2 ]

0 голосов
/ 25 сентября 2014

Я считаю, что в Jsoup нет методов для получения прогресса get () и post (). Мне удалось сделать это через HttpURLConnection, а затем передать Jsoup.parse файл. Это выглядит так: (не забудьте добавить разрешения в файл манифеста)

WithFileProgress.java:

public class WithFileProgress {
ProgressDialog progressDialog;
Context context;
TextView content;

public WithFileProgress(Context context, TextView content) {
    this.context = context;
    this.content = content;
}

public void connect(String url) {
    new downloadHTML().execute(url);
}

private class downloadHTML extends AsyncTask<String, Integer, Document> { // params, progress, result

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setTitle("downloadHTML");
        progressDialog.setMessage("Loading...");
        progressDialog.setIndeterminate(true);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(true);
        progressDialog.show();
    }

    @Override
    protected Document doInBackground(String... params) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        File file;
        Document d = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("downloadHTML").setMessage("Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage()).create();
            }

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();

            file = new File(Environment.getExternalStorageDirectory(), "downloadHTML.tmp");
            output = new FileOutputStream(file);

            byte data[] = new byte[8192];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;
                // publishing the progress....
                if (fileLength > 0) // only if total length is known
                    publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }

            d = Jsoup.parse(file, null);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return d;
    }

    @Override
    protected void onPostExecute(Document d) {
        super.onPostExecute(d);
        content.setText(d.html());
        progressDialog.dismiss();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        // if we get here, length is known, now set indeterminate to false
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setProgress(values[0]);
    }

}

}

MainActivity.java:

public class MainActivity extends Activity {
WithFileProgress api;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView content = (TextView)findViewById(R.id.content);
    api = new WithFileProgress(this, content);

    Button button = (Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            EditText input = (EditText)findViewById(R.id.input);
            String url = input.getText().toString();

            if (Jsoup.isValid(url, new Whitelist())) {
                api.connect(url);
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
                builder.setTitle("MainActivity").setMessage("Invalid address: "+url).create();
            }
        }
    });
}

}

activity_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<ScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/contentScroll"
    android:layout_above="@+id/input"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/content" />

</ScrollView>

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/input"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_toLeftOf="@+id/button"
    android:hint="URL address" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Download"
    android:id="@+id/button"
    android:layout_alignBottom="@+id/input"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@+id/input" />

0 голосов
/ 01 июля 2012

Точно так же: используйте вес тестовой веб-страницы, разделенный на время анализа, и используйте это значение в качестве множителя для других страниц.При первом запуске приложения вы можете рассчитать его.

И я думаю, что пользователю не нужен супер точный таймер.

И легкость в поиске подсказывает мне, что jsoup не нуждался в методах.(Поправьте меня если я не прав)

...