Delay between two functions of one method - java

I am new to Android Studio. I want to put delay between Animation of button AND opening of second activity, So that animation runs and then splashActivity opens.
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0){
Animation anim4 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.splash_anim);
btn.startAnimation(anim4);
startActivity(new Intent(MainActivity.this, splashActivity.class));
}
});

int Delay_time_of_animation=500;
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0){
Animation anim4 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.splash_anim);
btn.startAnimation(anim4);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(MainActivity.this, splashActivity.class));
}
}, Delay_time_of_animation);
}
});

I use the native java Timer for the delay. if you want to delay between two method then you have to pass the delay time in milliseconds.
int DELAY_TIME=2000
//start your animation
new Timer().schedule(new TimerTask() {
#Override
public void run() {
//this code will run after the delay time which is 2 seconds.
startActivity(new Intent(MainActivity.this, splashActivity.class));
}
}, DELAY_TIME);
2000 millisecond means 2 second you can increase this time

Related

Disable button after returning from an intent

Afternoon all I need to call an intent and upon returning disable the button for X seconds.
I have tried variations of the following, which either disable the button immediately and then enable or do not do what I need full stop.
Guarding.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Guarding.setEnabled(false);
SharedPref.write(SharedPref.SCANTYPE,"GUARDING");
Intent intent = new Intent(Menu.this, CmxScanner.class);
startActivity(intent);
Guarding.postDelayed(new Runnable() {
public void run() {
Guarding.setEnabled(true);
//Log.d(TAG,"resend1");
}
},10000);
}
});
So on first entry to the menu i have a button that is enabled, after clicking it must call the intent and upon returning disable the button again for X seconds. Before it will enable and allow a second request to the Intent
You can register your calling activity for a result as explained in the Android docs here. Then in the result callback you simply enable the button after 10 seconds:
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
Guarding.postDelayed(new Runnable() {
public void run() {
Guarding.setEnabled(true);
}
}, 10000);
}
}
});

How to make the java wait for x seconds and then execute

I making an app and I would run in to a problem that I can't fix.
I am using Android Studio and I need to make a Button that I have already made. Do more then it already does. I want it to after display a text also close the app. Do you know how I should program that. It would be very helpful. Thanks in advance.
Here is the Java code:
package test.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonOnClick(View v) {
Button button=(Button) v;
((Button) v).setText("Correct");
}
public void buttonAnClick(View q) {
Button button=(Button) q;
((Button) q).setText("Niet goed");
}
}
So I have already made the button in XML and told it:
android:onClick="buttonOnClick"
Hope you can help me out!
If you're looking to have something happen afterwards what you're looking for is this:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//What you want to happen later
}
}, 1500); //1500 = 1.5 seconds, time in milli before it happens.
Put that in your button's method.
If you want to close your app you should call
finish();
Finish closes out the current activity. If you have other activities on the stack you'd return to them but since you likely only have 1 it should take you out.
Try this.
public void buttonOnClick(View v) {
Button button=(Button) v;
((Button) v).setText("Correct");
new android.os.Handler().postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
},1000); // milliseconds: 1 seg.
}
Check out CountDownTimer
CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
If you are trying to get something done with a delay when a button is pressed then do it something like this:
public void buttonOnClick(View v) {
Button button=(Button) v;
button.setText("Correct");
button.postDelayed(new Runnable(){
public void run() {
//runs after 1 second delay on UI thread
}
}, 1000L);
}
If you want to pause then use java.util.concurrent.TimeUnit.
For example:
TimeUnit.SECONDS.sleep(1);
Just put method into your button click function
public void buttonOnClick(View v) {
//call method here
}
If you want to use RxJava
Disposable di = Observable.timer(2, TimeUnit.SECONDS)
.subscribe(timer->{
//next action after 2 seconds
},throwable->{
// throw exception
});
To destroy disposable use, di.dispose();
if Use Runnable and Handler
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//next action after 2 seconds
}
}, 2*1000);
to stop the handler use, handler.removeCallbacksAndMessages(null);

Android : Start Activity after button animation

I used an android library to make a submit button with a nice animation (code below), after pressing the button, a want to start a new activity, but only after the animation is finished, how do i do that?
Xml code for the button "submitButton":
<com.spark.submitbutton.SubmitButton
android:layout_width="200dp"
android:layout_height="200dp"
android:text="Submit"
android:textColor="#color/gray"
app:sub_btn_background="#color/white"
app:sub_btn_duration="3000"
app:sub_btn_line_color="#99FF00"
app:sub_btn_ripple_color="#99FF00"
app:sub_btn_tick_color="#color/white"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/submitButton" />
Submit button for java file and action listener :
SubmitButton submitButton = (SubmitButton) findViewById(R.id.submitButton);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,ListViewActivity.class));
}
});
If that custom button doesn't provide a listener for its animation, there's no way to know when its animation is done.
Alternatively, you could use the duration of that animation, and start your activity in a postDelayed(runnable, duration)
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(MainActivity.this,ListViewActivity.class));
}
}, duration);
You may also replace the new Handler() with the v from onClick(View v)
Rather than start the activity directly, wrap up the call in a runnable, and call postDelayed with 3000 ms delay.
Like this
public void onClick(View v) {
Runnable r = new Runnable()
{
public void run()
{
startActivity(new Intent(MainActivity.this,ListViewActivity.class));
}
}
v.postDelayed(r, 3000);
}

