How to set a time limit to an android activity - android

I have a game where if a user touches the wrong button he goes to the highscores page and if he clicks the right one he goes to the next level. What I would like to do is make it so if the user does absolutely nothing for 1.5 seconds (fast-paced game) then it automatically intents him back to the scores.class activity. I am new to programming so anything helps!!! Thanks.

This will give you an idea:
private MainActivity context;
private CountDownTimer countDownTimer;
public boolean timerStopped;
/** Called when the activity is first created. */
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
startTimer();
// method looks at users choice, example
/* if (answer == true){
stopTimer();
// go to next question and start timer again..
}
else{
// do something
}
*/
}
/** Starts the timer **/
public void startTimer() {
setTimerStartListener();
timerStopped = false;
}
/** Stop the timer **/
public void stopTimer() {
countDownTimer.cancel();
timerStopped = true;
}
/** Timer method: CountDownTimer **/
private void setTimerStartListener() {
// will be called at every 1500 milliseconds i.e. every 1.5 second.
countDownTimer = new CountDownTimer(1500, 1500) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
// Here do what you like...
Intent intent = new Intent(context, Scores.class);
startActivity(intent);
}
}.start();
}

have you tried with CountDownTimer?
Here is an example:
new CountDownTimer(1500, 1500) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
// Here do what you like...
}
}.start();

To fix the error mentioned:
MainActivity context;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
new CountDownTimer(1500, 1500) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
// Here do what you like...
Intent intent = new Intent(context, Score.class);
startActivity(intent);
}
}.start();

Related

Launch an Activity after timer

So I have this code, that has a countdown timer in a service with a 10 second timer. What I want to do is in the onFinish() method I want to launch the Activity (which is called MainActivity) automatically even when I am outside the app.
public class TimeDisplayTimerTask extends TimerTask{
CountDownTimer timer;
NotificationCompat.Builder notification;
private static final String TAG="com.timer";
private Handler mHandler = new Handler();
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
timer = new CountDownTimer(10000, 1000) {
#Override
public void onFinish(){
}
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG,"" + millisUntilFinished/1000);
}
};
timer.start();
}
});
}
}
Try This to open your main activty after 10 second.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// launch your main activity here and finish your current activity
}
}, 10000);
}
Probably you will have to override lifecycle method's and also use PARTIAL_WAKE_LOCK to keep cpu running untill you finish execution, in case user lock screen.
If you are inside a service then simply launch you activity using intent. Put this code in your onFinish() method:
Intent i = new Intent();
i.setClass(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
You neet to pass an activity context to your TimeDisplayTimerTask :
public class TimeDisplayTimerTask extends TimerTask{
CountDownTimer timer;
NotificationCompat.Builder notification;
private static final String TAG="com.timer";
private Handler mHandler = new Handler();
private Activity mActivity;
public TimeDisplayTimerTask(Activity activity){
mActivity = activity;
super();
}
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
timer = new CountDownTimer(10000, 1000) {
#Override
public void onFinish(){
if (activity != null {
Intent startIntent = new Intent(activity, MainActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(startIntent);
}
}
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG,"" + millisUntilFinished/1000);
}
};
timer.start();
}
});
}
}

Reset value to default when using OnclickListener in Android

I'm trying to do some example about countdown timer using Button and set OnclickListener for that Button. My Default value is 10 and it will be decrease each second, how can i reset my value back to 10?
CountDownTimer cannot be restarted, it can only be used once. You either have to create your own count down class that can handle being restarted, or just create a new instance of your CountDownTimer and cancel the old instance.
See the example code below where we have a CountDownTimer that counts down for 10 seconds in 1 second intervals, a Button that resets the timer when clicked (by cancelling the current timer and starting a new one), and a TextView that displays the time left in the current timer.
public class YourActivity extends Activity {
private CountDownTimer countDownTimer;
private TextView timerDisplayTextView;
private static final long TEN_SECONDS = TimeUnit.SECONDS.toMillis(10);
private static final long COUNTDOWN_INTERVAL = TimeUnit.SECONDS.toMillis(1);
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Button myButton; // initialized here
// timerDisplayTextView initialized here
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
countDownTimer.cancel();
countDownTimer = getNewCountDownTimer(TEN_SECONDS);
countDownTimer.start();
showTimeInTextView(TEN_SECONDS);
}
});
countDownTimer = getNewCountDownTimer(TEN_SECONDS);
countDownTimer.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
countDownTimer.cancel();
}
private void showTimeInTextView(long millisecondsLeft) {
timerDisplayTextView.setText(TimeUnit.MILLISECONDS.toSeconds(millisecondsLeft) + " seconds left");
}
private CountDownTimer getNewCountDownTimer(long length) {
return new CountDownTimer(length, COUNTDOWN_INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
showTimeInTextView(millisUntilFinished);
}
#Override
public void onFinish() {
}
};
}
}

