I am trying to restart the same Activity after a specific time say after 2 min when a button is clicked. However, it does close the activity, however does not launch in the specified time , here is the code:
public void snoozeup(View view)
{
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run()
{
//start your activity here
startActivity(new Intent(Time_Date.this, Time_Date.class));
}
}, a); //where a is integer with value 120000
mp.stop();
mp.release();
voicePlayer.stop();
voicePlayer.release();
songPlayer.stop();
songPlayer.release();
this.finish();
}
You can't do it in that way - once your Activity is finished, all UI threads are stopped. Your Runnable will never be called.
If you want some functionality to run when your Activity is closed, you need to create a Service.
You should also take note of the problems with using postDelayed as described in postDelayed() in a Service.
I fixed it by using:
public void snoozeup(View view)
{
Handler handler = new Handler();
Runnable x=new Runnable() {
#Override
public void run()
{
startActivity(new Intent(Time_Date.this, Time_Date.class));
}
};
handler.postDelayed(x, 6000);
mp.stop();
mp.release();
voicePlayer.stop();
voicePlayer.release();
songPlayer.stop();
songPlayer.release();
finish();
}
Related
I am now trying to delay for a certain time before going to the next intent. I tried with postdelayed method but nothing works.
final Handler mHandler = new Handler();
runInBackground(
new Runnable() {
#Override
public void run() {
if(condition has met){
Runnable runnable = new Runnable() {
public void run() {
Intent i=new Intent(DetectorActivity.this,Main4Activity.class);
startActivity(i);
finish();
}
};
mHandler.postDelayed(runnable, 1000000);
}
}
});
You have 2 Runnable but you're just running internal one by using postDelayed().
You should run the first one too.
like this
runInBackground(new Runnable() {
.
.
.
.
.
}.run());
I have a button(in say Activity 1), which when clicked should start a service (eg Service 1). But there must be a delay of 5 seconds before the service starts. I achieved this using SystemClock.sleep(5000) in the onStartCommand of the service. This worked properly.
Now I want to add the functionality that if the button is clicked again(even before the 5 seconds end), the service WILL NOT BE STARTED.
Any ideas how to do this?
(Edit : Please read the entire question before marking it as a duplicate. Thanks)
You can use handler with post delayed to achieve your goal. Make your button disable and enable it after five seconds along with starting your service. You can implement the following code:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button.setEnabled(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//start your service here
button.setEnabled(true);
}
}, 5000);
}
});
Above code will disable your button for 5 second and will start your service after 5 second.
I'd use a util class similar to the following. Pass it in a runnable and a delay in ms and you can call stop() on it to cancel before it has run. You can also call restart() if you want to restart your timer. I use it for things like auto showing/hiding controls on an immersive view.
public class DelayableRunnable{
int mDelay = 0;
Handler mHandler = new Handler();
Runnable mRunnable;
boolean mIsRunning = false;
public DelayableRunnable(Runnable runnable, int delay){
mRunnable = runnable;
mDelay = delay;
}
public void setNewDelay(int delay){
mDelay = delay;
}
public void start(){
if(mIsRunning) {
stop();
}
mHandler.postDelayed(mRunnable, mDelay);
mIsRunning = true;
}
public void stop(){
mHandler.removeCallbacks(mRunnable);
mIsRunning = false;
}
public void restart(){
stop();
start();
}
}
You can use Handler.postDelayed function for delayed actions in Android enviroment (better than plan java methods)
final Handler handler = new Handler(); // or use existed one your_view.getHandler()
handler.postDelayed(new Runnable() {
#Override
public void run() {
//start your service
}
}, 5000 /* 5s * 1000ms */);
Or simpler use you view function (work same as above):
your_view.postDelayed(new Runnable() {
#Override
public void run() {
//start your service
}
}, 5000 /* 5s * 1000ms */);
A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals void schedule (TimerTask task,long delay) Schedules the specified task for execution after the specified delay.
new Timer().schedule(new TimerTask() {
#Override
public void run() {
alertDialog.dismiss();
startActivity(new Intent(****.this,*********.class));
}
},5000);
I have a service. And there is a method called onServiceUpdate(). This method is similiar with onLocationChanged() in Google Maps API.
So i want to start CountDownTimer inside onServiceUpdate() method but showing error like this :
Can't create handler inside thread that has not called Looper.prepare()
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.os.CountDownTimer$1.<init>(CountDownTimer.java:114)
at android.os.CountDownTimer.<init>(CountDownTimer.java:114)
at skripsi.ubm.studenttracking.Service2$6.<init>(Service2.java:317)
at skripsi.ubm.studenttracking.Service2.onServiceUpdate(Service2.java:317)
This is my code :
#Override
public void onServiceUpdate(ServiceState state)
{
final float[] distance = new float[2];
Location.distanceBetween(state.getGeoPoint().getLatitude(), state.getGeoPoint().getLongitude(), 6.130607787619352,106.81839518499267, distance);
if (distance[0] > 25.0)
{
CountDownTimer cdt5 = new CountDownTimer(total_onServiceUpdate,1000) {
#Override
public void onTick(long millisUntilFinished) {
total_onServiceUpdate = millisUntilFinished/1000;
}
#Override
public void onFinish() {
sendSMS();
stopSelf();
}
}.start();
}
the onServiceUpdate() is an aysnchronous task that runs and notifies you, hence its a background thread. all you need to do is call timer.start(); from the main Thread, the Service actually runs on the main Thread, it is intentService that doesn't so, your solution is along the ways of
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
CountDownTimer cdt5 = new CountDownTimer(total_onServiceUpdate,1000) {
#Override
public void onTick(long millisUntilFinished) {
total_onServiceUpdate = millisUntilFinished/1000;
}
#Override
public void onFinish() {
sendSMS();
stopSelf();
}
}.start();
}
});
now you can continue sir. Always call codes the flirt with the Screen on the main Looper
Hope it helps
Android :
Try This before calling a Handler
if (Looper.MyLooper() == null) { Looper.Prepare(); }
I think the problem is that in your sendSMS() you are trying to do something which requires UIThread (like updating a view).
Try this:
Handler mHandler = new Handler() {
public void handleMessage(Message msg){
sendSMS();
}};
Modify the onFinish method to
#Override
public void onFinish() {
mHandler.sendEmptyMessage(0);
stopSelf();
}
You cannot update a activity gui from a service via a handler because the handler has to be created in the gui thread.
instead you have to send a broadcast from your service and implement a local broadcast-receiver in the activity that gets this broadcast
I am creating a New Android application
I d like to switch from one activity to another activity after a time interval, How can i do this?
Kindly guide me
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app Next activity
Intent i = new Intent(CurrentActivity.this, NextActivity.class);
startActivity(i);
// close this activity
finish();
}
}, TIME_OUT);
There are numerous ways to do this.
You could use postDelayed(), however that is not advised since you cannot STOP it, or control it reliably, between various phases of activity lifecycle, to prevent for example wierd behaviour when the user exits the activity, before the delay has passed.
You would need some locks, or other mechanism.
Most proper approach would be to simply start a timer on the 1st activity onPostResume() which will start another activity after some delay.
TimerTask mStartActivityTask;
final Handler mHandler = new Handler();
Timer mTimer = new Timer();
#Override
private protected onPostResume() { // You can also use onResume() if you like
mStartActivityTask = new TimerTask() {
public void run() {
mHandler.post(new Runnable() {
public void run() {
startNewActivity(new Intent(MyClass.class));
}
});
}};
// This will start the task with 10 seconds delay with no intervals.
mTimer.schedule(mStartActivityTask, 100000, 0);
}
private void startNewActivity(Intent i) {
mTimer.cancel(); // To prevent multiple invocations
startActivity(i); // Start new activity
// finish(); // Optional, depending if you want to return here.
}
Try this code
private Thread thread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
thread = new Thread(this);
thread.start();
}
#Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent userName = new Intent(this, UserNameActivity.class);
startActivity(userName);
}
So I have an activity which runs a simple snakes and ladders game, and I want to allow the player to click a button and move, which would subsequently be followed by the computer moving. My problem is, that once the player moves, the computer immediately makes its move.
Instead I want the activity to wait before the computer makes its move. I've looked around a lot and found that waiting involves using a thread, but I have failed to implement it without my app crashing
My attempt at declaring a thread:
final Runnable runnable = new Runnable() {
#Override
public void run()
{
while (true)
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
Thread thread= new Thread(runnable);
My onClick() method for the button:
Button rollButton = (Button) (findViewById(R.id.rollButton));
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//executes only if current player is a human
if(GAME_BOARD.getCurrentPlayer().isHuman()) {
GAME_BOARD.rollDie(); // rolls the die
showDie(GAME_BOARD); // displays die on screen
GAME_BOARD.move(); // moves the player and sets next player as current player
playerTurn.setText(GAME_BOARD.getCurrentPlayer().getName() +"'s turn");// sets TextView to display who's player's turn it is
thread.start();
if(!GAME_BOARD.getCurrentPlayer().isHuman()) {
GAME_BOARD.rollDie();
showDie(GAME_BOARD);
GAME_BOARD.move();
playerTurn.setText(GAME_BOARD.getCurrentPlayer().getName() +"'s turn");
}
}
}
});
So again, my question is, how do I make it so that before the second if statement executes, the activity waits, say 4 seconds?
you can use an Handler.postDeleayed. You have to provide a Runnable to execut and the delay period in milliseconds. The Runnable will be executed on the UI Thread
You can use Handle to post your task defined in runnable after some delay
use this
Inside Activity define
Handler hand = new Handler();
and define your task in runnable like this
Runnable run = new Runnable() {
#Override
public void run() {
**your Task here.......**
}
};
In on click event
btnStartShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
hand.postDelayed(run,3000); // For delay three seconds
}
});
also remove all pending messages by calling following sentence at appropriate place
hand.removeCallbacksAndMessages(null);
Use a CountDownTimer:
CountDownTimer timer = new CountDownTimer(4000, 1000) {
#Override
public void onFinish() {
*function containing the second statement*
}
#Override
public void onTick(long millisLeft) {
// not ticking
}
};
and in the onClick method in the click listener use:
timer.start();
Try the following,
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Runnable runnable = new Runnable() {
#Override
public void run() {
// whatever you would like to implement when or after clicking rollButton
}
};
rollButton.postDelayed(runnable, 5000); //Delay for 5 seconds to show the result
}