【问题标题】:Android: Asynch Thread for MethodAndroid:方法的异步线程
【发布时间】:2014-08-11 21:00:11
【问题描述】:

我意识到,为了让我的应用程序的一部分工作,我可能需要在单独的线程上运行它。在此之后,我的选择似乎是异步和线程,我认为异步似乎是更好的选择,因为我在使用线程方面几乎没有经验。我正在尝试在单独的线程上运行 PetroPriceString,但我没有这样做的知识。对此的任何帮助将不胜感激

编辑:我整个班级的补充

package org.me.myandroidstuff;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

//import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class PetrolPriceActivity extends Menu 
{
    private TextView response;
    private TextView errorText;
    private String result;
    private String petrolPriceURL;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);

        Bundle extras = getIntent().getExtras();
        if(extras!=null){
        petrolPriceURL =extras.getString("URLString");
        }
        // Get the TextView object on which to display the results
        response = (TextView)findViewById(R.id.error);
        response = (TextView)findViewById(R.id.title);
        try
        {
            // Get the data from the RSS stream as a string
            result =  petrolPriceString(petrolPriceURL);

            // Do some processing of the data to get the individual parts of the RSS stream
            // At some point put this processing into a separate thread of execution
            // Display the string in the TextView object just to demonstrate this capability
            // This will need to be removed at some point
            response.setText(result);
        }
        catch(IOException ae)
        {
            // Handle error
            response.setText("Error");
            // Add error info to log for diagnostics
            errorText.setText(ae.toString());
        } 

    }

    // End of onCreate

    // Method to handle the reading of the data from the RSS stream
    private static String petrolPriceString(String urlString)throws IOException
    {
        String result = "";
        InputStream anInStream = null;
        int response = -1;
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        // Check that the connection can be opened
        if (!(conn instanceof HttpURLConnection))
                throw new IOException("Not an HTTP connection");
        try
        {
            // Open connection
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            // Check that connection is Ok
            if (response == HttpURLConnection.HTTP_OK)
            {
                // Connection is OK so open a reader 
                anInStream = httpConn.getInputStream();
                InputStreamReader in= new InputStreamReader(anInStream);
                BufferedReader bin= new BufferedReader(in);

                // Read in the data from the RSS stream
                String line = new String();
                while (( (line = bin.readLine())) != null)
                {
                    result = result + "\n" + line;
                }
            }
        }
        catch (Exception ex)
        {
                throw new IOException("Error connecting");
        }

        // Return result as a string for further processing
        return result;
    }
    // End of petrolPriceString
 // End of Activity class
}

我的应用程序目前没有错误,但是我得到的输出不是我想要的,所以我相信一个单独的线程就是答案

【问题讨论】:

    标签: java android eclipse multithreading asynchronous


    【解决方案1】:

    AsyncTask 可用于在后台进行缓慢的工作(如网络交互)并在主/UI 线程上进行最后一点处理/交互。如果我正确理解了您的要求,您可以尝试以下操作:

    new AsyncTask<String, Void, String>() {
        @Override protected String doInBackground(String... params) {
            // we do this part in the background on another thread
            return petrolPriceString(params[0]);
        }
        @Override protected void onPostExecute(String result) {
            // result is the value returned from our call to petrolPriceString
            // anything we put in here is done on the main/UI thread
        }
    }.execute(urlString);
    

    如果您想捕获由 PetroPriceString 引发的异常,并相应地执行一些逻辑,一种可能的解决方案是将其保存为 AsyncTask 中的本地成员。类似于以下内容...

    new AsyncTask<String, Void, String>() {
        IOException exception = null;
        @Override protected String doInBackground(String... params) {
            try {
                return petrolPriceString(params[0]);
            } catch (IOException e) {
                exception = e;
                return null;
            }
        }
        @Override protected void onPostExecute(String result) {
            if (exception != null) {
                // handle our exception
            } else {
                // handle our result
            }
        }
    }.execute(urlString);
    

    【讨论】:

    • 很好,是的,我认为这正是我想要的。我可以在与我的汽油价格字符串相同的活动中使用此 AsyncTask 方法并且它仍将在单独的线程上运行吗?
    • 是的,doInBackground 部分将在 Android 为您设置的池中的单独线程上执行。
    • 在 onPostExecute 的情况下,我在 try catch 块中的其他地方有代码,用于处理石油价格字符串的后果,添加的 onPostExcute 方法将如何改变?
    • 我认为在这种情况下最简单的解决方案是在 AsyncTask 本身内捕获异常。我已经用一个如何实现这一点的例子更新了我的答案。希望这适用于您要完成的工作。
    • 非常感谢。 doinbackground 是长而不是字符串。这是为什么?
    猜你喜欢
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多