【问题标题】:Android:Is my Async Method working?Android:我的异步方法有效吗?
【发布时间】:2014-08-13 14:15:55
【问题描述】:

我决定为了加速我的应用程序并避免崩溃,我将通过 AsyncTask 方法在后台线程上运行我的方法 PetrolPriceString。然而,即使我的应用程序仍然运行,也没有加速并且查看我的代码,我确信我在放置方法时犯了一个错误,而且我认为尽管没有错误,我的一些代码可能是错误的。我的方法只是在后台线程中运行 PetrolPriceString 方法并返回 urlString,我希望它包含一个指向指定 RSS 提要的 URL。

    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.ProgressDialog;
import android.os.AsyncTask;
//import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class PetrolPriceActivity extends Menu 
{
    private TextView response;
    private TextView errorText;
    private String result;
    private String petrolPriceURL;
    private static final String TAG = "PetrolPrice";


    /** 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
         new AsyncTask<String, String, String>() {
            IOException exception = null;
            @Override protected String doInBackground(String... params) {
                try {
                    Log.v(TAG, "index=" + "hello");
                    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);

        return result;

    }
    // End of petrolPriceString
 // End of Activity class
}

我对 android 比较陌生,对线程的概念也很陌生,因此非常感谢任何帮助

【问题讨论】:

  • 好吧,第一个代码是的,对于实际的 asynctask 代码,我不太确定。如果这就是你的意思,我没有错误
  • AsyncTask实际上并没有加速执行,它只是将它与UI Thread分开,这意味着UI Thread可以同时执行其他工作。
  • 所以我应该将 PetrolPriceString 中的所有代码移动到 AsyncTask 中? Yeh Sasha Salauyou 我希望该方法在后台运行,因为如果我稍后添加更多内容可能会导致错误
  • 非常感谢您的帮助
  • (String urlString)throw IOException - 我将如何在我的内部类中执行此操作?

标签: java android multithreading asynchronous


【解决方案1】:

在我看来你只是在跑步

Log.v(TAG, "index=" + "hello");
return petrolPriceString(params[0]);

在后台线程上。当你第一次在这里调用这个方法时

result =  petrolPriceString(petrolPriceURL)

它通过该网络代码运行,然后运行AsyncTask,它再次调用该方法。好像是在递归调用自己。

我建议将AsynctTask 设为它自己的内部类,然后执行它,运行方法中的所有代码。

See this answer 了解如何做到这一点。

AsyncTask Docs

【讨论】:

  • 如何在我的 PetrolPriceActivity 活动中执行它?我会简单地使用 TalkToServer AsyncTask = new MyTask(); AsyncTask.execute();
  • @user3071845 使用链接中的示例在您的Activity 中创建一个内部类(您可以随意命名)。然后在任何需要的地方执行它。 AsyncTask.execute(petrolPriceURL) 但该变量应该是驼峰式大小写以符合 Java 标准。
  • 嗨,我想我已经让它工作了,但是我如何将我的结果变量从我的内部类传递给我的 PetroleumPriceActivity 类?这就是我需要让它工作的所有内容,因为当我检查我的 logcat 时,我确实有正确的信息
  • 正如链接的答案所示,由于它是Activity 的内部类,您可以简单地在onPostExecute() 中更新您的View
【解决方案2】:

我自己写了一个答案来帮助其他有同样问题的人。

petrolPriceString(..) 代码放入PetrolPriceActivity 的内部类中,该类扩展AsyncTask

并在onCreate方法中执行:

new asyncTask().execute(petrolPriceURL);

之后为更新 UI 所做的任何事情都在 onPostExecute 而不是 onCreate 上处理。

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.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class PetrolPriceActivity extends Menu {
    private TextView response;
    private TextView errorText;
    private String petrolPriceURL;
    private static final String TAG = "PetrolPrice";

    /** 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
        new asyncTask().execute(petrolPriceURL);
    }

    public class asyncTask extends AsyncTask<String, Void, String> {
           @Override
           protected String doInBackground(String...parmans) {
               String urlString = petrolPriceURL;
               {
                    String result = "";
                    InputStream anInStream = null;
                    int response = -1;
                    URL url = null;
                    try {
                        url = new URL(urlString);
                    } catch (MalformedURLException e) {
                        return null;
                    }

                    URLConnection conn = null;
                    try {
                        conn = url.openConnection();
                    } catch (IOException e) {
                        return null;
                    }

                    // Check that the connection can be opened
                    if (!(conn instanceof HttpURLConnection))
                        try {
                            throw new IOException("Not an HTTP connection");
                        } catch (IOException e) {
                            return null;
                        }
                    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 (IOException ex) {
                            try {
                                throw new IOException("Error connecting");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                    }

                    return result;
                }
           }

           @Override
           protected void onPostExecute(String result) {
               // Get the data from the RSS stream as a string
               response = (TextView)findViewById(R.id.error);
               response = (TextView)findViewById(R.id.title);

               try {
                    // Get the data from the RSS stream as a string
                    result =  doInBackground(petrolPriceURL);

                    response.setText(result);
                    Log.v(TAG, "index=" + result);
                } catch(Exception ae) {
                    // Handle error
                    response.setText("Error");
                    // Add error info to log for diagnostics
                    errorText.setText(ae.toString());
                }
            }
        }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多