How can i code a time limit in my android game - android

i have a quiz game for my android that has a time limit. what i want is there is a choices button that if you click one of the buttons it you will be automatically intent to the class next level but if you didnt answer or click any of the button you will be intent to the other class, thats why the game has a time limit. my problem is i dont know how to put a time limit that will intent or transfer you in another class automatically if you didnt click any of the button choices. i tried sleep but what happen is even i already clicked the correct answer and im on the next level class it will sleep to the class i intented to my sleep. please help me with my problem. i also try handler but didnt work
public class EasyOne extends Activity {
Button a, b, c;
TextView timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easyone);
a = (Button) findViewById(R.id.btn_ea1);
b = (Button) findViewById(R.id.btn_eb1);
c = (Button) findViewById(R.id.btn_ec1);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"CORRECT!",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),EasyTwo.class);
startActivity(intent);
}
});
}
private Runnable task = new Runnable() {
public void run() {
Handler handler = new Handler();
handler.postDelayed(task, 5000);
Intent intent = new Intent(getApplicationContext(),TimesUp.class);
startActivity(intent);
}
};

You should use a handler but in order to cancel the timeout you must remove the delayed message from the handler in your click listener code.
public class EasyOne extends Activity {
static private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 123) {
((EasyOne) msg.obj).onTimeout();
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easyone);
a = (Button) findViewById(R.id.btn_ea1);
b = (Button) findViewById(R.id.btn_eb1);
c = (Button) findViewById(R.id.btn_ec1);
Message msg = mHandler.obtainMessage(123,this);
mHandler.sendMessageDelayed(msg,5000);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"CORRECT!",
Toast.LENGTH_SHORT).show();
mHandler.removeMessages(123,this);
Intent intent = new Intent(getApplicationContext(),EasyTwo.class);
startActivity(intent);
}
});
}
private void onTimeout() {
//your code
}
}

Related

Cyclic restart my application in 3h intervals. How to?

I need to write an application to open the browser (sample site www.onet.pl), which will restart every 3 hours. The commotion of restart was displayed. I managed to create such a layout, but I can not handle the cyclical restart. Please help where to add and what code? One class is enough.
This is my code:
public class MainActivity extends AppCompatActivity {
private Object v;
Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start(null);
m_Runnable.run();
}
public void start(View v) {
Uri uri = Uri.parse("http://onet.pl");
Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);
this.mHandler = new Handler();
}
private final Runnable m_Runnable = new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "odświezenie strony", Toast.LENGTH_SHORT).show();
MainActivity.this.mHandler.postDelayed(m_Runnable, 15000);
}
};
}
You could use a timer instead of Runnable.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "odświezenie strony", Toast.LENGTH_SHORT).show();
//and put the rest of your code here
}
},0,5000);

Android - Handler - How To Stop The Intent?

I want to stop the delay/intent from processing when the back button is pressed. I've searched some threads but I don't have the same Handler logic, I think. I apologize if it is.
Here is the code I'm working with:
else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, PollWebView_Gilmore.class);
startActivity(intent);
finish();
}
}, 10000);
You have to save a reference to both the Handler and your Runnable somewhere, and then you can use the removeCallbacks(Runnable) method on the Handler to cancel the pending request.
Example code:
public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.postDelayed(runnable, 5000);
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
handler.removeCallbacks(runnable);
}
}
If you Don't need a delay why do you use a Handler? Just remove it!
Call this directly
Intent intent = new Intent(MainActivity.this, PollWebView_Gilmore.class);
startActivity(intent);
finish();
When your back button is pressed!
You can also get an idea by reading below posts.
Android: Proper Way to use onBackPressed() with Toast
How to run a Runnable thread in Android?
If you want to do something with the intent on back pressed.You can override onBackPressed() method.

Android change Activity after few seconds

