1

以前はこのフォーラムでいくらか活発に活動していましたが、忙しくなり、もうプログラムする時間がありませんでした。

ネットワーク上にある CSV ファイルからライブ統計をアプリに取得させるにはどうすればよいでしょうか....CSV ファイルは約 1 分ごとに更新されるため、ネットワークから直接読み取る方法が必要です....プログラムまた、csvファイルをソートして特定の値のみを引き出す必要がありますが、この問題を理解した後、後でその側面について心配するつもりです. 誰でも助けることができますか?ありがとう!

4

4 に答える 4

2

Web サーバー上のファイルに関心があるとします。 ここには2つの解決策があります。G: ドライブをネットワーク共有にするか、Windows 用の Apache をインストールし、コードの派生物を使用して Web サーバーから csv ファイルを取得します。

ネットワーク共有ルート:

Android デバイス用の AndSMB などの Samba クライアントが必要です。これは、Windows ボックスから共有ドライブをマウントし、ファイルをデバイスにコピーするために使用されます。次に、他の場合と同じようにファイルを開く必要があります。この Q/A を出発点として使用してください: Android で SD カードから特定のファイルを読み取る

アパッチルート:

Apache をインストールして構成します: http://httpd.apache.org/docs/2.2/platform/windows.html

これは、やりたいことに適応できるはずです。あなたの発信者は、私のコールバックのようなものを実装します。呼び出し元は、AsyncTask を実装するクラスをインスタンス化します。これは、メインの GUI スレッドからネットワーク トラフィックを切り離すために使用されます。そうしないと、3.0(?) 以降で問題が発生します。必要に応じてコードを細かく分割します。これを github のプロジェクトとして立ち上げる必要があります。プロジェクトは、完全なコードが必要な人のためにここにあります: https://github.com/nedwidek/Android-Rest-API

折り返し電話:

package com.hatterassoftware.restapi;

import java.net.URL;
import java.util.HashMap;

import android.os.AsyncTask;
import android.util.Log;

/**
 * An AsyncTask implementation for performing POSTs on the Hypothetical REST APIs.
 */
public class GetTask extends AsyncTask<String, String, HttpReturn>{
    private String restUrl;
    private RestCallback callback;
    private HashMap<String, String> headers;
    private String username;
    private String password;

    final String TAG = "GetTask";

    /**
     * Creates a new instance of PostTask with the specified URL, callback, and
     * request body.
     * 
     * @param restUrl The URL for the REST API.
     * @param callback The callback to be invoked when the HTTP request
     *            completes.
     * @param requestBody The body of the POST request.
     * 
     */
    public GetTask(String restUrl, RestCallback callback, HashMap<String, String> headers, String username, String password){
        this.restUrl = restUrl;
        this.callback = callback;
        this.headers = headers;
        this.username = username;
        this.password = password;
    }

    @Override
    protected HttpReturn doInBackground(String... params) {
        try {
            RestHttpUrlConnection request = new RestHttpUrlConnection(new URL(restUrl), headers, username, password);
            return request.doGetRequest();
        } catch (Throwable t) {
            Log.e(TAG, "Exception in doInBackground", t);
            return new HttpReturn(new RestException(t));
        }
    }

    @Override
    protected void onPostExecute(HttpReturn result) {
        Log.d(TAG, "Entered onPostExecute");
        Log.d(TAG, "result.status = " + result.status);
        Log.d(TAG, "result.content = " + result.content);
        callback.onTaskComplete(result);
        super.onPostExecute(result);
    }
}
package com.hatterassoftware.restapi;

import java.net.URL;
import java.util.HashMap;

import android.os.AsyncTask;
import android.util.Log;

/**
 * An AsyncTask implementation for performing POSTs on the Hypothetical REST APIs.
 */
public class GetTask extends AsyncTask<String, String, HttpReturn>{
    private String restUrl;
    private RestCallback callback;
    private HashMap<String, String> headers;
    private String username;
    private String password;

    final String TAG = "GetTask";

    /**
     * Creates a new instance of PostTask with the specified URL, callback, and
     * request body.
     * 
     * @param restUrl The URL for the REST API.
     * @param callback The callback to be invoked when the HTTP request
     *            completes.
     * @param requestBody The body of the POST request.
     * 
     */
    public GetTask(String restUrl, RestCallback callback, HashMap<String, String> headers, String username, String password){
        this.restUrl = restUrl;
        this.callback = callback;
        this.headers = headers;
        this.username = username;
        this.password = password;
    }

    @Override
    protected HttpReturn doInBackground(String... params) {
        try {
            RestHttpUrlConnection request = new RestHttpUrlConnection(new URL(restUrl), headers, username, password);
            return request.doGetRequest();
        } catch (Throwable t) {
            Log.e(TAG, "Exception in doInBackground", t);
            return new HttpReturn(new RestException(t));
        }
    }

