任何人都可以帮助我将AsyncTask更改为@Background和@UiThread吗? 我应该怎么开始?我该删除什么? onPost和onPre应该转换为UiThread吗? 我将非常感谢您的建议
这是我的代码。
@Click
void button1(View view)
{
ReadPic rp = new ReadPic();
rp.execute();
}
class ReadPic extends AsyncTask<Void, Void, Void>
{
ProgressBar progressBar;
boolean sukces = true;
public ReadPic()
{
progressBar = new ProgressBar(getBaseContext());
}
@Override
protected Void doInBackground(Void... arg0)
{
URL u;
InputStream is;
try
{
u = new URL( adres);
is = u.openStream();
Bitmap temp = BitmapFactory.decodeStream(is);
bmp=temp.copy(Bitmap.Config.ARGB_8888, true);
}
catch( Exception e)
{
sukces = false;
}
return null;
}
@Override
protected void onPreExecute()
{
if(progressBar !=null)
progressBar.setVisibility(ProgressBar.VISIBLE);
button1.setEnabled(false);
if(progressBar !=null)
progressBar.setVisibility(ProgressBar.INVISIBLE);
textView1.setText("DOWNLOADING...");
super.onPreExecute();
}
@Override
protected void onPostExecute(Void result)
{
if(sukces)
{
imageView.setImageBitmap(bmp);
imageView1.setImageBitmap(bmp);
imageView2.setImageBitmap(bmp);
imageView3.setImageBitmap(bmp);
imageView4.setImageBitmap(bmp);
imageView5.setImageBitmap(bmp);
imageView6.setImageBitmap(bmp);
imageView7.setImageBitmap(bmp);
imageView8.setImageBitmap(bmp);
textView1.setText("Downloading finished");
}
else
{
textView1.setText("Error when downloading");
}
button1.setEnabled(true);
progressBar.setVisibility(ProgressBar.INVISIBLE);
super.onPostExecute(result);
}
答案 0 :(得分:0)
你可以像这样转换它:
@Click
void button1(View view) {
startProcess();
}
void startProcess() {
if(progressBar !=null) // progressBar should be a field in your Activity / Fragment
progressBar.setVisibility(ProgressBar.VISIBLE);
button1.setEnabled(false);
if(progressBar !=null)
progressBar.setVisibility(ProgressBar.INVISIBLE);
textView1.setText("DOWNLOADING...");
yourBackgroundMethod();
}
@Background
void yourBackgroundMethod() {
URL u;
InputStream is;
try
{
u = new URL( adres);
is = u.openStream();
Bitmap temp = BitmapFactory.decodeStream(is);
bmp=temp.copy(Bitmap.Config.ARGB_8888, true);
onBackgroundSuccess();
onBackgroundTerminate();
}
catch( Exception e)
{
onBackgroundError();
onBackgroundTerminate();
}
}
@UiThread
void onBackgroundError() {
imageView.setImageBitmap(bmp);
imageView1.setImageBitmap(bmp);
imageView2.setImageBitmap(bmp);
imageView3.setImageBitmap(bmp);
imageView4.setImageBitmap(bmp);
imageView5.setImageBitmap(bmp);
imageView6.setImageBitmap(bmp);
imageView7.setImageBitmap(bmp);
imageView8.setImageBitmap(bmp);
textView1.setText("Downloading finished");
}
@UiThread
void onBackgroundSuccess() {
textView1.setText("Error when downloading");
}
@UiThread
void onBackgroundTerminate() {
button1.setEnabled(true);
progressBar.setVisibility(ProgressBar.INVISIBLE);
}