How can I call the same functions in onCreate() and onResume() methods? - java

I want to run the same functions in onCreate() and onResume(). The functions basically record in 10 seconds and then stop and play the recorded sound.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new CountDownTimer(
10000, // 10 second countdown
9999) { // onTick time, not used
public void onTick(long millisUntilFinished) {
// Not used
}
public void onFinish() {
isRecording = false;
}
}.start();
Thread thread = new Thread(new Runnable() {
public void run() {
isRecording = true;
record(); // starts to record
}
});
thread.start(); // thread start
// thread to start
play();
}
If I hit the Home button, then the app got put into the background. Now if I hit the app's icon button again, I'd like to call the same recording and playing functions.
Can I do same thing like this in onResume()? Basically duplicate the same thing.
public void onResume() {
super.onResume();
new CountDownTimer(
10000, // 10 second countdown
9999) { // onTick time, not used
public void onTick(long millisUntilFinished) {
// Not used
}
public void onFinish() {
isRecording = false;
}
}.start();
Thread thread = new Thread(new Runnable() {
public void run() {
isRecording = true;
record(); // starts to record
}
});
thread.start(); // thread start
play();
}

Just put the stuff you want to run in onResume(). onResume() will get called after onCreate() the first time then it will get called each time the application comes out of the background.
Activity lifecycle can be found (visually) here:
http://developer.android.com/reference/android/app/Activity.html

Related

How to start a thread if a button is idle?

I need a thread to start after 3 seconds of a button being idle, is there a simple way of doing it?
I'm building a counter app, the button triggers two counters, the total counter and the "tapping counter", the tapping counter helps keep track of the actual change of values, showing how many taps the user did, I need it to vanish after some seconds so the user can tap again.
for stuffs like that I usually use a Handler with a Runnable in order to do stuff after X milliseconds the user isn't doing a specific action.
First, create a runnable and a handler
final android.os.Handler handler = new android.os.Handler();
private Runnable runnable;
private final long DELAY = 3000; // how many milliseconds you want to wait
Then add the onClickListener:
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
Then, inside onClick event, remove callbacks and istantiate the handler again as follows:
if(runnable != null) {
// in this case the user already clicked once at least
handler.removeCallbacks(runnable);
}
runnable = new Runnable() {
#Override
public void run() {
//this code will run when user isn't clicking for the time you set before.
}
};
handler.postDelayed(runnable, DELAY);
Final result:
final android.os.Handler handler = new android.os.Handler();
private Runnable runnable;
private final long DELAY = 3000; // how many milliseconds you want to wait
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// all your previous stuffs
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(runnable != null) {
// in this case the user already clicked once at least
handler.removeCallbacks(runnable);
}
runnable = new Runnable() {
#Override
public void run() {
//this code will run when user isn't clicking for the time you set before.
}
};
handler.postDelayed(runnable, DELAY);
}
});
}
I hope this helps, for any question feel free to ask
Handler may work in this scenario, with a 3000 milisecond delay.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// do action
}
}, 3000);
At first, you create a Timer with a TimerTask(with your Thread) and schedule it to run after 3 seconds.
Every time the button is pressed, you reset the timer.
public class MyClass{
private Timer timer=new Timer()
private TimerTask task=new TimerTask(){
public void run(){
//your action
}
};
public void init(){
timer.schedule(task,3000);
}
public void onButtonClick(){
task.cancel();
timer.schedule(task,3000);
}
}

Android stop loop by click button

