I want to stop a activity after the animation loop gets completed - android

There is a button in my app, after i click on the button another activity starts in which the animation i.e. the gif file is being played. The gif file is of single loop. All i want to do is after one loop of the animation gets completed, the current activity should automatically return to the previous (first) activity. The animation time can be taken into consideration while doing this. Please help.
public class MainActivity extends Activity {
boolean gif;
long time = 8000;
Handler handler;
GIFWebView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (gif){
}
else
{
GIFWebView view = new GIFWebView
(this, "file:///android_asset/imageedit_ball.gif");
gif = true;
new Handler().postDelayed(new Runnable() {
public void run() {
gif = false;
}
}, time);
setContentView(view);
}
}
}
This is the code for it.

Call finish() in the run() method on the handler.
Your code will still not behave as expected because the handler with postDelayed is not executed exactly at the time you specify. It will be a few milliseconds off. This is not important when the animation takes several seconds but will be noticeable for very short animations.

Related

change activity inside handler

I want to change from my current activity to another while I am inside a Handler. The idea is other code inside the handler will run until a certain condition doesnt match (with increment of the count value every time). When the count value matches the condition I close the activity and move to another.
my code is:
mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
if(count<CONDITION_VALUE)
{
//do other stuff...
count++;
}else
{
//change activity...
finish();
}
mHandler.postDelayed(mRunnable, 4000);
}
};
mHandler.postDelayed(mRunnable, (1000));
The code is running without any error but the old activity is not being destroyed (i guess) and the new activity is reloaded after every 4 seconds.
I want the new activity to load only once.
How can I achieve this?
try this, from enter link description here
in your Activity
#Override
public void onDestroy() {
mHandler.removeCallbacks(mRunnable);
super.onDestroy();
}

Add the loading screen in starting of the android application

My app is loading the start page in 10 seconds. In that time of 10 sec android screen is blank.
In that time I want to add the loading screen. How to add it?
And tell me in app how to know the starting page is loading? And tell me how to do in my app?
use ProgressDialog.
ProgressDialog dialog=new ProgressDialog(context);
dialog.setMessage("message");
dialog.setCancelable(false);
dialog.setInverseBackgroundForced(false);
dialog.show();
hide it whenever your UI is ready with data. call :
dialog.hide();
You can use splash screen in your first loading Activity like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread welcomeThread = new Thread() {
#Override
public void run() {
try {
super.run();
sleep(10000); //Delay of 10 seconds
} catch (Exception e) {
} finally {
Intent i = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(i);
finish();
}
}
};
welcomeThread.start();
}
Hope this code helps you.
Please read this article
Chris Stewart wrote there:
Splash screens just waste your time, right? As an Android developer,
when I see a splash screen, I know that some poor dev had to add a
three-second delay to the code.
Then, I have to stare at some picture for three seconds until I can
use the app. And I have to do this every time it’s launched. I know
which app I opened. I know what it does. Just let me use it!
Splash Screens the Right Way
I believe that Google isn’t contradicting itself; the old advice and
the new stand together. (That said, it’s still not a good idea to use
a splash screen that wastes a user’s time. Please don’t do that.)
However, Android apps do take some amount of time to start up,
especially on a cold start. There is a delay there that you may not be
able to avoid. Instead of leaving a blank screen during this time, why
not show the user something nice? This is the approach Google is
advocating. Don’t waste the user’s time, but don’t show them a blank,
unconfigured section of the app the first time they launch it, either.
If you look at recent updates to Google apps, you’ll see appropriate
uses of the splash screen. Take a look at the YouTube app, for
example.
You can create a custom loading screen instead of splash screen. if you show a splash screen for 10 sec, it's not a good idea for user experience. So it's better to add a custom loading screen. For a custom loading screen you may need some different images to make that feel like a gif. after that add the images in the res folder and make a class like this :-
public class LoadingScreen {private ImageView loading;
LoadingScreen(ImageView loading) {
this.loading = loading;
}
public void setLoadScreen(){
final Integer[] loadingImages = {R.mipmap.loading_1, R.mipmap.loading_2, R.mipmap.loading_3, R.mipmap.loading_4};
final Handler loadingHandler = new Handler();
Runnable runnable = new Runnable() {
int loadingImgIndex = 0;
public void run() {
loading.setImageResource(loadingImages[loadingImgIndex]);
loadingImgIndex++;
if (loadingImgIndex >= loadingImages.length)
loadingImgIndex = 0;
loadingHandler.postDelayed(this, 500);
}
};
loadingHandler.postDelayed(runnable, 500);
}}
In your MainActivity, you can pass a to the LoadingScreen class like this :-
private ImageView loadingImage;
Don't forget to add an ImageView in activity_main.
After that call the LoadingScreen class like this;
LoadingScreen loadingscreen = new LoadingScreen(loadingImage);
loadingscreen.setLoadScreen();
I hope this will help you
public class Splash extends Activity {
private final int SPLASH_DISPLAY_LENGHT = 3000; //set your time here......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(Splash.this,MainActivity.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
}
}
If the application is not doing anything in that 10 seconds, this will form a bad design only to make the user wait for 10 seconds doing nothing.
If there is something going on in that, or if you wish to implement 10 seconds delay splash screen,Here is the Code :
ProgressDialog pd;
pd = ProgressDialog.show(this,"Please Wait...", "Loading Application..", false, true);
pd.setCanceledOnTouchOutside(false);
Thread t = new Thread()
{
#Override
public void run()
{
try
{
sleep(10000) //Delay of 10 seconds
}
catch (Exception e) {}
handler.sendEmptyMessage(0);
}
} ;
t.start();
//Handles the thread result of the Backup being executed.
private Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
pd.dismiss();
//Start the Next Activity here...
}
};
Write the code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread welcomeThread = new Thread() {
#Override
public void run() {
try {
super.run();
sleep(10000) //Delay of 10 seconds
} catch (Exception e) {
} finally {
Intent i = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(i);
finish();
}
}
};
welcomeThread.start();
}

