Further to my post Android: How to avoid errors on unlockCanvasAndPost method? I faced with a strange behaviour. I looked at the shared variable to use with the different threads. And by being happy I have used the solution proposed by @user1031431 in the focused-on-Java post Sharing a variable between multiple different threads. But nothing occured and the new values of the variable are stayed invisible for any non-main thread.
I tried the following:
public class MyMainThread extends WallpaperService{
....
class MyEngine extends Engine implements OnSharedPreferenceChangeListener{
...
private final Paint mPaint = new Paint();
private final GestureDetector doubleTap;
...
private MyThread myThread = null;
...
WallpaperEngine() {
....
doubleTap = new GestureDetector(MyMainThread.this,
new SimpleOnGestureListener() {
@Override
public boolean onDoubleTap(MotionEvent e) {
if (mTouchEvents) {
if(myThread!=null){
control.myStopAnimationFlag = 1;
}
return true;
}
return false;
}
});
....
}
...
class Control {
public volatile int myStopAnimationFlag = 0;
}
final Control control = new Control();
...
onSurfaceCreated(SurfaceHolder holder)
{
...
MyThread myThread = new MyThread(holder, mPaint);
myThread.start();
...
}
...
class MyThread extends Thread{
private SurfaceHolder mHolder;
private Paint _paint;
...
private final Handler mThreadHandler = new Handler(){
public void handleMessage(android.os.Message msg){ };
};
private final Runnable mThreadWorker = new Runnable() {
public void run() {
if (mDuration > 0)
{
control.myStopAnimationFlag = 0;
DrawFunction();
}
}
};
void MyThread(SurfaceHolder holder, Paint paint){
mHolder = holder;
_paint = paint;
}
run(){
DrawFunction();
}
...
DrawFunction(){
...
StartAnimation();
...
mThreadHandler.removeCallbacks(mThreadWorker);
if (mVisible) {
mThreadHandler.postDelayed(mThreadWorker, 1000 / 2);
}
}
StartAnimation(){
...
while(...){
if(myStopAnimationFlag==0){
// draw algorithm here
}
else break;
}
...
}
}
}
....
}
In this code the lines with setting and checking the variable myStopAnimationFlag work unexpectedly. For example, if I produce the double tap during the animation (proceeded by cycle while(...)) the variable myStopAnimationFlag still is assigned to love and in double tap event handler I set it to 1. But I expect that after changing this variable in main thread it will be done for another thread too.
Also I tried to define a variable myStopAnimationFlag as static. But that nothing gave me again.
So I wait for advice to make it comes true.
Thanks in advance for giving me chance:)