1

我以前在这个论坛上有点活跃,但我变得很忙,没有时间再编程了,反正我现在又回到了它,我需要一些帮助......

我将如何让我的应用程序从位于我的网络上的 CSV 文件中获取实时统计信息...... CSV 文件大约每分钟更新一次,所以我需要一种直接从网络读取的方法......程序还必须对 csv 文件进行排序,并且只提取某些值,但是在我弄清楚这个问题之后,我会担心这方面的问题。有人可以帮忙吗?谢谢!

4

4 回答 4

2

假设您对 Web 服务器上的文件感兴趣。 您在这里有 2 个解决方案。制作你的 G: 驱动网络共享或安装 Apache for windows 并使用我的代码派生从网络服务器获取 csv 文件。

网络共享路由:

您的 Android 设备需要像 AndSMB 这样的 Samba 客户端。这将用于从您的 Windows 框中安装共享驱动器并将文件复制到您的设备。然后,您需要像打开其他文件一样打开该文件。使用此 Q/A 作为起点:在 android 中从 sdcard 读取特定文件

阿帕奇路线:

安装和配置 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 分钟,然后重新调用你的打开/解析函数。实际上,您的程序现在将无限循环,直到您告诉它停止或退出应用程序。

希望这可以帮助

于 2013-01-16T20:46:58.247 回答
0

假设您的 CSV 文件可以通过 HTTP(S) 访问,您可以使用它HTTPURLConnection来访问资源,通过对象的getBody()方法提取数据Response。假设您不需要在之前或之后同步更新 UI,您可以将其实现为新的Runnable,然后调用start()它。否则,您将需要阅读AsyncTask

对于轮询行为,您需要表达您的等待条件(即它是否在 Activity 运行时一直这样做;它是否需要在后台运行?它应该在x尝试后停止还是在y为真时停止,等等.) 但您可以sleep()在进行网络活动之前调用线程。

抱歉,如果答案含糊不清 - 听起来您正在寻找一些基本的指向正确的方向。否则,请发布有关您需要的更多详细信息...

于 2013-01-16T20:54:23.167 回答
0

您是否有机会发布本地 Web 服务器并将 csv 文件下载到设备?下载后,您可以相应地读取和解析文件。

在我看来,你应该在你的 Android 应用程序中创建一个服务,它会休眠 X 分钟然后恢复工作。您还可以通过 IntentService 完成工作并使用 AlarmManager 编写警报。在任何这些情况下,您都可以通过 ResultReceivers 更新屏幕(活动)。

希望能帮助到你。

如果可以,请更具体地说明您想要实现的应用行为,以便为您提供更好的指导。

于 2013-01-16T20:55:13.570 回答