Updating UI on button click after a certain time

I have a TextView. I want to update its text (append a "1") after 1 second of a button click.
public class HaikuDisplay extends Activity {
Method m;
Timer t;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Timer();
m = HaikuDisplay.class.getMethod("change");
}
//Event handler of the button
public void onRefresh(View view)
{
//To have the reference of this inside the TimerTask
final HaikuDisplay hd = this;
TimerTask task1 = new TimerTask(){
public void run(){
/*
* I tried to update the text here but since this is not the UI thread, it does not allow to do so.
*/
//Calls change() method
m.invoke(hd, (Object[])null);
}
};
t.schedule(task1, 1000);
}
public void change()
{
//Appends a "1" to the TextView
TextView t = (TextView)findViewById(R.id.textView1);
t.setText(t.getText() + "1");
}
//Event handler of another button which updates the text directly by appending "2".
//This works fine unless I click the first button.
public void onRefresh1(View view)
{
TextView t = (TextView)findViewById(R.id.textView1);
t.setText(t.getText() + "2");
}
}
Consider all Exceptions be handled.
On first click, m.invoke gives InvocationTargetException. But it calls the method change() on successive invokes without any Exceptions(verified by logging). But it does not update the text. Where am I wrong?
Also, I see in the debugger that it creates a new Thread every time I click the button. That is fine. But why isn't it removing the previous Threads though their execution has been completed?
Do something like this
public void onRefresh1(View v) {
// You can have this in a field not to find it every time
final EditText t = (EditText) findViewById(R.id.textView1);
t.postDelayed(new Runnable() {
#Override
public void run() {
t.append("1");
}
}, 1000);
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Update UI
}
}, 1000);
implement this on button click
UPDATE:
There are some other answers. dtmilano suggested another solution which is almost same to mine except he is calling the postDelayed method of View class and In my answer I used postDelayed method of handler class.
from the api reference of android the postDelayed method of Handler says
The runnable will be run on the thread to which this handler is
attached.
and the postDelayed method of View says
The runnable will be run on the user interface thread.
This is the only difference between these two solution. in my answer instead of creating new Handler every time you can use any other handler instance. Then the runnable will be run on that thread where that specific handler is declared. And if the postDelayed of EditText is used the the runnable method will be run on the user Interface Thread.
Now the performance issue, both has the same performance (If anybody can prove me wrong with reference I will be happy)
That's looking awful convoluted - have you considered using CountDownTimer instead?
new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {
// no-op
}
public void onFinish() {
change();
}
}.start();
This should call change (and hence change the text) on the UI thread, avoiding reflection and threading errors.
Hi Use the following code for that. Hope this will help you .
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
// your code here
}
},
1000
);
Have a look of this question also.
display data after every 10 seconds in Android
You can try with this also.
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
doStuff();
/*
* Now register it for running next time
*/
handler.postDelayed(this, 1000);
}
};
**EDIT 3**
Try with this once you are need to enable once (i mean if you put your code in yourmethod()== this will get automatically call 1 seconds once.
private Timer timer;
TimerTask refresher;
// Initialization code in onCreate or similar:
timer = new Timer();
refresher = new TimerTask() {
public void run() {
yourmethod();
};
};
// first event immediately, following after 1 seconds each
timer.scheduleAtFixedRate(refresher, 0,100);

Android activity to handle multi threading

In my activity class i want to perform a series of long calculations that require around 5 sec to complete when i press a button. So in order to do that i have create a new class which does all the calculations in its run method(since it implements Runnable) and when finished i set a variable to true to indicate that. In the code that checks the if the button is pressed i start a new Thread passing my class in it and then cheking whether the run method has finished or not. If it finished i then print the data. The problem with this is that when i check if the calculations have finished they actually havent so it pass that line of code and never prints the data. I have tried to do the Async Class method but still i think it wont work. Is there a way to create the thread when i press the button and keep checking if had finished so i can print the data? Which piece of code in an Activity is actually get executed over and over again? Thanks for any information.
if(v.equals(this.button)) {
EditText param1 = (EditText)findViewById(R.id.param1);
EditText param2 = (EditText)findViewById(R.id.param2);
calculations = new MathCalc(param1.getText().toString(), param2.getText().toString());
new Thread(calculations).start();
while(!calculations.isReady());
Intent intent = new Intent(this,Show.class);
intent.putExtra("show1", calculations.getResult());
startActivity(intent);
}
This is want i want to achieve.
The AsyncTask is the right tool for this. The typical use case for the AsyncTask is that you want to do something small in the background and leave feedback through the UI before, during and/or after the task is done.
Be aware that running things in the background can get you in trouble if the user quits and restarts your activity a lot, since the background task will not end when the Activity is removed from screen.
An example activity is shown below. You could add the onPreExecute and onProgress methods to the AsynchTask to give the user feedback before and during the calculation.
public class CalcActivity extends Activity {
private Button button;
private TextView resultView;
public void onCreate() {
button = (Button) findViewById(R.id.my_button);
resultView = (TextView) findViewById(R.id.result);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
button.setEnabled(false);
AsyncCalculation calc = new AsyncCalculation();
calc.execute();
}
});
}
public class AsyncCalculation extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
int result = 0;
// Do some calculation
return result;
}
#Override
protected void onPostExecute(Integer result) {
// Set the result, start another activity or do something else
resultView.setText("The result was " + result);
button.setEnabled(true);
}
}
}
I don't see how this won't work with AsyncTask. You basically need to override two methods - doInBackground() and onPostExecute().
You're guaranteed that onPostExecute() will be invoked on the UI thread after the background computation finishes. You also don't have to worry how to update the UI Thread from another thread.
Here's a good example.
Use
Button someButton = (Button) findViewById(R.id.favouriteButton);
someButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while(!isDone){
doAlotOfCalculations();
}
}
});
thread.start();
}
});
private void doAlotOfCalculations(){
...
if(whenDone){
isDone = true;
}
....
}
Which piece of code in an Activity is actually get executed over and
over again?
There is no such a thing.
It is just onResume which executes every time you start(restart) this activity