Close an Activity after 10 seconds?

I use it to call another activity
Main.java
Intent intent = new Intent(this, Message_Note.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Message_Note.java :
public class Message_Note extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
}
}
How can i CLOSE the Message_Note Activity after 10 seconds ?? i should use a thread ?
After 100 MS, the activity will finish using the following code.
public class Message_Note extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finish();
}
}, 100);
}
}
You can use following approach.
Approach 1
int finishTime = 10; //10 secs
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
YourActivity.this.finish();
}
}, finishTime * 1000);
Approach 2
int FinishTime = 10;
int countDownInterval = 1000;
counterTimer = new CountDownTimer(FinishTime * 1000, countDownInterval) {
public void onFinish() {
//finish your activity here
}
public void onTick(long millisUntilFinished) {
//called every 1 sec coz countDownInterval = 1000 (1 sec)
}
};
counterTimer.start();
You can use AlarmManager. See :
http://developer.android.com/reference/android/app/AlarmManager.html
and
Alarm Manager Example
Another way is just like this:
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
Message_Note.this.finish();
}
}, 10000);

How to add time to countdown timer?

I know there is a post like this but it does not answer the question clearly.
I have a little game where you tap a head and it moves to a random position and you get +1 to score. Meanwhile there is a timer counting down from 60000 (60 seconds) and displaying below.
How can I make it so whenever the head is tapped, it adds a second to the timer?
new CountDownTimer(timer, 1) {
public void onTick(long millisUntilFinished) {
textTimer.setText("Timer " + millisUntilFinished/1000);
}
public void onFinish() {
Intent intent = new Intent(MainActivity.this, Gameover.class);
startActivity(intent);
}
}.start();
and in the onClickListner event I have:
timer=timer+1000;
It currently doesn't work as in there is no time added on the click.
Any help would be appreciated :)
You can't change the time of a scheduled timer. The only way to achieve what you are trying to do is by cancelling the timer and setting up a new one.
public class CountdownActivity extends Activity implements OnTouchListener{
CountDownTimer mCountDownTimer;
long countdownPeriod;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countdown);
countdownPeriod = 30000;
createCountDownTimer();
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mCountDownTimer != null)
mCountDownTimer.cancel();
createCountDownTimer();
return true;
}
private void createCountDownTimer() {
mCountDownTimer = new CountDownTimer(countdownPeriod + 1000, 1) {
#Override
public void onTick(long millisUntilFinished) {
textTimer.setText("Timer " + millisUntilFinished / 1000);
countdownPeriod=millisUntilFinished;
}
#Override
public void onFinish() {
Intent intent = new Intent(MainActivity.this, Gameover.class);
startActivity(intent);
}
};
}
}

how to include timer in my program?

i need to include timer in my application.i just gone through the example given in the sites.and tried to implement that in my program.but the thing is i dont know how to work with timer.in my program i want to start the timer on a button click.timer has to show in the screen.but the screen is a canvas(when we click on button it loads a canvas) with moving objects.when two objects collide timer has to stop and has to show the value in a message box.given below is my main activity code.
public class MyActivity extends Activity {
private static final String TAG = MyActivity.class.getSimpleName();
public static Timer myTimer;
private Button startbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
startbtn=(Button)findViewById(R.id.startbtn);
startbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// making it full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// set our MainGamePanel as the View
setContentView(new MainGamePanel(getApplicationContext()));
Log.d(TAG, "View added");
}
});
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
#Override
protected void onDestroy() {
Log.d(TAG, "Destroying...");
super.onDestroy();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopping...");
super.onStop();
}
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
//Do something to the UI thread here
}
};
}
i know how to check collision.i need only timer part like starting timer,showing on the screen and stopping it from another class.can anybody help me...plz....
Use this the code will be repeated after one second and timer will run for 30sec
new CountdownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
finish();
}
}.start();

Categories

Resources