    @Override
    protected void onPostExecute(HttpReturn result) {
        Log.d(TAG, "Entered onPostExecute");
        Log.d(TAG, "result.status = " + result.status);
        Log.d(TAG, "result.content = " + result.content);
        callback.onTaskComplete(result);
        super.onPostExecute(result);
    }
}

package com.hatterassoftware.restapi;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;

import android.util.Base64;
import android.util.Log;

public class RestHttpUrlConnection {

    private HttpURLConnection connection;

    final String TAG = "RestHttpUrlConnection";

    protected RestHttpUrlConnection(URL url, HashMap<String,String> headers, final String username, final String password) throws IOException {
        connection = (HttpURLConnection) url.openConnection();

        if(headers != null) {
            for(String key: headers.keySet()) {
                Log.d(TAG, "Adding header: " + key + "; " + headers.get(key));
                connection.addRequestProperty(key, headers.get(key));
            }
        }

        if(username != null) {
            String auth = "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.DEFAULT);

            connection.addRequestProperty("Authorization", auth);
        }
    }

    public HttpReturn doPostRequest(String postData) throws IOException {
        return doPostOrPut(true, postData);
    }

    public HttpReturn doGetRequest() throws IOException {
        return doGetOrDelete(true);
    }

    public HttpReturn doPutRequest(String putData) throws IOException {
        return doPostOrPut(false, putData);
    }

    public HttpReturn doDeleteRequest() throws IOException {
        return doGetOrDelete(false);
    }

    private HttpReturn doGetOrDelete(boolean isGet) throws ProtocolException, IOException {
        if (isGet) {
            connection.setRequestMethod("GET");
        } else {
            connection.setRequestMethod("DELETE");
        }

        String line;
        StringBuffer output = new StringBuffer(1024);
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = in.readLine()) != null) output.append(line);
        } catch (Exception e) {
            HttpReturn httpReturn = new HttpReturn(connection.getResponseCode(), output.toString());
            httpReturn.restException = new RestException(e);
            return httpReturn;
        }

        return new HttpReturn(connection.getResponseCode(), output.toString());
    }

    private HttpReturn doPostOrPut(boolean isPost, String data) throws ProtocolException, IOException {
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setFixedLengthStreamingMode(data.getBytes().length);
        if (isPost) {
            connection.setRequestMethod("POST");
        } else {
            connection.setRequestMethod("PUT");
        }

        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes(data);
        out.flush();
        out.close();

        connection.connect();

        String line;
        StringBuffer output = new StringBuffer(1024);
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = in.readLine()) != null) output.append(line);
        } catch (Exception e) {
            HttpReturn httpReturn = new HttpReturn(connection.getResponseCode(), output.toString());
            httpReturn.restException = new RestException(e);
            return httpReturn;
        }

        return new HttpReturn(connection.getResponseCode(), output.toString());     
    }
}
于 2013-01-16T20:56:33.693 に答える
1

csv を含むディスクをデバイスで使用できるようにして、次のような URL を使用できるようにします。

http://192.168.1.1/some.csv (run a webserver like apache)
or 
file://somedrive/somedir/some.csv (mount the disk). 

次に、csv を解析し、必要なデータを保存します。

その後、X 分間スリープし、open/parse 関数を再度呼び出します。事実上、アプリケーションを停止または終了するように指示するまで、プログラムは無限にループします。

お役に立てれば

于 2013-01-16T20:46:58.247 に答える
0

CSV ファイルが HTTP(S) 経由でアクセスできると仮定すると、 を使用HTTPURLConnectionしてリソースにアクセスし、オブジェクトのgetBody()メソッド経由でデータを引き出すことができます。Response前後に UI を同期的に更新する必要がないと仮定すると、これを新しいものとして実装してRunnableから呼び出すことができstart()ます。それ以外の場合は、 AsyncTaskを読みたいと思うでしょう。

ポーリング動作については、待機基準を表現する必要があります (つまり、アクティビティの実行中にずっとこれを行うか、バックグラウンドで実行する必要があるか、x回試行した後、またはyが true のときに停止する必要があるかなど)。 .) ただしsleep()、ネットワーク アクティビティを実行する前にスレッドを呼び出すことができます。

答えがあいまいな場合は申し訳ありません-基本的な正しい方向を探しているようです。それ以外の場合は、必要なものの詳細を投稿してください...

于 2013-01-16T20:54:23.167 に答える
0

ローカル Web サーバーを公開して、csv ファイルをデバイスにダウンロードできる可能性はありますか? ダウンロード後、それに応じてファイルを読み取って解析できます。

私の意見では、X 分間スリープしてから作業を再開するサービスを Android アプリに作成する必要があります。また、IntentService を介してジョブを完了し、AlarmManager を使用してアラームをプログラミングすることもできます。いずれの場合も、ResultReceivers を介して画面 (Activity) を更新します。

それが役に立てば幸い。

可能であれば、より適切な方向性を示すために、達成したいアプリの動作をより具体的にしてください。

于 2013-01-16T20:55:13.570 に答える