Reputation: 933
My app has a screen that refreshes every second in AsyncTask:
class BarRefresh extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
// doSomething();
while(redraw){
for(int i = 0; i < c.sets.size(); i++)
{
vals[i] = c.sets.get(i).getLast();
}
graph.updateVals(vals);
graph.postInvalidate();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(isCancelled()){
break;
}
}
return null;
}
}
A click on one of the objects opens a new activity with a parameter:
@Override
public boolean onTouch(View v, MotionEvent ev) {
// TODO Auto-generated method stub
float[] coords = new float[2];
coords[0] = ev.getX();
coords[1] = ev.getY();
int set = 0;
for(int i = 0; i < graph.values.length; i++){
if(graph.rects[i].contains(coords[0], coords[1]))
{
redraw = false;
Bundle chosen = new Bundle();
chosen.putInt("set", i);
Intent bb = new Intent(GraphTestActivity.this, LineGraphActivity.class);
bb.putExtras(chosen);
startActivity(bb);
// set = i;
}
}
//Toast t = Toast.makeText(GraphTestActivity.this, "KLIKNIETO " + set, Toast.LENGTH_SHORT);
//t.show();
return false;
}
In the new activity constructor looks like that:
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle pick = getIntent().getExtras();
setNr = pick.getInt("set");
c = Common.getInstance();
set = c.sets.get(setNr);
graph = new LineGraph(LineGraphActivity.this, set);
setContentView(graph);
}
Here is where things get weird. On the emulator everything works fine (app is on 2.1 API, so is the emulator), but when I load it up on my phone, five or more instances of the second activity open at the same time and I have to press back button multiple times to go back to the original screen.
My phone is Samsung i5700 Spica with And 2.3.7 (Cyanogen 7.2 NIGHTLY alpha)
Upvotes: 1
Views: 1384
Reputation: 22637
You are probably getting multiple onTouch()
events. Verify this through the debugger. on the emulator it's quite boolean, but on a real touch screen in the micro seconds as your finger is coming in contact with the screen you can receive multiple touch events.
If you can use a higher-level function like onClick
instead of onTouch
, do that. If you can't you need to keep track of the touch down and touch up events and only react to down if it wasn't already down.
A hack would be to define your activity as single instance, then you won't get multiple instances. This is almost certainly not the right thing to do though.
As a side note, putting Thread.sleep()
in your code almost always indicates a lurking bug, and that the code is written incorrectly. If you need something to happen at a later point in your code, use Handler.postDelayed()
or a Timer
.
Upvotes: 1