How to change images in imageview every n number of seconds - java

I have made an array that has all the images in int and i want to change those images every 3 seconds in the imageView, I have tries all the solutions I could find but was showing some error, I can't figure it out .
java file (home.java)
/**
* Created by sukhvir on 17/04/2015.
*/
public class home extends android.support.v4.app.Fragment {
ImageView MyImageView;
int[] imageArray = { R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5 };
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Inflate the layout for this fragment
*/
return inflater.inflate(R.layout.home, container, false);
}
}
xml file(home.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_gravity="center_horizontal" />
</LinearLayout>

Best option to achieve your requirement is You should use Timer to change Image each of 3 seconds as follows.
// Declare globally
private int position = -1;
/**
* This timer will call each of the seconds.
*/
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
// As timer is not a Main/UI thread need to do all UI task on runOnUiThread
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// increase your position so new image will show
position++;
// check whether position increased to length then set it to 0
// so it will show images in circuler
if (position >= imageArray.length)
position = 0;
// Set Image
MyImageView.setImageResource(imageArray[position]);
}
});
}
}, 0, 3000);
// where 0 is for start now and 3000 (3 second) is for interval to change image as you mentioned in question

use a CountDownTimer here is how: How to make a countdown Timer in android?
and change the image view background inside onFinish().
hope this will work out for you

first define a runnable
private Runnable runnable = new Runnable() {
#Override
public void run() {
changeImage(pos);
}
};
Than create a handler
private Handler handler;
handler = new Handler(Looper.getMainLooper());
In your changeImage method
private void changeImage(int pos) {
yourImageView.setImageResource(imageArray[pos]);
handler.postDelayed(runnable, duration);
}
Start and stop runnable with:
handler.postDelayed(runnable, duration);
handler.removeCallbacks(runnable);
I hope this'll help you. Good luck.

Related

Trying to make a basic counter using scheduled executor service

I'm new to java and was trying to make a simple android app that does the following:
display a window in the main activity
every second the value of integer i is increased by 1
update the window content to display the value of i every second
for example the window should display the following text:
1st second: "update 1"
2nd second: "update 2"
3rd second: "update 3"
...
etc
I learned that using java's ScheduledExecutorService with ScheduleAtFixedRate is better than implementing an infinite loop, so I attempted the following code:
public class MainActivity extends AppCompatActivity {
public FrameLayout mLayout;
public WindowManager wm;
public WindowManager.LayoutParams lp;
public int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// display a window saying "hello"
wm = (WindowManager) getSystemService(WINDOW_SERVICE);
mLayout = new FrameLayout(this);
lp = new WindowManager.LayoutParams();
lp.format = PixelFormat.TRANSLUCENT;
lp.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
LayoutInflater inflater = LayoutInflater.from(this);
inflater.inflate(R.layout.text_bubble, mLayout);
((TextView) mLayout.findViewById(R.id.text)).setText("hello");
wm.addView(mLayout, lp);
//creating a scheduled executor service, it runs the method "myTask" at fixed rate of 1 second
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
myTask();
}
}, 0, 1, TimeUnit.SECONDS);
}
private void myTask() {
Log.v(TAG,"Running");
//Increment i by 1 and update the window layout
i = i + 1;
((TextView) mLayout.findViewById(R.id.text)).setText("update " + i);
wm.updateViewLayout(mLayout, lp);
}
}
When I start the app it does display the window as intended, but it doesn't update the number every second, instead it only shows "update 1". I can't tell why as I didn't get any errors. After some trial and error I found that when I remove the last two lines from the myTask method (the lines responsible for updating the text of the window layout):
((TextView) mLayout.findViewById(R.id.text)).setText("update " + i);
wm.updateViewLayout(mLayout, lp);
when I remove these two lines the executor service will function just fine, and I can see that by watching the logged text message "running" popping every second. but when I add those two lines again, it doesn't pop these messages anymore(except for the first second).
so what am I doing wrong here? I thought the problem could be about the the way I update the layout maybe. what am I missing here?
Try this:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
//Your stuff
}
}, 0, 1000);
Or this using the scheuldedServiceExecutor:
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(() -> {
//Your stuff
}, 1, 5, TimeUnit.SECONDS);