i am trying to make a button that when its clicked , it changes its color image and starts a countdowntimer in a method activeDelay() as here:
piscaAutoButton = (Button) rootView.findViewById(R.id.piscaAutoButton);
piscaAutoButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(final View view) {
if (sessionManager.getPisca()) {
sessionManager.setPisca(false);
trigger = false;
piscaAutoButton.setBackgroundResource(R.drawable.button_bg_round);
} else {
sessionManager.setPisca(true);
piscaAutoButton.setBackgroundResource(R.drawable.button_add_round);
trigger = true;
activeDelay(trigger);
}
here is my activeDelay method:
private boolean activeDelay(boolean trigger) {
while (trigger) { // LOOP WHILE BUTTON IS TRUE CLICKED
int timerDelay = manualControl.getDelayPisca(); //input for timer
//delay manual
new CountDownTimer(timerDelay * 1000, 1000) {
public void onFinish() {
System.out.println("sent");
try {
System.out.println("blink button " + manualControl.getBlinkButton());
if (!manualControl.getBlinkButton().isEmpty()) {
MenuActivity.mOut.write(manualControl.getBlinkButton().getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void onTick(long millisUntilFinished) {
}
}.start();
}
return trigger;
}
My problem is that i need the counter keeps going after finished, stopping just when the user clicks again in the button (trigger = false). I am having problems to program that, if someone could help,i know the return inside activeDelay ejects from the method, how can we solve that ,tks
I would suggest you to don't use CountDownTimer(this runs for some specific time period) , instead of this you should use Handler(this run infinitely) . i am sending you handler code.
private Handler handler = new Handler();
//call this when you want to start the timer .
handler.postDelayed(runnable, startTime);
Runnable runnable = new Runnable() {
#Override
public void run() {
// Do here , whatever you want to do(show updated time e.t.c.) .
handler.postDelayed(this, xyz); //xyz is time interval(in your case it is 1000)
}
};
//Stop handler when you want(In your case , when user click the button)
handler.removeCallbacks(runnable);

Android wait 1 minute without stopping thread

How do I wait one minute in my Android application without stopping the thread? I need to play a sound every minute for X rounds. I have all the code working except the waiting code.
public void startRounds(View v)
{
MediaPlayer mp = MediaPlayer.create(this, R.raw.ding);
mp.start();
EditText txtRounds = (EditText) findViewById(R.id.txtRounds);
rounds = Integer.parseInt(txtRounds.getText().toString());
oneSession();
}
private void oneSession()
{
//this needs to be replaced with my new wait one minute function
SystemClock.sleep(60000);
MediaPlayer mp2 = MediaPlayer.create(this, R.raw.ding);
mp2.start();
if (rounds != 1) {
rounds--;
oneSession();
}
}
Solved:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//do something
}
}, 60 * 1000);
I am not sure if this is what you really want but it here do something will run after 60 * 1 seconds
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//do something
}
}, 60 * 1000);
You can use Handler which will get executed without blocking thread.eg
handler.postDelayed(new Runnable() {
#Override
public void run() {
/**put your code inside this
* this method will get exceuted after 1 min without stopping thread
* same thing can be recursive based on your requirement*/
}
},60000);
Run the minute in another thread because on the UI Thread de sound will stop:
new Thread(new Runnable() {
#Override
public void run() {
try{
Thread.sleep(60000)
}catch(InterruptedExcpetion e){
}
}).start();

onTick method of Countdown timer keeps getting called even after calling cancel

I am trying to load some data. Id data is loaded in 20 seconds than i start new activity else i will finish by giving some relevant message. I have started a countdownTimer to keep track of time. Once data is loaded, I want to stop the timer. I have Following class :
public class SplashActivity extends AppCompatActivity {
private Context mContext;
private Boolean mDataLoadedFromServer = false;
private String mJSONData;
private SplashTimerForLoadingMasterDataForAllChannels mTimer;
private void stopTimer(){
mTimer.cancel();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_splash);
mTimer = new SplashTimerForLoadingMasterDataForAllChannels(20000,1000);
mTimer.start();
}
class SplashTimerForLoadingMasterDataForAllChannels extends CountDownTimer {
public SplashTimerForLoadingMasterDataForAllChannels(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
Log.d("testTimer", "SplashTimerForLoadingMasterDataForAllChannels");
//SomE AsyncTAsk
LoadData loaddata = new LoadData();
loaddata.execute();
//SomE AsyncTAsk
}
#Override
public void onTick(long millisUntilFinished) {
Log.d("testTimer", "onTick millisUntilFinished = " + millisUntilFinished + " mDataLoadedFromServer = " + mDataLoadedFromServer);
//mDataLoadedFromServer is modified once Data is loaded in AsyncTask
if(mDataLoadedFromServer) {
stopTimer();
}
}
#Override
public void onFinish() {
Log.d("testTimer", "onFinish");
if(mDataLoadedFromServer) {
mDataSavedAndNextActivityLaunched = true;
if (Utils.checkIfUserLoggedIn()) {
mContext.startActivity(new Intent(mContext, ABCACtivity.class));
} else {
mContext.startActivity(new Intent(mContext, XYZActivity.class));
}
finish();
}
}
}
}
I cancel it in a local method call but onTick still keeps getting called. Can someone please help?
Basically counter does not simply stop if I cancle it from onTick() or from onFinish() ie FROM INSIDE TIMER.
However it stops very easily if I do it from any point outside of timer.
So the point at which my data is fully loaded...I called timer.cancle() and it did the trick.
However I still dont understand why it does not work if we do same from inside timer methods.
I tried this code snippet, since most answers are saying you cannot cancel the timer inside its implementation, thus i tried using a handler inside onFinish. Old post but if anyone comes across this its helpful.
new Handler().post(new Runnable() {
#Override
public void run() {
timerTextView.setText("00:" + String.format("%02d", counter));
cancel();
}
});
you need to call stopTimer() outside of the CountDownTimer's onTick(),
something like this
#Override
public void onFinish() {
Log.d("testTimer", "onFinish");
if(mDataLoadedFromServer) {
mDataSavedAndNextActivityLaunched = true;
if (Utils.checkIfUserLoggedIn()) {
mContext.startActivity(new Intent(mContext, ABCACtivity.class));
} else {
mContext.startActivity(new Intent(mContext, XYZActivity.class));
}
finish();
stopTimer();
}
}

