我開發了一個應用程序,它從互聯網獲取內容並在設備的屏幕上顯示相應內容。該程序運行良好,有點慢。大約需要3-4秒來加載和顯示內容。我想將我的代碼放在後臺線程中完成所有工作(獲取Web內容並顯示它)。另外,我想展示一個進度對話框。Android異步任務下載失敗err
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();
}*/
}
如果我用這段代碼運行應用程序,我得到這個:download failed。另一方面,如果我保留最終線程,則應用程序崩潰,NullPointerException。我真的不知道該做什麼了。
我真的很滿意,如果你可以給我一個替代這個代碼,不只是一些提示,因爲我是新來的android和我真的不知道很多。謝謝。
UPDATE:
我不想顯示下載進度,我想顯示的進度對話框,直到應用程序已準備好顯示的全部內容。
訪問此http://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog – kehnar
有沒有必要Thread.sleep(params [0]);因爲AsyncTask是無痛線程本身,所以你不需要關心線程。 –
你的日誌說什麼? – Maggie