我为计划的 ui 上的动画更改图像创建了一个线程。按钮单击时会中断,并设置固定图像。但是如果runOnUiThread 中的setImage 在onClick 中的setImage 之后不小心发生了,那就是错误的图像。
这段代码中是否有任何方法可以确保在从 InterruptedException 返回后通过某个地方。(我不想在 ui 线程上有更多延迟)
请帮忙谢谢!
thread = new Thread(){
@Override
public void run() {
while(!this.isInterrupted()){
for(int i=0; i<imageList.size(); i++){
if(getActivity()==null) return;
getActivity().runOnUiThread(new Runnable() {
public void run() {
ImageViewAnimatedChange(getActivity().getApplication(),
imgFunction, imageList.get(j), 0);
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Log.e(TAG, e.toString());
return;
}
}
}
}
};
//一次点击
if(thread!=null) {
thread.interrupt(); // catch interruptException
thread = null;
imgFunction.setImageResource(R.drawable.selector);
}
编辑:我按照建议重写了这部分。
public class asyncTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... params) {
Log.d(TAG, "doInBackground");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Log.w(TAG, e.toString());
return null;
}
final List<Bitmap> imageList = getImageList();
if(imageList.isEmpty()) return null;
Log.d(TAG, "start while ");
while(!isCancelled()){
Log.d(TAG, "while:" +Boolean.toString(isCancelled()));
for(int i=0; i<imageList.size()+1; i++){
final int j=i;
Log.d(TAG, "for" + Integer.toString(j));
if (j == imageList.size())
publishProgress(“ok”);
else
publishProgress(Integer.toString(i));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Log.w(TAG, e.toString());
return null;
}
}
}
Log.d(TAG, "while end");
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
QUtil.logE(TAG, "onPostExecute");
imgFunction.setImageResource(R.drawable.selector);
}
@Override
protected void onProgressUpdate(String... value) {
super.onProgressUpdate(value);
Log.d(TAG, "onProgressUpdate" + value[0]);
if(getActivity()==null || isCancelled()) return;
if(value[0]==“ok”)
ImageViewAnimatedChange(getActivity().getApplication(),
imgFunction, null, R.drawable.selector);
else
ImageViewAnimatedChange(getActivity().getApplication(),
imgFunction, getImageList().get(Integer.parseInt(value[0])), 0);
}
@Override
protected void onCancelled() {
super.onCancelled();
Log.e(TAG, "onCancelled");
try {
Thread.sleep(60);
} catch (InterruptedException e) {
Log.w(TAG, e.toString());
}
imgFunction.setImageResource(R.drawable.selector);
}
}
//开始
iftttAsyncTask = new IftttAsyncTask().execute("");
// 结束点击
if(asyncTask!=null) {
asyncTask.cancel(true); // catch interruptException
threadIfttt = null;
}
然后有时工作有时不工作,当“doInBackground”不在睡眠时不工作!它确实进入了 onCancel 但并没有真正取消,我用 isCanceled() 得到了错误记录图片如下