Start an Activity from Splash Screen, should I use run() or runOnUiThread()?

I have a Splash Screen (Logo Activity) to show the company name for 3 seconds before app starts. I start Main Activity from a thread, here is the code:
public class Logo extends Activity {
Thread t;
public boolean dead = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logo);
t = new Thread() {
public void run() {
try {
Intent i = new Intent(Logo.this, Main.class);
Thread.sleep(3000);
if (!dead) {
startActivity(i);
}
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
}
The Main Activity is called from a worked thread, is this correct? What are the differents with this code (using runOnUiThread)?
...
if (!dead) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(Logo.this, Main.class);
startActivity(i);
}
});
}
...
I see no difference with this code in debug mode (The same threads, the same operation, etc.). Which is correct?
Starting an intent I think is not an UI operation. runOnUI thread runs UI operation on UI thread. So you can use either of thread (runOnUI or normal). May be normal thread will be good in this situation. But I would like to suggest you use timer instead.
To be honest, I don't like the Thread.sleep. PLease take a look at my solution:
new Timer().schedule(new TimerTask() {
#Override
public void run() {
// Do your work here like... startActivity...
}
}, SPLASH_DURATION); // SPLASH_DURATION IS IN MILLISECONDS LIKE 3000
Also you can block the user to prevent the back key like this:
#Override
public void onBackPressed() {
// do nothing! disable user interaction!
}
You should use AsyncTask in "doInBackground" background thread and than sleep your thread(this thread not UIThread) "PostExecute" run on UI Thread than start your new activity
private class mSplashViewer extends AsyncTask<Void,Void,Void>{
protected void doInBackground(Void params){
Thread.currentThread().sleep(3000);
return null;
}
protected void onPostExecute(){
startActivity(...);
}
}

Categories