How can I make the android program display a layout and then wai a few sec. and the display another layout?

Hi guys I just want the program to display the layout main0 and stay for a few secounds then display layout main1 like the programs we see in any phone where an image or layout show up at the start of the program and then fade.
/**the main activity */
public class rdwt extends Activity implements OnClickListener{
Button b1;
Button b2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main0);
//Here
setContentView(R.layout.main1);
b1= (Button)findViewById(R.id.Button01);
b2= (Button)findViewById(R.id.Button02);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
public void onClick(View v) {
if (v==this.b1){
Intent callwrite = new Intent(this, wto.class);
startActivity(callwrite);
}
if(v==this.b2){
Intent callread = new Intent(this, rfr.class);
startActivity(callread);
}
}
}
You need to read a technical article about Updating the UI from a Timer
I think there are particularly two different approaches.
1) use a android.os.Handler and send a delayed message
2) use a timer and a timer task to update your layout after a specific amount of time
Code example:
TimerTask bla = new YourTask();
Timer timer = new Timer();
timer.schedule(bla, 1000);
And your class YourTask:
public class YourTask extends TimerTask {
public void run() {
updateYourLayout();
}
}
Edit: However I think you're looking for a splashscreen. This simple tutorial explains how to do it: http://www.anddev.org/simple_splash_screen-t811.html
// Place the following line in your code.
timer(3500); // Waits 3.5 seconds before moving on to the next activity.
public void timer(int counter){
new Handler().postDelayed(new Runnable(){
#Override
// counter is in milliseconds.
public void run() {
Intent mainIntent = new Intent(THISCLASSNAME.this,CLASSNAMETOJUMPTO.class);
startActivity(mainIntent);
finish();

Categories

Resources