Why does my CountDownTimer seem to be going backward?

I'm trying to make an app that reminds you to charge your phone if it is not used for a while. It works like this: you enter how long the phone should be idle before it reminds you. Then it starts a timer and reminds you when it finishes.
Here's my MainActivity.Java:
public class MainActivity extends AppCompatActivity {
//Defining UI elements
public Button changeAppStateButton;
public TextView minsEditText;
//App variables
boolean isAppRunning = false;
public int secondsPhoneIsAsleep;
public int timerDuration = secondsPhoneIsAsleep * 1000; //multiplying seconds by 100 to get milliseconds
public int tickDuration = 60000; //multiplying seconds (1) by 100 to get milliseconds
//Called when button is pressed
public void changeAppState(View view) {
Button changeAppStateButton = (Button) view;
if (isAppRunning) { //If the app is running, stop app
isAppRunning = false;
changeAppStateButton.setBackgroundColor(getColor(R.color.colorPurple));
changeAppStateButton.setText("Start Reminder");
timer.cancel();
Log.i("TIMER", "Timer interrupted");
} else { //If the app is not running, start app
secondsPhoneIsAsleep = Integer.parseInt(minsEditText.getText().toString()) * 60;
isAppRunning = true;
changeAppStateButton.setBackgroundColor(getColor(R.color.colorRed));
changeAppStateButton.setText("Stop Reminder");
timer.start();
Log.i("TIMER", "Timer started");
}
}
public CountDownTimer timer = new CountDownTimer(timerDuration, tickDuration) {
#Override
public void onTick(long millisUntilFinished) {
Log.i("TIMER", "tick");
}
#Override
public void onFinish() {
isAppRunning = false;
changeAppStateButton.setBackgroundColor(getColor(R.color.colorPurple));
changeAppStateButton.setText("Start Reminder");
Log.i("TIMER", "Timer finished");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setting values for UI elements
changeAppStateButton = findViewById(R.id.changeAppStateButton);
minsEditText = findViewById(R.id.minEditText);
}
This is part of my XML:
<EditText
android:id="#+id/minEditText"
android:layout_width="59dp"
android:layout_height="42dp"
android:layout_marginTop="14dp"
android:ems="10"
android:foregroundTint="#FF0000"
android:inputType="number"
android:text="30"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="20sp"
app:layout_constraintStart_toEndOf="#+id/whenUntouched"
app:layout_constraintTop_toBottomOf="#+id/numberEditText" />
<Button
android:id="#+id/changeAppStateButton"
android:layout_width="0dp"
android:layout_height="45dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="110dp"
android:background="#9C27B0"
android:fontFamily="#font/alegreya_sans_sc"
android:onClick="changeAppState"
android:text="Start Reminder"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
This is logcat when I press the button:
I/DEV_TIMER: Timer finished
I/DEV_TIMER: Timer started
Why does the timer seem to be going backward? Why isn't it logging a message every "tick"?
Some explanation would be highly appreciated. I'm not too experienced with Android and Java.
Since the code specified in MainActivity.java
Doesn't initialize variable secondsPhoneIsAsleep, so the default value will be 0.
So timerDuration will be 0.
So timer is created to count for a duration of 0.
So when the button is clicked, even though you read new value for secondsPhoneIsAsleep, invoking timer.start() will cause it to count only till 0 based on the earlier initialized value.
Hence onFinish() gets called logging Timer finished, then the Timer started gets logged as part of button click code.
Solution
If you create timer instance on button click then it should use the correct value of secondsPhoneIsAsleep and work properly. Like below:
MainActvity.java
public class MainActivity extends AppCompatActivity {
//Defining UI elements
public Button changeAppStateButton;
public TextView minsEditText;
//App variables
boolean isAppRunning = false;
public int secondsPhoneIsAsleep;
public CountDownTimer timer;
public int timerDuration;
public int tickDuration = 1000; //multiplying 1 second by 1000 to get milliseconds
//Called when button is pressed
public void changeAppState(View view) {
Button changeAppStateButton = (Button) view;
if (isAppRunning) { //If the app is running, stop app
isAppRunning = false;
changeAppStateButton.setBackgroundColor(getColor(R.color.colorPurple));
changeAppStateButton.setText("Start Reminder");
timer.cancel();
Log.i("TIMER", "Timer interrupted");
} else { //If the app is not running, start app
secondsPhoneIsAsleep = Integer.parseInt(minsEditText.getText().toString()) * 60;
timerDuration = secondsPhoneIsAsleep * 1000;
timer = getNewTimer(); // Creates a new timer.
isAppRunning = true;
changeAppStateButton.setBackgroundColor(getColor(R.color.colorRed));
changeAppStateButton.setText("Stop Reminder");
timer.start();
Log.i("TIMER", "Timer started");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setting values for UI elements
changeAppStateButton = findViewById(R.id.changeAppStateButton);
minsEditText = findViewById(R.id.minEditText);
}
private CountdownTimer getNewTimer() {
return new CountDownTimer(timerDuration, tickDuration) {
#Override
public void onTick(long millisUntilFinished) {
Log.i("TIMER", "tick");
}
#Override
public void onFinish() {
isAppRunning = false;
changeAppStateButton.setBackgroundColor(getColor(R.color.colorPurple));
changeAppStateButton.setText("Start Reminder");
Log.i("TIMER", "Timer finished");
}
};
}

Using the camera in android

I am trying to build an Android app that simply uses the camera to take a picture without launching the default camera app. In other words, I want to make a custom camera app. I can do this using the Camera hardware object class, however this is deprecated and I want to use some of the new features of camerax and not have to worry about the code not working after some time. I have also read the camera API documentation, however it is still unclear how to use the camera. Are there any very simple step by step tutorials or guides that might help me?
Thanks,
You can check my example about how to use AndroidX libraries and TextureView for camera customization.
https://github.com/icerrate/Custom-Camera-App
First at all, define your layout. This is my activity_main.xml file:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextureView
android:id="#+id/view_finder"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/take_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_margin="#dimen/horizontal_margin"
app:layout_constraintStart_toStartOf="parent"
android:src="#drawable/ic_camera"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Remember that TextureView will receive the camera preview and the Floating Action Button works as a "Take Photo" button.
Then add your MainActivity.java file:
public class MainActivity extends AppCompatActivity implements LifecycleOwner {
private static final int RC_PERMISSIONS = 100;
private TextureView viewFinder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
viewFinder = findViewById(R.id.view_finder);
FloatingActionButton takePhotoFab = findViewById(R.id.take_photo);
//Check permissions
if (allPermissionGranted()) {
viewFinder.post(new Runnable() {
#Override
public void run() {
startCamera();
}
});
} else {
ActivityCompat.requestPermissions(this,
new String[] {Manifest.permission.CAMERA}, RC_PERMISSIONS);
}
takePhotoFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePhoto();
}
});
}
private void startCamera() {
Point screenSize = getScreenSize();
int width = screenSize.x;
int height = screenSize.y;
//Get real aspect ratio
DisplayMetrics displayMetrics = new DisplayMetrics();
Display display = getWindowManager().getDefaultDisplay();
display.getRealMetrics(displayMetrics);
Rational rational = new Rational(displayMetrics.widthPixels, displayMetrics.heightPixels);
//Build the camera preview
PreviewConfig build = new PreviewConfig.Builder()
.setTargetAspectRatio(rational)
.setTargetResolution(new Size(width,height))
.build();
Preview preview = new Preview(build);
preview.setOnPreviewOutputUpdateListener(new Preview.OnPreviewOutputUpdateListener() {
#Override
public void onUpdated(Preview.PreviewOutput output) {
ViewGroup group = (ViewGroup) viewFinder.getParent();
group.removeView(viewFinder);
group.addView(viewFinder, 0);
viewFinder.setSurfaceTexture(output.getSurfaceTexture());
}
});
CameraX.bindToLifecycle(this, preview);
}
private void takePhoto() {
Toast.makeText(this, "Shot!",
Toast.LENGTH_SHORT).show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == RC_PERMISSIONS) {
if (allPermissionGranted()) {
viewFinder.post(new Runnable() {
#Override
public void run() {
startCamera();
}
});
} else {
Toast.makeText(this, "Permission not granted",
Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionGranted() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
}
private Point getScreenSize() {
Display display = getWindowManager(). getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size;
}
}
In this class, you would be able to send the camera preview to the TextureView, with help of PreviewConfig.Builder() and binding it to the Activity lifeCycle using CameraX.bindToLifeCycle()
Also, don't forget to add Camera permission to the manifest and consider runtime permissions.
Screenshot:
Custom Camera preview
Hope this help you!

Text Animation and Background change

I'm stuck and need help.
How can I add animations like on the picture. I want the color of the background and text to be smoothly automatically changed 1 sec after the app is launched. And to be like a cycle. Meanwhile an icon is impulsing.
You can use Property Animation for changing color
int colorFrom = getResources().getColor(R.color.red);
int colorTo = getResources().getColor(R.color.blue);
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.setDuration(500); // milliseconds
colorAnimation.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animator) {
textView.setBackgroundColor((int) animator.getAnimatedValue());
}
});
colorAnimation.start();
Use alpha animations to fade in and out the textchanging So on repeat is when it is fading back in so you can update the text at that time
AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
anim.setDuration(500);
anim.setRepeatCount(1);
anim.setRepeatMode(Animation.REVERSE);
txtLabel.startAnimation(anim);
anim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
txtLabel.setText("my next Text"); //for fading back in
}
});
You can use the same animation for alpha on a bitmap or imageView to pulse in and out as well.
AlphaAnimation animPulse = new AlphaAnimation(1.0f, 0.0f);
animPulse.setDuration(500);
animPulse.setRepeatCount(Animation.INFINITE);
animPulse.setRepeatMode(Animation.REVERSE);
imgPulse.startAnimation(animPulse);
Then of course just put in your
public void onCreate(){
Handler mMainHandler = new Handler(Looper.prepareMainLooper());
mMainHandler.postDelay(new Runnable(){
doAnimations();
}, 1000);
}
Then simply lump all your animations into methods and call them from doAnimations. Good luck.
Here you go..
I did the code to change color of background layout and text. Currently I did for random colors, if you need pre-defined colors, please let me know. Below is my code
activity_main.xml
`
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.golevr.background_animation.MainActivity"
android:id="#+id/constraint">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
`
MainActivity.java
`
public class MainActivity extends AppCompatActivity {
// Move your declarations here if you intend on using them after the onCreate() method
ConstraintLayout layout;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Inflate your objects
layout = (ConstraintLayout) findViewById(R.id.constraint);
textView = (TextView) findViewById(R.id.textView);
// We change the color to RED for the first time as the program loads
layout.setBackgroundColor(Color.RED);
// We change the color to GREEN for the first time as the program loads
textView.setTextColor(Color.GREEN);
// Create the timer object which will run the desired operation on a schedule or at a given time
Timer timer = new Timer();
// Create a task which the timer will execute. This should be an implementation of the TimerTask interface.
// I have created an inner class below which fits the bill.
MyTimer myTimer = new MyTimer();
// We schedule the timer task to run after 1000 ms and continue to run every 1000 ms.
timer.schedule(myTimer,1000,1000);
}
// An inner class which is an implementation of the TImerTask interface to be used by the Timer.
class MyTimer extends TimerTask{
#Override
public void run() {
// This runs in a background thread.
// We cannot call the UI from this thread, so we must call the main UI thread and pass a runnable
runOnUiThread(new Runnable() {
#Override
public void run() {
Random rand = new Random();
// The random generator creates values between [0,256) for use as RGB values used below to create a random color
// We call the RelativeLayout object and we change the color. The first parameter in argb() is the alpha.
layout.setBackgroundColor(Color.argb(255, rand.nextInt(256),rand.nextInt(256),rand.nextInt(256)));
textView.setTextColor(Color.argb(222,rand.nextInt(222),rand.nextInt(222),rand.nextInt(222)));
}
});
}
}
}
`
Is this what you want?

