My app has a TextView
and a button, when I touch the button it starts the countdown. The problem is that when I close the application and reopen it, the countdown does not continue. How can I make it continue? I tried with Shared
Preferences
but it only saves the final value.
My code:
public class MainActivity extends Activity {
Button b1;
TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
b1 = (Button) findViewById(R.id.b1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu
// this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void a(View view){
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
tv1.setText("La cuenta llega a 0 en: " + millisUntilFinished / 1000);
}
public void onFinish() {
tv1.setText("Listo!");
}
}.start();
}
}
I think I just answered another question about how to save a value in
SharedPreferences
, so I hope that both answers will help you. I explain:In order for the countdown of your application to continue, even when the application is completely stopped, that is, it does not exit when you press the button where all the applications that are running even if you do not have them open, you must create a Service and You can create two types of services:
It is difficult to understand 100% the
Servicios
. I haven't managed to master them yet, but here are some guides with which I could implement my firstService
:Tutorial To Create A Service In Android
Example of Service in Android: A stopwatch
In addition, combining them
Services
with the classCountDownTimer
that is used just to create a countdown, you will have more than enough. I explain this class:For it to run you need the following code:
With this code we create one
CountDownTimer
that performs a countdown of 20s (20000 milliseconds) and notifies every second (1000 milliseconds). This class needs to override two methods:The
Services
is a bit confusing, I'm telling you, but I hope that by combining this, you can get what you need.Good luck and if you need anything, leave a comment.
Good luck with your App!!
In
onCrate()
it add thisand remove the method
a(View view)
If that doesn't work, add your layout to the question
activity_main
for the full picture.