开发者

Android: How to work with background thread?

开发者 https://www.devze.com 2023-04-11 19:29 出处:网络
I\'ve developed an application that takes content from the internet and shows it accordingly on the device\'s screen . The program works just fine , a little bit slow . It takes about 3-4 seconds to l

I've developed an application that takes content from the internet and shows it accordingly on the device's screen . The program works just fine , a little bit slow . It takes about 3-4 seconds to load and display the content . I would like to put all the code that fetches the content and displays it in a background thread and while the program is doing those functions , I would like to display a progress dialog. Could you help me do this ? I would like especially to learn how to put the code in a background thread.

MY CODE

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 (param开发者_运维百科s == 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();
    }
}


Check ASyncTask, its specifically created for such tasks.


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();
            }
        }

    }
};

now start this with

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


How to work with Background Thread.

Note:

Do not work with UI with this background thread.

AsyncTask.execute(new Runnable() {
   @Override
   public void run() {
      //TODO background code
   }
});

Hope this would help you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号