Android - Forcing ANR for testing purpose - android

Why i can't force Android ANR with this code?
No log messages or pop up. The application is just launched lazily.
[UPDATE]
I can't get it even sleeping a View.setOnClickListener or BroadcastReceiver.onReceive!
Is there a trick?
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Log.e("Test", "", e);
}
}
}
I'm using Samsung GT-6200L with stock Android 3.2

Try it in onTouchEvent. In onCreate your activity is not fully running
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.d(TAG,"onTouchEvent");
while(true) {}
}

The ANR-WatchDog project has a test app that produces ANRs in a reliable manner (as reliable as ANRs can be): the app hangs because of a deadlock.
The gist of it:
Prepare a lock object as a private field in your activity:
final Object mutex = new Object();
Have a thread that performs some work in a critical section, and an android.os.Handler that posts work depending on the same lock.
new Thread(new Runnable() {
#Override
public void run() {
synchronized (mutex) {
while (true) {
try {
Thread.sleep(60000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
synchronized (mutex) {
// Shouldn't happen
throw new IllegalStateException();
}
}
}, 1000);
Putting the above code snippet inside a button click handler, for example, should do the trick.

I've been facing the same issue yesterday, and I've found out that using a plain debug build ANR dialogs simply won't show up. (Although the UI thread was completely hanged.)
But after exporting and properly signing the application the dialogs were popped up properly (in every cases mentioned above). However I am still not sure what really prevents to pop up ANR messages, maybe someone else can clarify this later...

Try using:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int a=0;
while(true) {
a++;
}
}
Your code probably didn't work because it got setup too early, and the Activity probably wasn't fully initialized and created yet. With the above code, launch the activity and touch/swipe on the screen and wait for the ANR dialog to popup.

Make a button in your activity.
public void onBtn1(View v) {
int a = 0;
while(true) {
a++;
}
}
Make the button execute the above code.
Spam click the button with your finger =)

I used this code for force ANR
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void force(View view){
while(true) {}
}
I just created a simple button in the xml file and set android:onClick=force

Related

Can Android kill my app while it is in the middle of a loop execution?

When Android decides to remove an application from the stack in order to free up some RAM, what happens if the application that is being destroyed is currently running some loop in the background? Will the loop be terminated amid execution or will the VM wait for it to finish?
Will the loop be terminated amid execution or will the VM wait for it to finish?
The loop is terminated, otherwise it isn't quite "killing".
Simple test:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
#Override
public void run() {
try {
while (true) {
Log.i("LOOP", "Running");
Thread.sleep(1000);
}
} catch (InterruptedException e) {}
}
}).start();
}
}
Swipe the app out from the recent apps.

Android app forced to close on background colour change?

so I am building an experiment app where the background will change colour at random intervals.
I am stuck on the background change.
I have working code that changes the background colour, but when I put it in a thread/ try and catch bracket, the application is forced to close and doesnt give me an error?
Here is the code that works when used in the oncreate method:
View view = this.getWindow().getDecorView();
view.setBackgroundColor(Color.RED);
But when I want to make it "sleep" for 1 second and then change it to red, it bombs out.
Please note that this method is a separate method from the oncreate and is called from within there and will not work for some reason?
public void changeBackground(final View v){
Thread timer = new Thread(){
public void run(){
try{
sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}finally{
v.setBackgroundColor(Color.RED);
}
}
};
timer.start();
}
What am I doing wrong?
What I need:
when the app starts, it must wait for 1 second and then change the background colour without it bombing out.
Thanks in advance!
You cannot access UI thread from your custom thread. You have to run your runnable in UI thread. Change your changeBackground method to the following,
public void changeBackground(final View v) {
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
v.setBackgroundColor(Color.RED);
}
}
};
this.runOnUiThread(timer);
}
Or you can use Asynctask, this handles that issue for you. Here, and here.
Manipulate view state on UI thread:
v.post(new Runnable() {
#Override
public void run() {
v.setBackgroundColor(Color.RED);
}
});
More about it: http://developer.android.com/guide/components/processes-and-threads.html
UI operations can't be done in a Thread
v.setBackgroundColor(Color.RED);
Remove above line from finally and Use a runOnUIthread() to update UI in Finally.
and your final code will look like this
public void changeBackground(final View v){
Thread timer = new Thread(){
public void run(){
try{
sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}finally{
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
v.setBackgroundColor(Color.RED);
}
});
}
}
};
timer.start();
}
Solutions to fix this issue:-
Update you App
Clear Gmail Storage Data
Clear App Cache and Data
Reset App Preferences
Reset Smartphone Factory Settings
I found these steps with the help of YouTube.
Here is that link:-
youtube.com/watch?v=fx8Fv8RXag8

calling an activity without any click event - android

