Android 如何正确连接以从服务器获取多个文件?

Android 如何正确连接以从服务器获取多个文件?,android,Android,我正在开发我的第一个android应用程序,我有一个愚蠢的问题。 我在那里读到:我可以将多个参数(此处为URL)传递给如下方法: *.执行(url1、url2、url3); 然后像典型数组一样使用URL。 但当我尝试这一点时,我只使用了第一个url。 我不知道我在这里做错了什么。有人知道一些有用的东西吗 更新:使用Log.d,我注意到关于传递url和获取数据的一切都很好,但在connect()方法连接到第二个url之后,它就停止了。我想我没有关闭连接/断开连接,这就是它不工作的原因。我查阅了参考

我正在开发我的第一个android应用程序,我有一个愚蠢的问题。 我在那里读到:我可以将多个参数(此处为URL)传递给如下方法: *.执行(url1、url2、url3); 然后像典型数组一样使用URL。 但当我尝试这一点时,我只使用了第一个url。 我不知道我在这里做错了什么。有人知道一些有用的东西吗

更新:使用Log.d,我注意到关于传递url和获取数据的一切都很好,但在connect()方法连接到第二个url之后,它就停止了。我想我没有关闭连接/断开连接,这就是它不工作的原因。我查阅了参考资料,但没有关于断开连接的内容。 这是我的密码:

 public class MyActivity extends Activity {
 TextView cpuT;
 TextView ramT;
 TextView uptimeT;
 TextView storageT;

List<String> ram = new ArrayList<String>();
List<String> cpu = new ArrayList<String>();
List<String> uptime = new ArrayList<String>();
List<String> storage = new ArrayList<String>();
List<String> temperatures = new ArrayList<String>();


public class NetThread extends AsyncTask<URL, Void, Void> {
    @Override
    protected Void doInBackground(URL... urls) {
                int count = urls.length;
            for(int i = 0; i < count; i++) {
                try {
                    List<String> data = new ArrayList<String>();
                    URLConnection conn = urls[i].openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStreamReader isr = new InputStreamReader(conn.getInputStream());
                    BufferedReader in = new BufferedReader(isr);
                    String line;
                    while ((line = in.readLine()) != null) {
                        data.add(line);
                    }
                    in.close();
                        if (urls[i].getFile().equals("/ram")) {
                        ram = data;
                        ramT.setText("");
                        for (String x : ram)
                            ramT.setText(ramT.getText() + x + "\n");
                    }

                    else if (urls[i].getFile().equals("/cpu")) {
                        cpu = data;
                    }

                    else if (urls[i].getFile().equals("/uptime")) {
                        uptime = data;
                        uptimeT.setText("");
                        for (String x : uptime) {
                            uptimeT.setText(uptimeT.getText() + x + "\n");
                        }
                    }

                    else if (urls[i].getFile().equals("/storage")) {
                        storage = data;
                        storageT.setText("");
                        for (String x : storage) {
                            storageT.setText(storageT.getText() + x + "\n");
                        }
                    }

                    else if (urls[i].getFile().equals("/temperatures")) {
                        temperatures = data;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        return null;
    }

}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    cpuT = (TextView) findViewById(R.id.displayCpu);
    ramT = (TextView) findViewById(R.id.displayRam);
    uptimeT = (TextView) findViewById(R.id.displayUptime);
    storageT = (TextView) findViewById(R.id.displayStorage);

    URL ramUrl = null;
    URL uptimeUrl = null;
    URL storageUrl = null;
    try {
        ramUrl = new URL("http", "192.168.0.111", 1984, "/ram");
        uptimeUrl = new URL("http", "192.168.0.111", 1984, "/uptime");
        storageUrl = new URL("http", "192.168.0.111", 1984, "/storage");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    NetThread netThread = new NetThread();
    netThread.execute(ramUrl, uptimeUrl, storageUrl);
}
}
公共类MyActivity扩展活动{
文本视图cpuT;
文本视图ramT;
文本视图正常运行时间;
文本视图存储;
List ram=新的ArrayList();
列表cpu=new ArrayList();
列表正常运行时间=新建ArrayList();
列表存储=新建ArrayList();
列表温度=新的ArrayList();
公共类NetThread扩展异步任务{
@凌驾
受保护的Void doInBackground(URL…URL){
int count=url.length;
for(int i=0;i
IntenServiceAsyncTask提供了一个工作线程,因此无法同时下载多个映像。但是,您可以使用ThreadPoolExecutor进行多次下载。您可以创建一个线程池,根据要下载的文件数量执行这些线程ThreadPoolExecutor几乎可以处理线程管理的各个方面,而且非常高效

以下是创建执行器的代码示例:

ExecutorService mExecutor=
    new ThreadPoolExecutor(
            coreSize,      // basic number of threads
            maxPoolSize,   // maximum number of threads created
            keepAliveTime,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>()
            ); 

IntenServiceAsyncTask提供了一个工作线程,因此无法同时下载多个映像。但是,您可以使用ThreadPoolExecutor进行多次下载。您可以创建一个线程池,根据要下载的文件数量执行这些线程ThreadPoolExecutor几乎可以处理线程管理的各个方面,而且非常高效

以下是创建执行器的代码示例:

ExecutorService mExecutor=
    new ThreadPoolExecutor(
            coreSize,      // basic number of threads
            maxPoolSize,   // maximum number of threads created
            keepAliveTime,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>()
            ); 

你可以检查谷歌的asyc任务样本

public类MainActivity扩展了FragmentActivity{
公共静态最终字符串TAG=“网络连接”;
//引用显示事件的片段,因此我们可以用按钮清除它
//必要时。
私有LogFragment-mLogFragment;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_main);
//初始化显示介绍文本的文本片段。
SimpleTextFragment introFragment=(SimpleTextFragment)
getSupportFragmentManager().findFragmentById(R.id.intro_fragment);
introFragment.setText(R.string.welcome\u消息);
introFragment.getTextView().setTextSize(TypedValue.COMPLEX\u UNIT\u DIP,16.0f);
//初始化日志框架。
初始化日志();
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
getMenuInflater().充气(R.menu.main,menu);
返回true;
}
@奥夫
public class MainActivity extends FragmentActivity {

public static final String TAG = "Network Connect";

// Reference to the fragment showing events, so we can clear it with a button
// as necessary.
private LogFragment mLogFragment;

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

    // Initialize text fragment that displays intro text.
    SimpleTextFragment introFragment = (SimpleTextFragment)
                getSupportFragmentManager().findFragmentById(R.id.intro_fragment);
    introFragment.setText(R.string.welcome_message);
    introFragment.getTextView().setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16.0f);

    // Initialize the logging framework.
    initializeLogging();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // When the user clicks FETCH, fetch the first 500 characters of
        // raw HTML from www.google.com.
        case R.id.fetch_action:
            new DownloadTask().execute("http://www.google.com");
            return true;
        // Clear the log view fragment.
        case R.id.clear_action:
          mLogFragment.getLogView().setText("");
          return true;
    }
    return false;
}

/**
 * Implementation of AsyncTask, to fetch the data in the background away from
 * the UI thread.
 */
private class DownloadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {
        try {
            return loadFromNetwork(urls[0]);
        } catch (IOException e) {
          return getString(R.string.connection_error);
        }
    }

    /**
     * Uses the logging framework to display the output of the fetch
     * operation in the log fragment.
     */
    @Override
    protected void onPostExecute(String result) {
      Log.i(TAG, result);
    }
}

/** Initiates the fetch operation. */
private String loadFromNetwork(String urlString) throws IOException {
    InputStream stream = null;
    String str ="";

    try {
        stream = downloadUrl(urlString);
        str = readIt(stream, 500);
   } finally {
       if (stream != null) {
           stream.close();
        }
    }
    return str;
}

/**
 * Given a string representation of a URL, sets up a connection and gets
 * an input stream.
 * @param urlString A string representation of a URL.
 * @return An InputStream retrieved from a successful HttpURLConnection.
 * @throws java.io.IOException
 */
private InputStream downloadUrl(String urlString) throws IOException {
    // BEGIN_INCLUDE(get_inputstream)
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Start the query
    conn.connect();
    InputStream stream = conn.getInputStream();
    return stream;
    // END_INCLUDE(get_inputstream)
}

/** Reads an InputStream and converts it to a String.
 * @param stream InputStream containing HTML from targeted site.
 * @param len Length of string that this method returns.
 * @return String concatenated according to len parameter.
 * @throws java.io.IOException
 * @throws java.io.UnsupportedEncodingException
 */
private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");
    char[] buffer = new char[len];
    reader.read(buffer);
    return new String(buffer);
}

/** Create a chain of targets that will receive log data */
public void initializeLogging() {

    // Using Log, front-end to the logging chain, emulates
    // android.util.log method signatures.

    // Wraps Android's native log framework
    LogWrapper logWrapper = new LogWrapper();
    Log.setLogNode(logWrapper);

    // A filter that strips out everything except the message text.
    MessageOnlyLogFilter msgFilter = new MessageOnlyLogFilter();
    logWrapper.setNext(msgFilter);

    // On screen logging via a fragment with a TextView.
    mLogFragment =
            (LogFragment) getSupportFragmentManager().findFragmentById(R.id.log_fragment);
    msgFilter.setNext(mLogFragment.getLogView());
}