Access a thread to notify it from another method (Android application) - java

I'm developping an android application and trying to deal with threads without really knowing a lot about them... (Yeah bit stupid of me, I know)
I'll try to explain it properly and quite quickly.
In the onCreate method of my activity, I'm calling an AlertDialog to make the user choose to either load data from the internet or directly access the application using the data previously stored in database.
For that, in the onCreate, I call my method to raise the AlertDialog, positive button should start the worker thread to download, and negative button should call intent to move to next activity. So far, I got this :
by not calling wait() anywhere, my AlertDialog appears but the thread starts anyway
by calling wait() at the first line of my thread, I have to declare it static to access it from the listeners of my AlertDialog and be able to notify() it or interrupt(), I receive the error: object not locked by thread before wait().
worker = new Thread(new Runnable() {
public void run() {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
[rest of my run method]
private void miseAJourDesDonnes() {
confirmInscrip = new AlertDialog.Builder(this).setMessage(
"Voulez-vous mettre à jour l'intégralité des données de l'application? (Connexion internet requise").setPositiveButton("Mettre à jour",
okListener).setNegativeButton("Continuer sans", nonListener);
confirmInscrip.create();
confirmInscrip.show();
}
OnClickListener okListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(AccueilSplash.this, "Mise à jour en cours", Toast.LENGTH_SHORT).show();
worker.notify();
return;
}
};
OnClickListener nonListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(AccueilSplash.this, "Accès direct à l'application", Toast.LENGTH_SHORT).show();
worker.interrupt();
Intent entre = new Intent(AccueilSplash.this, Androt.class);
startActivity(entre);
}
};
worker is my instance of Thread (the bbackground one)
Am I just being dumb or Is there a subtility I havent grasped?
thanks for any answer...

Below is a quick explanation of how wait() and notify() works but might I suggest that you just don't create the worker thread unless the user clicks ok? You may still want to cancel the thread later if they want to stop the download but creating the thread before you even know if it going to be used doesn't seem like the best approach.
In order to call wait(), notify(), or notifyAll() on an object you must first own the monitor of the object you wish to call the method on, so in you case within the runnable this would be how you would need to do it:
Runnable runnable = new Runnable() {
public void run() {
// wait(); This call wouldn't work
syncronized (this) {
wait(); // This call will work
}
}
};
To notify that runnable you would also have to have the monitor
// runnable.notifyAll(); this call will not work
syncronized (runnable) {
runnable.notifyAll(); // this call will work
}
For more information about threads and concurrency in Java I would suggest Java Concurrency in Practice
There may be some built in framework for background tasks in Android that I don't know about but using pure java the easiest approach to this seems like it would be something like this:
private Thread downloadThread;
OnClickListener okListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Runnable download = new Runnable() {
public void run() {
// Create your input streams and such
boolean downloadComplete = false;
while(!downloadComplete && !Thread.currentThread().isInterruped()) {
// Do some downloading
}
if (!Thread.currentThread().isInterruped()) {
// Alert user of success.
}
}
};
downloadThread = new Thread(download);
downloadThread.start();
}
};
OnClickListener cancelListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
downloadThread.interrupt();
}
};

I'm new to using threads as well, but you could try reading this example to give you a good starting point. It's about progress dialogs, but it illustrates how to manage threads and start them up at the right time. The really useful code is collapsed under the 'see more about Progress Dialgos with a second Thread' section.
Going to your code, I think your mistake is in how you declare your thread. Try instead creating is as a class extending Thread. e.g.
private class Worker extends Thread{
Handled mHandler; //See the example linked above for how to use handlers
int progress;
//and whatever other variables it might need
worker(Handled h){
mHandler = h;
//and any other initialisation you need
}
public void run(){
//and all your code here
}
}
Then nothing happens with this Thread until you instantiate it with the following, in your onClickListeners.
Worker worker = new Worker(handler)
Even after that it won't actually start until you call worker.start(). Define your handler along the lines of
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
int progress = msg.getData().getInt("progress");
loadingDialog.setProgress(progress);
if (progress >= 100){
dismissDialog(LOADING_DIALOG);
}
}
};
Hope that helps you get started! Do read the link above, as I imagine you'll want some kind of progress dialog as well when it's actually doing the loading from the website. Or perhaps it would be done in a background service, but I couldn't help you with that.

Related

Android Thread Allocation - growing heap?

