我开发了一个应用程序,它从互联网上获取内容,并相应地在设备的屏幕上显示。这个程序运行得很好,有点慢。加载和显示内容大约需要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();
}
}发布于 2011-10-10 14:42:04
检查ASyncTask,它是为此类任务专门创建的。
发布于 2011-10-10 14:38:25
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();发布于 2016-07-08 03:53:22
如何使用使用后台线程工作。
注意:
不使用具有此后台线程的UI。
AsyncTask.execute(new Runnable() {
@Override
public void run() {
//TODO background code
}
});希望这能帮到你。
https://stackoverflow.com/questions/7714299
复制相似问题