【问题标题】:Android: How to work with background thread?Android:如何使用后台线程?
【发布时间】:2011-10-10 14:31:40
【问题描述】:

我开发了一个应用程序,它从互联网上获取内容并相应地显示在设备的屏幕上。该程序运行良好,有点慢。加载和显示内容大约需要 3-4 秒。我想将所有获取内容并将其显示在后台线程中的代码,当程序执行这些功能时,我想显示一个进度对话框。你能帮我做这件事吗?我特别想学习如何将代码放在后台线程中。

我的代码

public class Activity1 extends Activity
{
    private ProgressDialog progressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        new AsyncTask<Integer, Integer, Boolean>()
        {
            ProgressDialog progressDialog;

            @Override
            protected void onPreExecute()
            {
                /*
                 * This is executed on UI thread before doInBackground(). It is
                 * the perfect place to show the progress dialog.
                 */
                progressDialog = ProgressDialog.show(Activity1.this, "",
                        "Loading...");
            }

            @Override
            protected Boolean doInBackground(Integer... params)
            {
                if (params == null)
                {
                    return false;
                }
                try
                {
                    /*
                     * This is run on a background thread, so we can sleep here
                     * or do whatever we want without blocking UI thread. A more
                     * advanced use would download chunks of fixed size and call
                     * publishProgress();
                     */
                    Thread.sleep(params[0]);
                    // HERE I'VE PUT ALL THE FUNCTIONS THAT WORK FOR ME
                }
                catch (Exception e)
                {
                    Log.e("tag", e.getMessage());
                    /*
                     * The task failed
                     */
                    return false;
                }

                /*
                 * The task succeeded
                 */
                return true;
            }

            @Override
            protected void onPostExecute(Boolean result)
            {
                progressDialog.dismiss();
                /*
                 * Update here your view objects with content from download. It
                 * is save to dismiss dialogs, update views, etc., since we are
                 * working on UI thread.
                 */
                AlertDialog.Builder b = new AlertDialog.Builder(Activity1.this);
                b.setTitle(android.R.string.dialog_alert_title);
                if (result)
                {
                    b.setMessage("Download succeeded");
                }
                else
                {
                    b.setMessage("Download failed");
                }
                b.setPositiveButton(getString(android.R.string.ok),
                        new DialogInterface.OnClickListener()
                        {

                            @Override
                            public void onClick(DialogInterface dlg, int arg1)
                            {
                                dlg.dismiss();
                            }
                        });
                b.create().show();
            }
        }.execute(2000);

        new Thread()
        {
            @Override
            public void run()
            {

                // dismiss the progressdialog
                progressDialog.dismiss();
            }
        }.start();
    }
}

【问题讨论】:

  • 你从哪里得到空指针? (屏幕截图没有为我加载。)另外,只有progressDialog.dismiss() 的第二个线程的目的是什么?
  • 我认为您的 Thread.sleep 调用引发了异常。并且异常没有消息,所以 e.getMessage() 返回 null。

标签: android multithreading background


【解决方案1】:

检查ASyncTask,它是专门为此类任务创建的。

【讨论】:

  • +1 异步任务是要走的路。它允许您从后台线程更新 UI 线程。
  • 所以我被告知..如果你能告诉我我的代码有什么问题(在我的问题中),你肯定会获得投票......如果我使用它,应用程序会崩溃跨度>
  • 首先,我将删除底部的 Thread 对象,因为它没有做任何事情。
  • 我的猜测是底部的新 Thread() 东西导致了空指针。
【解决方案2】:
public Runnable NameOfRunnable = new Runnable()
{
    @Override
    public void run()
    {
        while (true)
        {
            // TODO add code to refresh in background
            try
            {
                Thread.sleep(1000);// sleeps 1 second
            }
            catch (InterruptedException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
};

现在开始

                    Thread name = new Thread(NameOfRunnable);
                    name.start();

【讨论】:

  • 这个线程不能在 UI 线程上做任何事情,所以提这个是没有意义的。他需要能够与 UI 线程对话才能更新进度对话框。异步任务是要走的路。
  • 取决于您如何设置活动。查看与 UI 交互的 Handler 类
【解决方案3】:

如何使用后台线程

注意:

不要在 UI 上使用此后台线程
AsyncTask.execute(new Runnable() {
   @Override
   public void run() {
      //TODO background code
   }
});

希望这会对你有所帮助。

【讨论】:

  • 这是一个完美的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多