Hi everyone out there,
i am developing an android application against API 7 at the moment in which i use an activity which need to be restarted. Lets say my activity looks like this:
public class AllocActivity extends Activity implements OnClickListener{
Button but;
private Handler hand = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_alloc);
but = (Button) findViewById(R.id.button);
but.setText("RELOAD");
but.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0){
Intent intent = getIntent();
startActivity(intent);
finish();
}
});
}
#Override
protected void onDestroy(){
super.onDestroy();
System.gc();
}
/****** THREADS AND RUNNABLES ******/
final Runnable fullAnim = new Thread(new Runnable(){
#Override
public void run(){
try{
hand.post(anim1);
Thread.sleep(2000);
hand.post(anim2);
Thread.sleep(1000);
// and so on
}catch(InterruptedException ie){ie.printStackTrace();}
}
});
final Runnable anim1 = new Runnable() {
#Override
public void run(){
// non-static method findViewById
ImageView sky = (ImageView)findViewById(R.id.sky);
}
};
}
The problem is that the gc doesnt seem to free the fullAnim thread so that the heap is growing by ~100K at every restart - till it slows down and crashes. Declaring fullAnim as static does solve this problem - but as i use non static references this doesnt work out for me.
So at this point i am kindof lost - and i hope u can advice me where to go next. Is there something i might be doing wrong or is there a tool i can use to manage threads to drop and free heap after restart.
kindly regards
UPDATE
thanks to everyone who answered - helped alot. using TimerTask did the trick in the end. i did the following change:
/****** THREADS AND RUNNABLES ******/
final TimerTask fullAnim = new TimerTask(){
#Override
public void run(){
try{
hand.post(anim1);
Thread.sleep(2000);
hand.post(anim2);
Thread.sleep(1000);
// and so on
}catch(InterruptedException ie){ie.printStackTrace();}
}
};
as the activity was more than 6k loc long this was a pretty decent solution without facing bigger impacts. KUDOS!
i dont use a Timer to shedule the task - dont know if its bad practice but
the animation is called like this:
Thread t = new Thread(fullAnim);
t.start();
A running Thread is never garbage collected.
A Thread is not stopped automatically if your Activity stops or is destroyed. It could run forever.
Every non-static inner class keeps a reference to the enclosing instance. E.g. hand.post(anim1); works inside that inner class because it has an implicit reference to AllocActivity.this.
So what you effectively do is to keep a reference to your Activity alive for longer than it is supposed to be alive, i.e. until after onDestroy.
Make sure to stop threads manually if you don't want them anymore.
Because final variable have low priority for GC. So you need to explicitly release the runneable objects in onPause() method because there is not ensurence onDestory() will call immediate after finish() call .
#Override
protected void onPause(){
super.onPause();
//cancel timer to stop animations
if(t!=null){
t.cancel();
}
System.gc();
}
UPDATE
use timer to achieve this
boolean isFirstAnim=true;
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
if(isFirstAnim){
// play your first animation at every
}else{
// play your second animation at every
}
}
}, 0, 3000);
What happens when all activities of an application finishes?
"When you call finish() this doesn't mean the Activity instance is
garbage collected. You're telling Android you want to close the
Activity (do not show it anymore). It will still be present until
Android decides to kill the process (and thus terminate the DVM) or
the instance is garbage-collected."
You need to implement your own stop method to stop the running thread, you can make a call to it in onDestroy
refer this Stopping a runnable
Alternatively
you can perform your operation in an asynctask and use onProgressUpdate() to publish progress on UI thread and use cancel(true) in combination with check in doInBackground() whether cancel has been called to stop the task.

Sleep() in Android Java

