how to manage a countdown to begin right away with an activity start and to start new activity when time is up? Thanks in advance
Edits:
Activity contatins a button. User should press it until time is up, otherwise another activity starts
try this code
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
//start new activity
}
}.start();
You can achieve this in two ways
METHOD 1: Creation of a thread and setting time to sleep exactly after that redirection to main app screen.
METHOD 2: Set time to handler and call Handler().postDelayed , it will surly call run method of runnable after setting the time and redirection to main app screen.
we can implement in this given way wher we can write code for our MainScreen
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainscreen);
// METHOD 1
/****** Create Thread that will sleep for 10 seconds *************/
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 10 seconds
sleep(10*1000);
// After 10 seconds redirect to another intent
Intent i=new Intent(getBaseContext(),AnotherScreen .class);
startActivity(i);
//Remove activity
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();
//METHOD 2
/*
new Handler().postDelayed(new Runnable() {
// Using handler with postDelayed called runnable run method
#Override
public void run() {
Intent i = new Intent(MainScreen.this, AnotherScreen.class);
startActivity(i);
// close this activity
finish();
}
}, 10*1000); // wait for 10 seconds
*/
}
#Override
protected void onDestroy() {
super.onDestroy();
}}
the AnotherScreen code can be as follows
import android.app.Activity;
import android.os.Bundle;
public class AnotherScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.anotherScreen);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
for an another example visit http://www.androidhive.info/2013/07/how-to-implement-android-splash-screen-2/
https://codereview.stackexchange.com/questions/31295/review-request-android-countdowntimer-activity
This is the answer you are looking for a spalshActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
try {
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
Intent i = new Intent(SplashScreen.this,
MainActivity.class);
startActivity(i);
finish();
}
};
Timer timer = new Timer();
timer.schedule(timerTask, 300);// DElay of 300 mil sec
} catch (Exception e) {
Log.e("ERROR in Splash Screen", e.toString());
}
}
Related
Please guide me in this. Appreciate all your help.
My background service is toasting ABC
//-------------------String displayingText = "ABC";-----------------
And I have two strings, ABC and DEF declared in mainactivity.java
How do I pass the value displayingText from main activity to this service.
How do I change the displayingText to DEF after the toast ABC finished.
MyService.Java
public class MyService extends Service {
public static final long INTERVAL=3000;//variable to execute services every 5 second
private Handler mHandler=new Handler(); // run on another Thread to avoid crash
private Timer mTimer=null; // timer handling
//the get intent dont work. where or how should i put it?
Intent myIntent = getIntent();
if (myIntent !=null && myIntent.getExtras()!=null)
String value = myIntent.getExtras().getString(PassToService);
#Nullable
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("unsupported Operation");
}
#Override
public void onCreate() {
// cancel if service is already existed
if(mTimer!=null)
mTimer.cancel();
else
mTimer=new Timer(); // recreate new timer
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(),0,INTERVAL);// schedule task
}
#Override
public void onTaskRemoved(Intent rootIntent) {
stopSelf();///its will stop service
super.onTaskRemoved(rootIntent);
}
#Override
public void onDestroy() {
Toast.makeText(this, "In Destroy", Toast.LENGTH_SHORT).show();//display toast when method called
mTimer.cancel();//cancel the timer
super.onDestroy();
}
//inner class of TimeDisplayTimerTask
private class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast at every 10 second
//String displayingText = "ABC";
String displayingText = myIntent.getStringExtra("PassToService");
final Toast Notify = Toast.makeText(getApplicationContext(), displayingText, Toast.LENGTH_SHORT);
Notify.setGravity(Gravity.CENTER, 0, 0);
Notify.show();
Handler cancelToast = new Handler();
cancelToast.postDelayed(new Runnable() {
#Override
public void run() {
Notify.cancel();
}
}, 1000);
}
});
}
}
}
You can do it by passing value from activity to service-
startService(new Intent(YourActivity.Service.class).putExtra("key","value"));
I have designed a splash screen with a button. The Java code is as below. The layout of the splash contains some texts with animation and button named skipped splash screen. When the user presses the button, the splash screen has to stop immediately and open the next activity. But when I open the splash screen and press skip button, the next activity opens but after the duration for which splash screen has to run gets over, again the activity opens. How to stop the splash screen when a user presses the skip button?
public class Qz1 extends Activity {
TextView a;
TextView b;
TextView c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qz1);
a =(TextView)findViewById(R.id.roundOnea22);
a.startAnimation(AnimationUtils.loadAnimation(Qz1.this, R.anim.anim_slide_in_left));
b =(TextView)findViewById(R.id.roundOneb);
b.startAnimation(AnimationUtils.loadAnimation(Qz1.this, R.anim.anim_slide_in_right));
c =(TextView)findViewById(R.id.roundme);
c.startAnimation(AnimationUtils.loadAnimation(Qz1.this, R.anim.anim_slide_in_left));
Thread thread = new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
try{
sleep(3200);
startActivity(new Intent(getApplicationContext(), Qone.class));
} catch (InterruptedException e){
e.printStackTrace();
}
}
};
thread.start();
}
public void round1(View v){
Intent i = new Intent(Qz1.this, Qone.class);
startActivity(i);
}
}
Let's suppose you want to keep your first activity in the background, but you do not want the thread to re-open the second activity as soon as it has finished sleeping.
In order to achieve that, you can make your "thread" a global variable of a custom Thread class. You can define this as an inner class of your activity:
MyThread thread;
and the class definition:
private class MyThread extends Thread
{
public boolean bRun = true;
#Override
public void run()
{
try
{
sleep(3200);
if (bRun)
{
startActivity(new Intent(getApplicationContext(), Activity2.class));
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
In onCreate(), you write
thread = new MyThread();
thread.start();
Then you can change your "onClick" method like this:
public void round1(View v){
if (thread != null && thread.isAlive())
{
thread.bRun = false;
}
Intent i = new Intent(Qz1.this, Qone.class);
startActivity(i);
}
This will keep the thread from starting the second activity, if it has been started by clicking the button.
Shouldn't be using sleep(2000)
use an animationlistener (http://developer.android.com/reference/android/view/animation/Animation.AnimationListener.html)
when onAnimationEnd is triggered call startActivity.
I think best practice here would be to use a Handler.
You can do it like this:
public class Test extends AppCompatActivity{
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Settign the splashscreen with the button i suppose
setContentView(R.id.splashcreen);
}
#Override
protected void onStart() {
super.onStart();
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startNextActivity();
}
}, 2000);
}
public void startNextActivity(){
startActivity(new Intent(getApplicationContext(), Qone.class));
}
public void skipSplashScreen(){
if (handler != null)
handler.removeCallbacksAndMessages(null);
startNextActivity();
}
#Override
protected void onStop() {
super.onStop();
// clear handler on stop
if (handler != null)
handler.removeCallbacksAndMessages(null);
}
}
CAll skipSplashScreen() when user press the button and the handler will stop so the timer stops and you go to next activity manually by calling method startNextActivity().
It's best practice to use Async Tasks for wait/sleep scenarios, such as for splash screens, but requirements can differ.
Anyway this is my way to call a splash screen:
Create the AsyncTask first.
private class SplashTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
finish();
Intent intent = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(intent);
}
}
}
Then call this where ever you want: on button click, on start, or on create:
new SplashTask().execute();
try this in the splash activity
Button button = (Button)findViewById(R.id.buttonLayout);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(this,TargetActivity.class));
finish();
}
});
I have some pretty standard code to run an MP3, but it takes like 2 seconds to play it. This app is very simple. This app should play a 1-2 second sound. Also, is there a way to buffer the mp3 at app's load into the RAM or something so it can play very quickly(w/o delay)? Please help!
import android.content.Context;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity1 extends ActionBarActivity {
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity1);
}
public void playSound(View v)throws Exception{
mediaPlayer = MediaPlayer.create(this, R.raw.john_cena);
mediaPlayer.setLooping(false);
mediaPlayer.start();
Thread.sleep(1500);
//mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
Log.d("1234FIND", "STOP RELEASE RESET");
}
}
If you want to avoid the slight delay as the media file is loaded, you should prepare your media player instance ahead of time. There's a delay while your media file is loaded and prepared for playback. You have a few options:
Continue to use MediaPlayer.create(), but do so sooner, before you're ready to call playSound(). In the simple example you provided, try calling MediaPlayer.create() in the onCreate() method.
You could also use the prepareAsync() and setOnPreparedListener() methods to prepare the media file in the background and set a notification when it is ready. This is more complicated but provides you with more control and a better user experience. If you need to load a large file, this is the best way to make it work. Small audio files probably aren't as big of a deal.
If you're going to play the same media file over and over again, you don't need to release the MediaPlayer right away. If you don't reset or release, the media will still be in memory and can play again immediately. But be sure to call release() when you're definitely done, and in the lifecycle events such as onPause() or onStop().
See the documentation for details.
To get it to play for a few seconds and then stop, use Android's CountDownTimer:
// Will call onFinish() after 2 seconds. Second parameter is
// for onTick() which we don't need and can ignore.
new CountDownTimer(2000, 2000) {
public void onTick(long millisUntilFinished) {
// Do nothing...
}
public void onFinish() {
mediaPlayer.stop();
// Decide here if you need to prepare a new clip
// or release the media player
}
}.start();
Here is a complete example:
package com.example.matthew.somediaplayer;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "TEST";
private MediaPlayer mediaPlayer;
private boolean isMediaPlayerPrepared = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setEnabled(false);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying() == false) {
playSound();
}
}
});
}
#Override
public void onResume(){
super.onResume();
Log.d(TAG, "In onResume()");
createAndPrepareMediaPlayer();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "In onStop()");
mediaPlayer.release();
isMediaPlayerPrepared = false;
}
#Override
public void onPause(){
Log.d(TAG, "In onPause()");
super.onPause();
}
public void createAndPrepareMediaPlayer() {
Log.d(TAG, "In createAndPrepareMediaPlayer()");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if(isMediaPlayerPrepared == false) {
try {
AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.test);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Media player is prepared.");
isMediaPlayerPrepared = true;
Button button = (Button) findViewById(R.id.button);
button.setEnabled(true);
}
});
Log.d(TAG, "Beginning to prepare media player.");
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void playSound() {
Log.d(TAG, "In playSound()");
if( isMediaPlayerPrepared ) {
// Will call onFinish() after 2 seconds. Second parameter is
// for onTick() which we don't need and can ignore.
new CountDownTimer(2000, 2000) {
public void onTick(long millisUntilFinished) {
// Do nothing...
}
public void onFinish() {
Log.d(TAG, "In onFinish()");
// We can't call a method like pause on an unprepared MediaPlayer instance.
if( isMediaPlayerPrepared ) {
mediaPlayer.pause();
} else {
Log.d(TAG, "Media player isn't prepared, and isn't allowed to pause.");
}
}
}.start();
mediaPlayer.setLooping(false);
mediaPlayer.seekTo(0); // set to beginning of track (if not already)
mediaPlayer.start();
Log.d(TAG, "Starting to play a sound.");
}
}
}
I need to return the value from my countdowntimer so I can update a textView. I'm not sure how I can do this, I've added a comment where I've tried adding a return but no luck.
public class BrewTimer extends Activity{
public String secsRemain = "not set";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("Timer Created, we're in the onCreate Method.");
}
public void startBrewTimer(long remaningMillis) {
// Start the Brew Timer
System.out.println("Timer object fired!");
new CountDownTimer(remaningMillis, 1000) {
public void onTick(long millisUntilFinished) {
secsRemain = "seconds remaining: " + millisUntilFinished / 1000;
System.out.println(secsRemain);
return secsRemain; // <-- This is what I want to do
}
public void onFinish() {
System.out.println("Timer Finished!!!");
}
}.start();
}
public void stopBrewTimer() {
//Stop the Brew Timer
}
}
I need to return the value from my countdowntimer so I can update a
textView.
There is no need to do that. It runs on the ui thread. You can update textview in onTick itself.
Example:
public class MainActivity extends Activity {
TextView tv;
public String secsRemain = "not set";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
startBrewTimer(200000);
}
private void startBrewTimer(long remaningMillis){
CountDownTimer counter = CountDownTimer(remaningMillis, 1000){
public void onTick(long millisUntilDone){
secsRemain = "seconds remaining: " + millisUntilFinished / 1000;
tv.setText(secsRemain);
}
public void onFinish() {
tv.setText("DONE!");
}
}.start();
}
}
You can get values through broadcast receiver......as follows,
First create your own IntentFilter as,
Intent intentFilter=new IntentFilter();
intentFilter.addAction("YOUR_INTENT_FILTER");
Then create inner class BroadcastReceiver as,
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
/** Receives the broadcast that has been fired */
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction()=="YOUR_INTENT_FILTER"){
//HERE YOU WILL GET VALUES FROM BROADCAST THROUGH INTENT EDIT YOUR TEXTVIEW///////////
String receivedValue=intent.getStringExtra("KEY");
}
}
};
Now Register your Broadcast receiver in onResume() as,
registerReceiver(broadcastReceiver, intentFilter);
And finally Unregister BroadcastReceiver in onDestroy() as,
unregisterReceiver(broadcastReceiver);
Now the most important part...You need to fire the broadcast from wherever you need to send values..... so do as,
Intent i=new Intent();
i.setAction("YOUR_INTENT_FILTER");
i.putExtra("KEY", "YOUR_VALUE");
sendBroadcast(i);
don't forget to accept my answer if you find this ans satisfactory....cheers :)
I have the following code:
package com.example.top_tech_deals;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.VideoView;
public class Splash extends Activity{
#Override
protected void onCreate(Bundle TravisLoveBacon) {
// TODO Auto-generated method stub
super.onCreate(TravisLoveBacon);
setContentView(R.layout.splash);
VideoView vv = (VideoView)this.findViewById(R.id.videoView);
String fileName = "android.resource://" + getPackageName() + "/" + R.raw.splashvid2;
vv.setVideoURI(Uri.parse(fileName));
vv.start();
Thread timer = new Thread(){
public void run(){
try{
sleep(12000);
} catch(InterruptedException e){
e.printStackTrace();
} finally{
Intent openStartingPoint = new Intent ("android.intent.action.MENU");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
//Function that will handle the touch
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
synchronized(timer){
splashTread.notifyAll();
}
}
return true;
}
}
By using one of Bucky's tutorials I managed to create the above code which is used to create a splash screen for 12 seconds. I also modified it so that a Video will play. The main problem I'm having is with the last bit of the code which is the OnTouchEvent I found online. What it should do is allow the user to skip the splash screen simply by tapping the screen, which should take the user to the MENU file.
The error seems to be in this line:
synchronized(timer){
Which says "error timer cannot be resolved into a variable"
Why is this happening and how can I fix it? Thanks for the help.
See code:
package com.example.top_tech_deals;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.VideoView;
public class Splash extends Activity{
Thread timer;
#Override
protected void onCreate(Bundle TravisLoveBacon) {
// TODO Auto-generated method stub
super.onCreate(TravisLoveBacon);
setContentView(R.layout.splash);
VideoView vv = (VideoView)this.findViewById(R.id.videoView);
String fileName = "android.resource://" + getPackageName() + "/" + R.raw.splashvid2;
vv.setVideoURI(Uri.parse(fileName));
vv.start();
timer = new Thread(){
public void run(){
try{
synchronized (this) {
wait(12000);
}
} catch(InterruptedException e){
e.printStackTrace();
} finally{
Intent openStartingPoint = new Intent ("android.intent.action.MENU");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
//Function that will handle the touch
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
synchronized(timer){
timer.notify();
}
}
return true;
}
}
Your timer variable is local to your onCreate() method, but you're trying to access it (via synchronized) in a different method -- so it is unresolved. You need to either move timer to being a class data member, or use some other object whose scope is available in your onTouchEvent() method.
User a count downTimer instead of using a thread and in the override method onFinish()
CountDownTimer countDownTimer = new CountDownTimer(12000, 1000) {
public void onTick(long millisUntilFinished) {
//ToDO
}
public void onFinish() {
Intent openStartingPoint = new Intent ("android.intent.action.MENU");
startActivity(openStartingPoint);
}
}.start();
and in onTouch()
#Override
public boolean onTouchEvent(MotionEvent event) {
startActivity(openStartingPoint);
countDownTimer.cancle();
return true;
}
It seems your timer variable is not declare at class scope,it is declared in onCreate() function thats why other methods are not able to get it by reference. I suggest declare this as class variable like this private Thread timer = null; and initialize it in oncreate() method
#Override
protected void onCreate(Bundle TravisLoveBacon) {
// TODO Auto-generated method stub
super.onCreate(TravisLoveBacon);
setContentView(R.layout.splash);
VideoView vv = (VideoView)this.findViewById(R.id.videoView);
String fileName = "android.resource://" + getPackageName() + "/" + R.raw.splashvid2;
vv.setVideoURI(Uri.parse(fileName));
vv.start();
this.timer = new Thread(){
public void run(){
try{
sleep(12000);
} catch(InterruptedException e){
e.printStackTrace();
} finally{
Intent openStartingPoint = new Intent ("android.intent.action.MENU");
startActivity(openStartingPoint);
}
}
};
timer.start();
}