Iam an newbie to android.I don't know whether this question may sound silly but i didn't find any solution.Please bare me. I had created an application which will first loads the app logo. I need to call another activity after this without using any click event.can anybody help me out wit this? and also i need to know in windows we can place panels over another panel. Can we do the same ting android? If yes how can i achieve that? I know that in a layout we have to place views but my questions is can we design view over another view so that i can hide and show views whenever needed?
Thanks in advance
Using Timers or Threads is a horrible way to do this, you are inviting memory leaks into your app. Use Android's Handler instead:
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
// create Intent for next activity and call startActivity with it
}
}, 2000);
If you have a reference to your content view, use contentView.getHandler() instead of creating a new one.
By the way, if this is for a personal project, consider NOT USING SPLASH SCREENS
You do not really provide enough information to give you a proper answer, but this will start a timer and when 5000 milliseconds has elapsed it will switch to another activity:
public class SplashActivity extends Activity {
private Timer t;
public void onCreate(Bundle b) {
super.onCreate(b);
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this, NextActivity.class);
startActivity(i);
}
}, 5000);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
Thread timer = new Thread() {
public void run() {
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent intent = new Intent();
intent.setClass(WelcomePage.this, HomePage.class);
startActivity(intent);
}
}
};
timer.start();
}
that should do the trick my friend!!

Android - Why second thread halts execution of the first one?

I have an app that runs 2 threads in loops. 1st one is updating a graph in 1s interval and the second one is updating another graph at 60s interval. The second task is taking a long time since it is quering some server in the internet 3 times that might not always be available and even if it is it will take up to 5-7s to execute.
What is happening is when I launch the second thread it will pause execution of the first one and that is not what I want, I wish both run concurrently. Here in the Youtube video you can see the results of the app running. http://youtu.be/l7K5zSWzlxI
"thread_updater1s" is running a green graph, large readout, and a timer in the corner so you clearly see it stalls for 11 seconds.
1)First of all why is that happening? how to fix it?
2)I'm aware that I might not launch the threads properly at all. I had hard time understanding how to make something to run in a interval loop in Java and my code worked fine for one graph/tread. Now when I have 2 loops in separate threads I don't know why they are not executing concurrently.
Here is the code:
public class LoopExampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
thread_updater1s.start();
thread_updater2.start();
}// end of onCreate
final Runnable r1s = new Runnable() {
public void run() {
do_1s_updates(); // those are very quick http calls to the local API server
} // to get data nessessary for some plot.
// They have 1s timeout as well but rarely timeout
};
final Runnable r2 = new Runnable() {
public void run() {
do_large_updates(); //This makes 7 long call over the Internet to the slow https
//server once every 60s. Has 10s timeout and sometimes takes as much as
//7s to execute
}
};
Thread thread_updater1s = new Thread() {
#Override
public void run() {
try {
while (true) {
handler.post(r1s);
sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread_updater2 = new Thread() {
#Override
public void run() {
try {
while (true) {
handler2.post(r2);
sleep(60000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
PS. please be forgiving and informative I only code Java for 15 days so far with absolutely no prior experince or lesson.
You need to make the http requests in the threads (not the posted runnables). Then, when you have the data downloaded, you create a runnable with that data that will update the graph and post that runnable to be executed by the UI thread. Here is an example:
public class LoopExampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
thread_updater1s.start();
thread_updater2.start();
}// end of onCreate
Thread thread_updater1s = new Thread() {
#Override
public void run() {
try {
while (true) {
final Object data = getDataFromServer1();
handler.post(new Runnable() {
#Override
public void run() {
updateGraph1(data);
}
);
sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread_updater2 = new Thread() {
#Override
public void run() {
try {
while (true) {
final Object data = getDataFromServer2();
handler.post(new Runnable() {
#Override
public void run() {
updateGraph2(data);
}
);
sleep(60000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Obviously, change that final Object data by the appropriate class that represents your data downloaded.
handler.post pushes the runnable onto the main (UI) thread's message queue for execution on the main thread.
So what you're doing is every sleep interval, you're sending a message to the main thread to run the function. Clearly, the main thread can't run 2 things at once, so that's why one runnable is delayed for the next one.
You probably want to do the work of the runnable in the separate threads - why did you start using a handler? What happens if you call do_1s_updates and do_large_updates directly instead of through the handler & runnable?

how to do dynamic loading in android?

i have an rss feed that comes via an XML. There are several events that are returned with information about them. The events are returned with tags...for eg: ....info...
as soon as i encounter tag, i want to update the listview that i am using to show the events.
So the user does not see the loading progress dialog, rather he sees the events getting added to a list.
How do i do this.
thank you in advance.
Here's pseudo codeish example for one way of doing this using SAX parser;
// MyParserThread is assumed to be inner class of Activity here.
private class MyParserThread extends Thread implements MyParserObserver {
private MyParser mParser;
public MyParserThread() {
mParser = new MyParser();
mParser.setObserver(this);
}
public void run() {
try {
// load xml
mParser.parse(xml);
} catch (Exception ex) {
}
}
public void onMyParserEvent(final DataReceivedFromParsing data) {
runOnUiThread(new Runnable() {
public void run() {
// update data to your UI.
}
});
}
public void cancel() {
mParser.cancel();
}
}
And in your parser you're implementing ContentHandler
public void cancel() {
mCancelled = true;
}
public void startElement(....) {
if (mCancelled) {
// If you want to stop Thread from running, all you have to do
// is make parsing stop.
throw new SAXException("Cancelled");
}
....
}
And triggering parsing once your onCreate is called would be;
public void onCreate(...) {
...
mParserThread = new MyParserThread();
mParserThread.start();
...
}
Now this isn't perfect but hopefully gives some idea how to do Thread handling for this purpose. Fundamentally you just have start it, and adding 'cancel' functionality is somewhat more of a bonus - e.g. for cases in which Activity is destroyed while your Thread is running.

Categories

Resources