I am following this tutorial to have a loading screen in my program. The tutorial says my activity should Sleep() using the Sleep() command, however it does not recognize Sleep() as a function and provides me with an error, asking if I would like to create a method called Sleep().
Here is the code sample:
public class LoadingScreenActivity extends Activity {
//Introduce an delay
private final int WAIT_TIME = 2500;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
System.out.println("LoadingScreenActivity screen started");
setContentView(R.layout.loading_screen);
findViewById(R.id.mainSpinner1).setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
//Simulating a long running task
this.Sleep(1000);
System.out.println("Going to Profile Data");
/* Create an Intent that will start the ProfileData-Activity. */
Intent mainIntent = new Intent(LoadingScreenActivity.this,ProfileData.class);
LoadingScreenActivity.this.startActivity(mainIntent);
LoadingScreenActivity.this.finish();
}
}, WAIT_TIME);
}
}
You can use one of the folllowing methods:
Thread.sleep(timeInMills);
or
SystemClock.sleep(timeInMills);
SystemClock.sleep(milliseconds) is a utility function very similar to Thread.sleep(milliseconds), but it ignores InterruptedException. Use this function for delays if you do not use Thread.interrupt(), as it will preserve the interrupted state of the thread.
The function is Thread.sleep(long).
Note, however, that you should not perform a sleep on the UI thread.
The code you posted is horrible. Please don't use that on an actual device. You will get an "Application Not Responding" error if you run something similar to this.
If you're using Handlers, keep in mind that a Handler is created on the thread where it runs. So calling new Handler().post(... on the UI thread will execute the runnable on the UI thread, including this "long running operation". The advantage is that you can create a Handler to the UI Thread which you can use later, as shown below.
To put the long running operation into a background thread, you need to create a Thread around the runnable, as shown below. Now if you want to update the UI once the long running operation is complete, you need to post that to the UI Thread, using a Handler.
Note that this functionality is a perfect fit for an AsyncTask which will make this look a lot cleaner than the pattern below. However, I included this to show how Handlers, Threads and Runnables relate.
public class LoadingScreenActivity extends Activity {
//Introduce a delay
private final int WAIT_TIME = 2500;
private Handler uiHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHandler = new Handler(); // anything posted to this handler will run on the UI Thread
System.out.println("LoadingScreenActivity screen started");
setContentView(R.layout.loading_screen);
findViewById(R.id.mainSpinner1).setVisibility(View.VISIBLE);
Runnable onUi = new Runnable() {
#Override
public void run() {
// this will run on the main UI thread
Intent mainIntent = new Intent(LoadingScreenActivity.this,ProfileData.class);
LoadingScreenActivity.this.startActivity(mainIntent);
LoadingScreenActivity.this.finish();
}
};
Runnable background = new Runnable() {
#Override
public void run() {
// This is the delay
Thread.Sleep( WAIT_TIME );
// This will run on a background thread
//Simulating a long running task
Thread.Sleep(1000);
System.out.println("Going to Profile Data");
uiHandler.post( onUi );
}
};
new Thread( background ).start();
}
use Thread.sleep(1000);
1000 is the number of milliseconds that the program will pause.
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
Keep in mind: Using this code is not recommended, because it is a delay of time but without control and may need more or less time.

Android: Wait() the main thread while a dialog gets input in a separate Thread

