ANR timeout too long - android

I think I'm being a bit daft here, but I don't understand why I'm getting faulty ANR timeout values.
Example one:
public void onClick(View v) {
while(true);
}
I run this code and trigger a touch event on another view. I will get the ANR after ten seconds, whereas I expected five seconds.
Example two:
public void onClick(View v) {
try {
Thread.sleep(60*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Again, I run the code and trigger a touch event. This time I will not get an ANR at all.
Any ideas of what is going on?

Related

How do i add a delay to program before running selection query to avoid bind value being null?

I keep getting an illegal argument exception when running my app. However, this happens prior to the Toast messages coming up and that's why I think I need a delay.
Prior to adding on the DatabaseHelper class, my app was running and the proper value was coming up on both Toast messages, the one in the MainActivity and the one showing the intent value passed in the DisplayResult activity.
I'm not sure what to do at this point.
Just do a thread sleep in a runnable.
int timeYouWantToSleep = 60000;
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(timeYouWantToSleep);
//do your work here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
If this doesn't work, you know it's not a delay that you need.

Thread.sleep() inside android application [duplicate]

I'm working on a memory game for Android and I'm having a problem. When the user taps the second image - if the images are not the same I want the second image to show for 1, 2 seconds.
What I've tried is to sleep for 1-2 sec. the UI thread after the second image is activated - but this doesn't seem to work - the second image doesn't seem to show! (only the first images is showed)
Here's my code:
public void whenTapedImage(View v, int position)
{
i++;
ImageView imgV=(ImageView)v;
if(i%2!=0)
{
firstClick=position;
imgV.setImageResource(im.images.get(firstClick));
}
else
{
secondClick=position;
imgV.setImageResource(im.images.get(secondClick));
try {
Thread.currentThread().sleep(1000);
if(!(im.images.get(firstClick).equals(im.images.get(secondClick))))
{
Toast.makeText(easyGame.this, "Try Again!", Toast.LENGTH_SHORT).show();
im.notifyDataSetChanged();
gridview.setAdapter(im);
gridview.invalidate();
aux=player1Turn;
player1Turn=player2Turn;
player2Turn=aux;
}
else{
done=done+2;
ImageAdapter.keepVisibleViews.add(firstClick);
ImageAdapter.keepVisibleViews.add(secondClick);
if(player1Turn==true)
{
player1Score++;
String score=Integer.toString(player1Score);
score1.setText(score);
}
if(player2Turn==true)
{
player2Score++;
String score=Integer.toString(player2Score);
score2.setText(score);
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
What am I doing wrong?
You must not sleep the UI thread as this would prevent android from delivering any other events to your activity's UI.
Instead, do something such as use a timer and have the timer's method use the run on ui thread facility to make the desired postponed change.
For robustness you may need to implement a state machine (either formally, or in effect) to keep track of what is supposed to be happening - you'll need to decide if the current delay should be aborted or enforced if another button is pushed, and make the state machine treat that appropriately.
This is similar to Waiting in android app
Try following the solution posted there and use the Timer Class

Timers accuracy

I am using this library to establish a connection and data transfer between two android devices. what i want to do is: one phone send the same message every 2 seconds, everytime the receiver reads the message, it starts some work..
I tried doing that with Timers and TimerTasks, but it is not synchronized at all. i get weird different delays.
public void onClick(View v){
new Timer().schedule(new TimerTask()
{
public void run()
{
bt.send("Start");//////////////////////////////////////////////////////
Log.i("time", "data sent "+System.nanoTime());
}
try {
Thread.currentThread();
Thread.sleep(50, 0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
s.playSound();
//
}
}
, 0, 3000);
and also sleep() is not a good way to produce delays, because sometimes its interrupted.
Is there any other way to do that?

Count time(seconds) the button remained clicked in Android

I want to make a program which will tell me the number of seconds I kept holding the button.
for example if I clicked the button for 5 seconds, it should tell me the button remained pressed for 5 seconds.
is this achievable in android?
This is how I tried, didn't work because when I put the while loop in, the button stays clicked even I press it for just one second. The program doesn't crash but the button remains clicked and I think it freezes.
thread = new HandlerThread("");
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
while(btn.isPressed())
{
try {
thread.sleep(1000);
total = total++;
temp = temp++;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Toast.makeText(MainActivity.this, ""+temp+" "+total, 0).show();
}
});
You could use time stamps, and an OnTouchListener to achieve this.
When your OnTouchListener receives an ACTION_DOWN event, store the first time stamp. When it receives an ACTION_UP event, store the second time stamp and calculate the difference between the two.
As mentioned by Raghunandan, you should never block on the UI thread using calls such as thread.sleep, as this will cause the UI to stop responding, and in some cases can cause the program to be killed because of this.
Here is an example of what I've outlined above. Please note, this code was written from memory, and has not been tested, but you should get the general gist of it.
btn.setOnTouchListener(new OnTouchListener() {
private long firstTouchTS = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN) {
this.firstTouchTS = System.currentTimeMillis();
} else if (event.getaction()==MotionEvent.ACTION_UP) {
Toast.makeText(MainActivity.this,((System.currentTimeMillis()-this.firstTouchTS)/1000)+" seconds",0).show();
}
}
});
References: OnTouchListener MotionEvent
thread.sleep(1000);
Calling sleep on the ui thread hence it freezes. Do not call sleep on the ui thread. It blocks the ui thread.
Read
http://developer.android.com/training/articles/perf-anr.html.
Use a Handler if you want to repeat some task

Android - two actions in app at the same time

I am developing app and I need that my app will be doing two actions at the same time. For example - I can drag marker and the map will be scrolling at the same time.
I tried to update map while dragging marker, everything would be okay, except thing that when thread starts, maps starts scrolling continuously and I cand do anything more. Here is the code, I call it in onCreate() method. I tried to do Runnable and AsyncTask and the results were the same. Any suggestions?
private void update() {
new Thread() {
public void run() {
while (true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
while (drag)
mMap.animateCamera(CameraUpdateFactory.scrollBy(10, 0), 2, null);
}
});
try {
Thread.sleep(2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
You don't have the code to interrupt your thread. That's why your map keep scrolling. Try to use drag event to drive this animation, and add some code to terminate the thread at some point.

Categories

Resources