order of onCreate() and onClick()

I have a Button in my Activity which, if not clicked within 5 seconds from creating the Activity, I want to crash the App. I tried the following but found out from logging that the OnClickListener code is executed after all other code in onCreate(Bundle) is run. So the boolean is always false when it is checked. How can I fix this?
private Boolean isClicked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("0-isClicked", String.valueOf(isClicked));
setContentView(R.layout.activity_main_map);
ImageView iv = (ImageView) findViewById(R.id.myBTN);
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
isClicked = true;
Log.e("1-isClicked", String.valueOf(isClicked));
startActivity(i);
}
});
Log.e("2-isClicked", String.valueOf(isClicked));
//let app crashes after 5 seconds (5000 milliseconds) if user didn't take action
if (!isClicked) {
Log.e("3-isClicked", String.valueOf(isClicked));
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (Exception e) {
e.printStackTrace();
} finally {
throw null;
}
}
};
timer.start();
}
}
And this is what LogCat gives:
E/0-isClicked﹕ false
E/2-isClicked﹕ false
E/3-isClicked﹕ false
E/1-isClicked﹕ true
I would do it the other way around: you crash your app anyway if in the 5 seconds, the user didn't click.
To ease the pain you can use CountdownTimer and do something those lines:
public void onCreate(){
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
Log.e("isClicked", String.valueOf(isClicked));
}
public void onFinish() {
if(!isClicked) throw null;
}
}.start();
}
You can use a Timer for setting a task to be executed 5 seconds later and in that task you can finish the activity. Create the timer on onCreate()
timer = new Timer(); // Keep the timer (of type Timer) as a member of the activity class so you can access it later
timer.scheduleTask(timerTaskInstance, 5000); // timerTaskInstance is an instance of TimerTask for which you should override the run() method
Now if the button is clicked before the timer times out just cancel the timer on the button's listener method:
timer.cancel();
More info about TimerTask
I think you have to understand when oncreate is runned. Your three first log statments is from onCreate and should be:
E/0-onCreate﹕ false
E/2-onCreate﹕ false
E/3-onCreate﹕ false
See http://www.codelearn.org/android-tutorial/android-activity

How to restore to exact activity after coming from Paused or Resumed state in android

I have two simple activities MainActivity and ThreadActivity. I call ThreadActivity from MainActivity.
The code ofMainActivity:
public class MainActivity extends Activity {
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btn2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ThreadActivity.class);
startActivity(intent);
}
});
}
}
And the code of ThreadActivity:
public class ThreadActivity extends Activity{
private Thread myThread=null;
Button btn;
int i = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runThread();
}
});
}
void runThread(){
myThread = new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
btn.setText("#" + i);
Log.d("Thread", "I am running " + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
}
};
myThread.start();
}
}
When I start ThreadActivity I run a simple thread and change button text.
My Problem
When I loose focus from application, i.e when application becomes partially visible, and I come back I am redirected to ThreadActivity and the thread is still running.
When I leave application running and open a new application, and then come back, I am again redirected to ThreadActivity.
The problem is when I press back button, I am being redirected to first activity MainActivity. But instead when back button is being pressed I want my application to exit. In a few words MainActivity should not exist in the stack.
I tried setting android:noHistory="true" for MainActivity but I could not keep the behavior explained in bullet points working. I mean when I pause the application and restore it back, it redirected me to MainActivity instead of ThreadActivity.
Just call finish() when starting the ThreadActivity:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ThreadActivity.class);
startActivity(intent);
finish();
}
});
BUT there is a problem with your app. Use a Timer to set the text of the Button! By using a Thread like you do you are creating a memory leak and that is very bad. Try this:
private int i = 0;
private Timer timer;
private final TimerTask timerTask = new TimerTask() {
#Override
public void run() {
btn.post(new Runnable() {
#Override
public void run() {
btn.setText("#" + i++);
}
});
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer = new Timer();
timer.schedule(timerTask, 300, 300);
}
});
}
#Override
public void onPause() {
super.onPause();
if(timer != null) {
timer.cancel();
}
}
From your comments to other peoples' answers, it seems like you want the ThreadActivity to always be resumed instead of the MainActivity when your thread is running.
Do the thread in a Service - the service will mean your application's VM is likely to be kept alive longer. An app with no foreground activities can be killed off quite quickly (even if it has background threads running).
You need to persist that the thread is running, and the progress (if, in the real code that is applicable). Currently you could persist the value of i in your while loop.
Your application's default launcher activity (MainActivity) will launch when you click on it from your launcher. Check if the persisted value has been set, and act as though the user started the ThreadActivity in onCreate, if you finish() in onCreate, the user won't see any UI from the MainActivity
Depending on what you're actually trying to do, you might be able to resume the thread depending on the progress persisted - in this example, you could start from the persisted value of i (instead of 0).
What I had to is set android:noHistory="true" for MainActivity and in the ThreadActivity I had to add the solution mention by #NeTeInStEiN in this quesiotn
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}

Categories

Resources