I'm writing an activity in Android where the user modifies an SQL Database. The UI consists of an EditText where the user enters the name, and a Seekbar where the user enters how attractive the person is. Underneath there are a bunch of buttons: add, edit, view, delete.
When the user clicks on the "Edit" button, an input dialog is displayed asking the user to input the record number. Once that is done, that record is loaded.
The problem I was having was that the inputdialog would be displayed and while the user entering the record no, the rest of the edit method would carry on so that by the time the user was done entering the input - nothing happened because the function had already been completed.
In order to solve this problem, I decided to use Multi-Threads (which I do not have much experience using). When the edit button is pressed, the main UI Thread is blocked (using wait() - this is because I don't want the UI to be active while the user is entering the record id.) and the input dialog is displayed in a seperate thread.
Once the input has been entered, the thread is notified and the rest of the edit function continues. (The code is below).
The problem is that when I call the wait function on the UI Thread, I get an error that says "object not locked by thread before wait() ". How do I lock the UI Thread?
I know in general one shouldn't block the UI Thread, but I think it's okay in this case because I don't want it to accept any user input.
Thanks for your help.
public class Attractivometer extends Activity implements OnClickListener {
private Button buttonAddRecord, buttonEditRecord, buttonSaveChanges;
private Button buttonDeleteRecord, buttonViewRecord;
private EditText fieldName;
private SeekBar seekbarAttractiveness;
private String inputFromInputDialog=null;
private Thread inputThread;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.Attractivometer);
buttonAddRecord = (Button) findViewById(R.id.buttonAddRecord);
buttonSaveChanges = (Button) findViewById(R.id.buttonSaveChanges);
buttonEditRecord = (Button) findViewById(R.id.buttonEditRecord);
buttonDeleteRecord = (Button) findViewById(R.id.buttonDeleteRecord);
buttonViewRecord = (Button) findViewById(R.id.buttonViewRecord);
fieldName = (EditText) findViewById(R.id.fieldName);
seekbarAttractiveness = (SeekBar) findViewById(R.id.seekbarAttractiveness);
buttonAddRecord.setOnClickListener(this);
buttonSaveChanges.setOnClickListener(this);
buttonEditRecord.setOnClickListener(this);
buttonDeleteRecord.setOnClickListener(this);
buttonViewRecord.setOnClickListener(this);
}
public void onClick(View clickedItem)
{
switch(clickedItem.getId())
{
case R.id.buttonAddRecord:
//.....
break;
case R.id.buttonSaveChanges:
//...
break;
case R.id.buttonEditRecord:
inputThread = new Thread(new Runnable(){
public void run()
{
showInputDialog("Enter Record ID", InputType.TYPE_CLASS_NUMBER);
}
});
inputThread.start();
try {
Thread.currentThread().wait();
} catch (InterruptedException e) {
Log.e("Attractivometer","Main Thread interrupted while waiting");
e.printStackTrace();
}
try {
inputThread.join();
} catch (InterruptedException e) {
Log.e("Attractivometer","Input Thread interrupted while joining");
e.printStackTrace();
}
int recordId = Integer.parseInt(inputFromInputDialog);
if(recordId!=null)
{
AttractivometerSQLHandler AttractivometerDatabaseHandler = new AttractivometerSQLHandler(this);
AttractivometerDatabaseHandler.openDatabase();
String recordName = AttractivometerDatabaseHandler.getName(recordId);
String recordAttractiveness = AttractivometerDatabaseHandler.getAttractiveness(recordId);
if(recordName==null || recordAttractiveness==null )
{
//no record found.
Toast.makeText(this, "No record with that ID found", Toast.LENGTH_SHORT).show();
}else
{
fieldName.setText(recordName);
seekbarAttractiveness.setProgress( Integer.parseInt(recordAttractiveness) );
recordIsOpen(true);
}
AttractivometerDatabaseHandler.closeDatabase();
}else
//No input.
recordIsOpen(false);
break;
case R.id.buttonDeleteRecord:
//...
break;
case R.id.buttonViewRecord:
//....
}
}
private void showInputDialog(String prompt, int inputType)
{
AlertDialog.Builder inputDialog = new AlertDialog.Builder(this);
inputDialog.setTitle("Record No.");
final EditText fieldInput = new EditText(this);
fieldInput.setInputType(inputType);
fieldInput.setHint(prompt);
inputDialog.setView(fieldInput);
inputDialog.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
inputFromInputDialog = fieldInput.getText().toString();
inputThread.notify();
}
});
inputDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
inputFromInputDialog = null;
inputThread.notify();
}
});
inputDialog.show();
}
}
No, no, no! Do not block the UI thread. The system will raise an "Application Not Responding" error. Also, do not try to interact with the user from a non-UI thread.
When the user clicks "edit", don't start the edit method. Just pop up a dialog to collect the required information. Add a DialogInterface.OnClickListener to the positive button and (with the required information now in hand) start the edit method from there.
See the guide topic Dialogs for more information.
First of all, you should not pause the main Thread, because everything will be frozen if you do that, and from an user perspective, that is not good at all.
And second, you should pop up a dialog with 2 buttons, (Done, Cancel) and allow user to go further by pressing one of those buttons. Here you can find out how to display a custom dialog: http://www.helloandroid.com/tutorials/how-display-custom-dialog-your-android-application
First rule of multi-thread programming in Android is that, You should never stop UI thread, and all the long running operations should be made in separate thread. And by long running operations I mean, SQLite database writing/ reading etc.
before invoke wait need get the object lock like this:
synchronized(Thread.currentThread()) { //added
try {
Thread.currentThread().wait();
} catch (InterruptedException e) {
Log.e("Attractivometer","Main Thread interrupted while waiting");
e.printStackTrace();
}
}
but why you want to make main thread wait?

Using a progressdialog and handler