Creating a Singleton CountDownTimer in Android

I'm a beginner in android and I've written an activity. It contains a CountDownTimer that counts down from a particular value. It also contains a Button that loads text information and a textview to display count.
Below is the code for Activity1:
public class Screen extends Activity1 implements OnClickListener {
private static final int MILLIS_PER_SECOND = 1000;
private static final int SECONDS_TO_COUNTDOWN = 1;
TextView Time;
int totaltime;
Button startTimer, howTo, pause;
protected CountDownTimer MyTimer;
int PracticeCount;
long tot;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.pushupscreen);
getRefs();
getSpeed();
getCount();
setTotalTime();
startTimer.setOnClickListener(this);
pause.setOnClickListener(this);
}
private void getRefs() {
// Initialize layout resources
Time = (TextView) findViewById(R.id.tvTime);
startTimer = (Button) findViewById(R.id.bStart);
howTo = (Button) findViewById(R.id.btHowTo);
pause = (Button) findViewById(R.id.bPause);
howTo.setOnClickListener(this);
}
private void getTheCount() {
//get count from SharedPreferences
}
private void getSpeed() {
//get speed from SharedPreferences
}
private void setCount(){
totalTime=speed*count;}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == startTimer) {
try {
showTimer(time);
} catch (NumberFormatException e) {
// method ignores invalid (non-integer) input and waits
// for something it cant use
}
} else if (v == pause) {
MyTimer.cancel();
Timer.setText("Resume");
} else if (v == howTo) {
//Launch screen containing information
}
}
private void showTimer(long time) {
if (MyTimer != null) {
MyTimer.cancel();
}
MyTimer = new CountDownTimer(tot2, MILLIS_PER_SECOND) {
#Override
public void onTick(long millisUntilFinished) {
tot = millisUntilFinished;
long seconds = millisUntilFinished / 1000;
Time.setText(String.format("%02d", seconds / 60) + ":"
+ String.format("%02d", seconds % 60));
}
#Override
public void onFinish() {
Time.setText("KABOOM!");
}
}.start();
}
}
And here is the layout file for this:
<TextView
android:id="#+id/tvTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:gravity="center"
android:padding="10dip"
android:text="#string/starttime"
android:textSize="60sp" />
<Button
android:id="#+id/bStart"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_above="#+id/tvTime"
android:text="Start" />
<Button
android:id="#+id/bPause"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_above="#+id/tvTime"
android:layout_toRightOf="#+id/btHowTo"
android:text="Pause" />
<TextView
android:id="#+id/tvCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btHowTo"
android:layout_centerHorizontal="true"
android:layout_marginTop="39dp"
android:text="25"
android:textSize="80sp"
android:textAlignment="center"/>
My questions:
1.How do I create 4 activities that use the same layout and the same timer? Each Activity loads a different content in the textview and a different screen on the click of HowTo button.
2.How can Activity1 be designed to run for 1/4th the time set and pass remaining time to Activity2? Is it possible?
I would really appreciate any help and advice that you can provide. Thanks.
A couple things here.
Its very easy to re-use layouts. In each activity's onCreate you would just call:
setContentView(R.layout.pushupscreen); The pushupscreen.xml file can be shared across all activities this way.
What you probably want to do is persist a timestamp to some common data source for all the activities. This could be a write to a SharedPreferences file: Documentation here. Then as each activity resumes, check how much time has already passed by comparing this timestamp to the current timestamp. You could also pass the timestamp as an extra in the intent to start up the subsequent activities. The documentation for that can be found here and here
You could make a custom control, which is basically a new class which inherits some other control's class (for example a LinearLayout or a RelativeLayout). You could then load a view's XML to your new layout or programmatically create new controls inside your control. More info here:
Custom components in Android
After a 1/4 of your countdown period, you can create and send an Intent to start a new activity in the onTick method. You can also put the remaining 3/4 as a millisecond value (of type long) in an intent extra. You can then obtain this value in the new activity and invoke a custom CountDownTimer child there for the rest of your countdown. Then you can finally execute what you wish after the countdown is done in the onFinish() method.

Categories