I need some help with my first Android project.
I want to write a app which is showing you a picture with a ImageView for a few seconds I would say so about 4 seconds and after that it change to a second activity which shows a button(only for testing).
My Problem is that my app after I started it in my AVD jump over the picture and shows immediately the button.
How can I fix it? I looked up so long and tried so many things I hope someone of you have a idea :)
Thanks for helping
Here my Code of my MainActivity:
package com.example.parkourspots;
public class MainActivity extends Activity {
private ViewTreeObserver vto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View myLayout = findViewById(R.id.startscreen);
vto = myLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
#Override
public void onGlobalLayout(){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
});
}}
Check this code.
package com.example.parkourspots;
public class MainActivity extends Activity {
private static int TIME_OUT = 4000; //Time to launch the another activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View myLayout = findViewById(R.id.startscreen);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(MainActivity.this, ActivityTwo.class);
startActivity(i);
finish();
}
}, TIME_OUT);
}
});
You can try:
public class MainActivity extends Activity {
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler.postDelayed(new Runanble() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
}, 4000); // 4 seconds
}
}
In addiction, you may add this for your second activity declaration in AndroidManifest: android:finishOnTaskLaunch="true"
never stall the UI thread. The UI thread is responsible for keeping your app feeling responsive.
But this is an fast and alternative solution for your problem.
public class MyActivity extends Activity {
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler.postDelayed(new Runnable() {
public void run() {
doStuff();
}
}, 5000);
}
private void doStuff() {
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
}
Then 5 seconds after the intent must start.
But i recommend async task
1)Sleeping 500 only sleeps for .5 seconds. So it would blink quickly anyway
2)Sleeping doesn't allow the thread to get back to the looper, so it freezes your UI. This means it won't update and draw anyway. Use a timer instead. Or posting a message to a handler would be acceptable here.
The problem is you're only sleeping for 500 milliseconds (half of one second), so it makes sense that it happens seemingly-immediately. You're also going to want to remove the OnGlobalLayoutListener after it's called. Here's an example of an approach that should work for you:
final Handler handler = new Handler(); // Create a Handler on the main Thread
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
#Override
public void onGlobalLayout(){
removeOnGlobalLayoutListener(vto, this);
handler.postDelayed(new Runnable(){
public void run(){
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
}, 4000); //Post back to the main Thread after 4000 mils (4 seconds)
}
});
#SuppressLint("NewApi")
public static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener){
if (Build.VERSION.SDK_INT < 16) v.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
else v.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
}
Proper and short solution
Make a handler and give them a delay to call back itself:
final Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 1s
}
}, 1000);
Remember that 1 sec = 1000 milliseconds
Adjust time with that formula.
Happy Coding.

What code should I input if I want to have a timer that will intent to other class?

What code should I put if I want to have a class that has a timer that will intent to other class? but it has a button that will automatically intent to other class if I click the button. its like a game, that if you don't click the button you will be transferred to the other class because it has a time limit
example is:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easyone);
a = (ImageButton) findViewById(R.id.ib_a);
b = (ImageButton) findViewById(R.id.ib_b);
c = (ImageButton) findViewById(R.id.ib_c);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"CORRECT!",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),EasyTwo.class);
startActivity(intent);
}
});
}
Thread timer = new Thread(){
protected void timeout() {
try {
sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
Intent intent = new Intent(getApplicationContext(),TimesUp.class);
startActivity(intent);
}
}
};start();
}
}//this one
I don't know what code should I input so I put the sleep though I know it is wrong
I have an error on the last bracket I'm very noob in brackets can you help me?
You can use an timeout just like this:
private void timeout() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getApplicationContext(),MainMenu.class);
startActivity(intent);
}
}
}, 5000);
I use this method all the time and I never had any problems.
From what I understand you are trying to do is you want to go to the next Activity if the Button is clicked or if the time is up.
that if you dont click the button you will be transfered to the other class because it has a time limit
With your code, the Thread won't run if the Button isn't clicked so you need to move that code outside of the Listener for it to run when the Button isn't clicked, wherever you want it to start.
so i put the sleep though i know it is wrong
sleep() is ok because it is on a background Thread
Use this for reference
private void timeOutCheck() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//call intent here
}
}, 5 * 1000);
}

Passing data through Intent in Android, just want the number of clicks

I have a program that starts on one activity goes to the next and their is button to click, after a certain amount of time it goes back to the starting page and reports the number of clicks.
Here's my code: clickcount is the first activity
public class ClickCountActivity extends Activity {
/** Called when the activity is first created. */
Button next;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
next=(Button) findViewById(R.id.NextButton);
//---------------------------------------------------------------
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(ClickCountActivity.this, startClickActivity.class);
i.putExtra("comingFrom", "come");
final int result=1;
startActivityForResult(i,result);
}
});
//---------------------------------------------------------------------------
}
}
public class startClickActivity extends Activity {
/** Called when the activity is first created. */
Button clicker;
int counter ;
Timer timer = new Timer(); // use timer to start a new task
MyTimerTask task = new MyTimerTask();
final long seconds = 3;
Intent p = getIntent();
String answer = p.getStringExtra("comingFrom");
class MyTimerTask extends TimerTask {
public void run()
//override run method
{
Intent x = new Intent(startClickActivity.this, ClickCountActivity.class);
x.putExtra("returnStr", answer);
setResult(RESULT_OK,x);
startActivity(x);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action);
clicker=(Button) findViewById(R.id.Clicker);
//---------------------------------------------------------------
clicker.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter++; // counts number of clicks
task.cancel(); // cancels current task
task = new MyTimerTask(); //create new task
timer.schedule(task,seconds*1000L); // start a new timer task in 5seconds (timertask, seconds(long))
// System.out.println(counter);
}
});
}
}
Your code in run method should be this:
Intent x = new Intent(startClickActivity.this, ClickCountActivity.class);
x.putExtra("returnStr", counter);
setResult(RESULT_OK,x);
finish();
You need to pass the no. of counts i.e. counter in intent and collect it from onActivityResult(int requestCode, int resultCode, Intent data) method of ClickCountActivity class. The value is passed in the data intent and can be queried using int counterValue = data.getIntegerExtra("returnStr", 0);

Categories

Resources