I'm working on an app that connect to a webpage to get some content. I want to show a progressdialog, but I think I'm doing something wrong.
This is my code:
final ProgressDialog myProgressDialog = ProgressDialog.show(WhoisBeyondActivity.this, "Wait...", "Fetching data...", true);
Handler handler=new Handler();
handler.post(new Runnable()
{
public void run()
{
try {
// code to execute
Thread.sleep(2000);
} catch (Exception e) {
}
myProgressDialog.dismiss();
}
});
The problem is that the progressdialog is only shown one second at the end of the operation I want to make. I think the progressdialog is only executing when I execute the dismiss() because it appears and dissapears quickly. Is like the progressdialog appears only to dissapear ... help me please!!! I have read a lot of tutorials, and I have try a lot of option, like THREAD instead of HANDLER, but it is not usefull for me, because I have to edit UI.
There's an excellent example and tutorial here:
http://www.helloandroid.com/tutorials/using-threads-and-progressdialog
That's what I used the first time I did a threaded dialog in Android, and I bookmarked it. Hopefully it helps.
The reason you are getting the described behaviour is that the post method will just execute the passed in runnable against the thread to which the Handler is attached. In your case this is the UI thread.
You are calling ProgressDialog.show(), which is asynchronous. This does not actually show the dialog as soon as the method returns, rather you have just requested that the UI display a dialog. You then immediately post a thread that sleeps for 2 seconds, which is added to the UI queue and blocks the UI from performing the dialog show. The UI then wakes from your sleep, shows the dialog then is dismissed.
You should perform any network operation in either a new Thread or in an AsyncTask. Have a look at these links for more details:
AsyncTask
Painless threading
Threading
Designing for responsiveness
Thread documentation
Handler documentation
You don't want to use a separate thread per-say. What you really want is an AsynTask. This will allow you to create the progress dialog and do the background processing right there in the task. Simple to write and easier to implement. If your refer to the link, what you need is actually really similar to your question. With a little tweaking, it should work just fine for you.
public class HelloActivity extends Activity {
protected static final String TAG = "HelloActivity";
ProgressDialog myProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//
showDialog(1);
final Handler handler=new Handler(){
#Override
public void handleMessage(Message msg) {
//update UI here depending on what message is received.
switch(msg.what){
case 0:
myProgressDialog.dismiss();
}
super.handleMessage(msg);
}
};
Thread t = new Thread(){
public void run(){
try {
// code to execute
Thread.sleep(5000);
} catch (Exception e) {
}
handler.sendEmptyMessage(0);//nothing to send
}
};
t.start();
}
#Override
protected Dialog onCreateDialog(int id) {
myProgressDialog = ProgressDialog.show(HelloActivity.this, "Wait...", "Fetching data...", true);
return myProgressDialog;
}
}

Android thread confusion

I have written a function to create a splash screen with a 5 second timeout for my app.
The code works fine, but when the timeout reaches zero and I want to redirect to my main activity, the app crashes with the following error:
Only the original thread that created a view hierarchy can touch its views.
So I looked around a bit and someone suggested nesting this inside my function. It seems like a good Idea, but now methods like sleep / stop won't work.
My code is below, I can provide more / explain more in details if it isn't clear enough just let me know. Thanks for the help.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showSplashScreen();
}
protected boolean _active = true;
protected int _splashTime = 5000; // Splash screen is 5 seconds
public void showSplashScreen() {
setContentView(R.layout.splash_layout);
// Thread splashThread = new Thread() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
int waited = 0;
while (_active && (waited < _splashTime)) {
Thread.sleep(100);
if (_active) {
waited += 100;
}
}
} catch (InterruptedException e) {
// do nothing
} finally {
showApplication();
}
}
});
}
Probably not what you want to hear, but you should never put a splash screen on your mobile app. With the exception of games, when people use a mobile app they want to get in, do what ever it is they need to do, and get out. If you make that process take longer, people are just going to get frustrated with you app. You should probably reconsider just not using a splash screen.
This will perform sleep on the UI thread. That's never a good idea.
Why not something like this?
new Handler().postDelayed(new Runnable() {
public void run() {
// start application ...
}
}, _splashTime);
But this answer has a good point. Displaying a splash screen for 5 seconds can be very annoying.
I believe you want AsyncTask for this. The method called on completion of the task will be called on your UI thread, making modifying UI elements much easier.
Use a Handler to post an event to the UI thread that will remove the splash.
Code should be something like...
splash.show()
new Handler().postDelayed(
new Runnable() {
void run() {
splash.remove();
},
delayTime);
I suggest you to make new activity for your spalsh screen, show it in a regular way (with startActivityForResult) and place in it such code (in it, not in your main activity):
new Handler().postDelayed( new Runnable()
{
public void run()
{ finish(); }
}, 5000 );
Also you can handle in this new activity click events for giving opportunity to user to close it faster, tapping on it.

Categories