I have some code that will not run if I don't have a breakpoint. My speculation is that the code gets executed too quickly, and the time between me allowing a breakpoint to continue lets a thread lock on to my code. It also doesn't get "caught" with my exception handling, so its not bad code, but when the breakpoint is there it will dive into the try further and do everything I want it to do
not sure how to get this to work without being in debug mode! I am considering wait() or sleep() functions but it seems like a silly workaround, let me know if there is a better way
Thread triggerService = new Thread(new Runnable(){
public void run(){
Looper.prepare();
try{
// ....... code here does not get executed
// such as if statements or anything
Looper.loop();
}catch(Exception ex){
System.out.println("Exception in triggerService Thread -- "+ex);
}//end catch
}//end run
}, "myNewThread");
triggerService.start();
Insight appreciated!
Code works fine for me. Is there any other code in you program? Have you inserted debug output? You could test if the run() method is executed.
Related
I try to play some music for my activity but "sometimes" it throws exceptions below :
android.os.DeadObjectException: Transaction failed on small parcel; remote process probably died
This is my code that might be related on this error.
...
Thread thread = new Thread(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bgm.start();
});
thread.start();
...
This code is in onCreate method and rest part is just make some animations with Handler or get 3 String intent values and five int intent values from previous activity.
It doesn't even tell me which line of my code it happened.
Thanks for reading my question.
Possible Solutions:
Override your service's onDestroy() method and watch what event flow leads to it. If you catch DeadObjectException without going through this method, your service should have been killed by the OS.
by removing Typeface, this might be because of ttf which I was using from the assets folder Please try comment the typeface and test it hope it will work for sure
put all your code inside the onCreate. From there you will see what is the culprit like a NullPointerException for example but your code will run smoothly already.
DeadObjectException: The object you are calling has died, because its
hosting process no longer exists.
This is my first Android application and I am finding troubles with while loop, I am trying to use a while loop on my Android application but the application freezes.
What I'm trying to do is track the user location (using onlocationChanged) and keep querying on the location until the query returns a result. It's a GIS application so I am going to describe the application behavior:
the application keeps tracking the user position using a listener "onLocationChangedListener" and store it in a variable "myPosition". I am using a boolean"noResults=true". I will use a method "query(myPosition)" in the while loop, this method has a callback that when a result is found, and changes a boolean "noResults" to false. the loop will keep on until "noResults" is false (that means query's callback changed the boolean's value)
, here's what I did:
while(noResults)
{
//myPosition keeps changing
query(myPosition);
//query has a callback that when a result is found it changes noResults to false
}
I resolved the problem using a "Handler" that query the Feature Layer every 5 seconds, this stops the main thread from generating application not responding error:
Handler m_handler=new Handler();
Runnable m_runnable;
m_runnable = new Runnable(){
public void run() {
//query code here
m_handler.postDelayed(m_runnable, 5000);
}
};
m_handler.postDelayed(m_runnable, 0);
running while loop codes on the main thread freezes the UI, and makes all other processes pause making your app unresponsive use
Threads..
also note that the while loop you are running is running on a default Thread termed as the ui thread so in short run while loops on separate threads..
eg..
new Thread(new Runnable() {
#Override
public void run() {
// Your hard while loop here
//get whatever you want and update your ui with ui communication methods.
}
).start();
for ui communicating methods
View.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "updated ui", Toast.LENGTH_LONG).show();
}
});
the view could be any views you are updating..
also like #TehCoder said you could use asynctask but asynctask is not meant for long workaflow work there are 3 of them but i can't recall the last one
Maybe you should use an AsyncTask? I'm not quite sure what your problem is tho.
Loop is not a problem in android (or any language).
There are two scenario might be reason for your freezing,
If you run network call in api, android throw error and crashes. You have to do network related calls in Aysnc Task ot threading
Use try throw catch and exception cases to avoid app crashing and better coding skill.
There are many previous questions regarding the android.os.NetworkOnMainThreadException exception , which is essentially a protective approach by android to prevent us from freezing UI.
Opening a socket from another thread (hence, not the MainThread) should solve this issue:
Thread t = new Thread (new Runnable() {
#Override
public void run() {
try{
Socket socket = new Socket ( SOME_IP_AS_STRING , SOME_PORT_AS_INT);
// do some IO with socket
}
catch (Exception e) {}
}
});
t.run();
However, this code throws the mentioned exception - android.os.NetworkOnMainThreadException,
and when debugging (using the Android Studio), it looks like run() is running under the MainThread after all, which makes no sense.
where do I got it wrong?
You're calling .run() which actually will run the Thread in your main UI Thread. You need to call .start() instead to avoid it.
The exception that is thrown when an application attempts to perform a networking operation on its main thread. Try to run your code in AsyncTask , For more detail refer here
I have been tracing down a problem where a block of my code just stops working. At long last, I identified the line, as seen below:
Log.v(TAG,"Here");
tv.setText("");
Log.v(TAG,"There");
During the time that blocks, the first statement gets called, the second one doesn't. Any idea what could be causing this?
In case there's any doubt, tv is a TextView. There is no errors printed out, and in fact, this line worked once previously...
I figured out what my problem was, I'm posting the answer here to help anyone out in the future. It might be an Android bug, or something odd... No error was ever posted. Bottom line is, don't make GUI calls in a ScheduledThreadPoolExecutor.
ScheduledThreadPoolExecutor masterExecutor;
masterExecutor=new ScheduledThreadPoolExecutor(1);
masterExecutor.schedule(new Runnable(){
#Override
public void run() {
//Formerly, I ran the block of code here, that blocked.
runOnUiThread ( new Runnable()
{
#Override
public void run() {
//Now I moved the code inside of a runOnUiThread
}
});
}
},1000,TimeUnit.MILLISECONDS);
Let's say in various points in my application, I create and fire off a new runnable like so:
new Thread(new Runnable() {
public void run() {
while(true) {
//do lots of stuff
//draw lots of stuff on screen, have a good ol time
//total loop processing time abt 1250-1500ms
//check for conditions to stop the loop, break;
} } }
Now, is there any way to terminate that thread midway through execution other than break; inside my while loop? I'd like to be able to kill it specifically and immediately from the parent thread, like, as in the event that the user just requested to load a different map. It feels clunky to insert an if (stopFlag) break; (set in parent thread) after every 5 or so lines of code.
I peeked at Runnable's and Thread's methods and I just can't see it. Someone know an awesome trick?
You may use AsyncTask and call cancel to cancel the thread.
Instead of while (true) you may check for a condition or a flag that would be changed properly when the Thread/Runnable should be stopped. This seems to be the suggested strategy since Thread.stop() has been deprecated.
You could use AsyncTask as suggested, which probably works best in this case. I believe you can also use the interrupt() method, which is preferred if good if you're not in Android, but still suffers from having to explicitly check if it is interrupted:
Thread t = new Thread(new Runnable() {
public void run() {
while (true) {
// do some stuff
if (isInterrupted()) {
break;
}
}
});
t.start();
// Whoa! Need to stop that work!
t.interrupt();