I want to create a countdown such that when the app is completely closed, the countdown timer is paused and saved. When the app is opened again, the countdown resumes where it left off.
My idea was to save the value "millisUntilFinished" in the "onStop" when the app is closed and in the "onResume" continue the countdown when the app is opened.
The problem is that I don't know how to do it, someone help me?
The code of my countdown:
public class MainActivity extends Activity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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();
}
Use SharedPreferences.
onResume(){
SharedPreferences prefs =
getSharedPreferences("PREF_NAME", MODE_PRIVATE);
int startTime = prefs.getInt("PAUSED_TIME", 0); //0 is the default value.
}
onPause(){
SharedPreferences.Editor editor =
getSharedPreferences("PREF_NAME", MODE_PRIVATE).edit();
editor.putInt("PAUSED_TIME", time);
editor.commit();
}
Related
i want that my countdown continue when i completely close the app but i dont know how to do it. Someone can explain it to me or pass me some link where explain it? Thank
The code for the countdown
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();
}
}
You need to do following steps :
At the exit point of your app(either it is onBackPress of Home Activity or Ok click of the dialog that ask for exit) find the value of System.currentTimeMillis() and save it to SharedPrefences.
Now on second launch(in onCreate()) just find again value of System.currentTimeMillis(), then get the data saved in SharedPrefences and get the diff. of both values.
Now the diff is the time period that your app was shut down, hope you are looking for the same data.
I have an main activity that opens a child activity:
startActivity(new Intent(this, ChildActivity.class));
From within the child activity, I press the Back button to return back to the main activity. I also have this code in the main activity:
#Override
protected void onResume() {
super.onResume();
dosomething();
}
However, onResume is never reached.
Am I missing something?
This way, it's calling onResume() when you go back from child Activity to parent: Activity:
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView mTextView = (TextView)findViewById(R.id.mTextView);
mTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,ChildActivity.class);
startActivity(intent);
}
});
}
#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
protected void onResume() {
super.onResume();
Toast.makeText(this,"Yes calling",Toast.LENGTH_LONG).show();
}
#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);
}
}
ChildActivity.java
public class ChildActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child);
Toolbar mtooToolbar= (Toolbar)findViewById(R.id.mtoolBar);
setSupportActionBar(mtooToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#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_child, 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;
}
if(id==android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
onResume() is called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.
Always followed by onPause().
Check this link to understand the relationship:
Activity Lifecycle
you can use finish() method to finish your activity.
I can post to Facebook using their sharDialog() pop-up. However, if I want to post a set message on a button click, without having the dialog pop up, how do I go about doing that?
public class MainActivity extends AppCompatActivity {
private ShareDialog share;
private ShareLinkContent content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
content = new ShareLinkContent.Builder().setContentTitle("CURRENT LOCATION").build();
share = new ShareDialog(this);
ImageButton fbBut = (ImageButton) findViewById(R.id.facebook_button);
fbBut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
share.show(content);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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) {
//Opens the settings preferences
Intent settings = new Intent(MainActivity.this, SettingsActivity.class);
MainActivity.this.startActivity(settings);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
}
This is the code that I have so far.
I have a first activity ("Home"), with two buttons: one is called About and leads to activity About and the second is named List and leads to the activity List.
Manifest.xml should be fine, but I get a load of tiny petty errors I can't fix up by myself, regrettably.
Home.class is the following
Public class Home extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Button AboutButton = (Button)findViewById(R.id.About);
AboutButton.setOnClickListener(new View.OnClickListener()){
#Override
public void onClick(View view); {
Intent openAbout = new Intent(Home.this, About.class);
startActivity(openAbout);
}
}
Button ListButton = (Button)findViewById(R.id.List);
ListButton.setOnClickListener(new View.onClickListener());{
#Override
public void onClick(View view); {
Intent openList = new Intent(Home.this, List.class);
startActivity(openList);
}
}
}
#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_home, 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);
}
}
while About.class is like this
public class About extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
Button ReturnButton = (Button)findViewById(R.id.Return);
ReturnButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent returnhome = new Intent(About.this, Home.class);
startActivity(returnhome);
}
public void onClick(View view); {
Intent returnhome = new Intent(About.this, Home.class);
startActivity(returnhome);
}
}
}
#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_about, 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);
}
}
and List is like this:
public class List extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Button ReturnButton = (Button)findViewById(R.id.Return);
ReturnButton.setOnClickListener(new View.OnClickListener()){
#Override
public void onClick(View view) {
Intent returnhome = new Intent(About.this, Home.class);
startActivity(returnhome);
}
}
}
#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_list, 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);
}
}
I get lot of red light bulbs, saying, for instance that ")" or ";" is expected or (worse) onClickListener cannot be resolved
Last but not least: I copied this code online and I was wondering why after "View" there is a "view"; what does it mean?
I copied your code and I see fails everywhere... let me explain you what's going on ...
HOME CLASS
1.- You have to remove the ")"
2.- You don't have to ";" when you call onClick()
3.- When you are don on your onClick() NOW you have to close it, you missed the ");"
AboutButton.setOnClickListener(new View.OnClickListener()){ //<-- Just remove one
#Override
public void onClick(View view); { //<-- Remove this ";"
Intent openAbout = new Intent(Home.this, About.class);
startActivity(openAbout);
}
}//Here goes ");"
4.- The ListButton has the same issues so just fix it as you will fix the first one.
ABOUT CLASS
1.-On this case you have the setOnClickListener() ok, BUT why you have two onClick(View view)? It's not necessary just remove one of them.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
Button ReturnButton = (Button) findViewById(R.id.Return);
ReturnButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent returnhome = new Intent(About.this, Home.class);
startActivity(returnhome);
}
});
}
LIST CLASS
1.-Well in your List class you have made the same error as the first one... Your onClickListener() it's wrong.
2.-Once again you included an unnecessary ")" on new View.OnClickListener() just remove it,
3.-Another fail that I'm seeing is that you are trying to make an Intent but you are refering that you are on About.this and you are NOT. You are on List class so you have ot put List.this because the first parameter refers :
A Context as its first parameter (this is used because the Activity class is a subclass of Context)
More information about Intents
4.- You need to close again the setOnClickListener()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Button ReturnButton = (Button)findViewById(R.id.Return);
ReturnButton.setOnClickListener(new View.OnClickListener()){ //<-- remove one ")"
#Override
public void onClick(View view) {
Intent returnhome = new Intent(About.this, Home.class); //<-- Remove About.this and put List.this
startActivity(returnhome);
}
}//<-- Close the setOnClickListener() with ");"
}
It's okay guy, this is your first question and I'll answer it, but NOW as I've made the favor to take my time and explain to you what was wrong on your code take your time to :
How do I as a question on StackOverflow
Learn some Android basics
And the most IMPORTANT THING
DO NOT COPY PASTE AN INTERNET CODE if you don't know the basics, I mean you can copy paste the code, but you'll face with this problem every time you do this, so first of all read the tutorial, make an examples, and you'll improve every day.
I have tried to retrieve data from Shared Preferences and tried to intent it over to my main activity where I want it to display the score the user got. There are no errors, it just doesn't save the best_score_number_tv or doesn't correctly send it over. I hope there isn't too much wrong :(
Main_Screen
public class Main_Screen extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
getSupportActionBar().hide();
//SETS CUSTOM FONT
TextView main_screen_titleone = (TextView)findViewById(R.id.main_screen_titleone);
TextView main_screen_titletwo = (TextView)findViewById(R.id.main_screen_titletwo);
TextView best_score_tv = (TextView)findViewById(R.id.best_score_tv);
TextView best_score_number_tv = (TextView)findViewById(R.id.best_score_number_tv);
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/LemonMilk.otf");
main_screen_titleone.setTypeface(myCustomFont);
main_screen_titletwo.setTypeface(myCustomFont);
best_score_tv.setTypeface(myCustomFont);
best_score_number_tv.setTypeface(myCustomFont);
//******************;
retrieveBestScore();
}
public void startTheGame(View view){
Intent intent = new Intent(this, press_screen.class);
startActivity(intent);
}
public void retrieveBestScore(){
Intent getBestScore = getIntent();
int BEST_SCORE = getBestScore.getIntExtra("BEST_SCORE", 0);
TextView best_score_number_tv = (TextView)findViewById(R.id.best_score_number_tv);
best_score_number_tv.setText(BEST_SCORE + "");
}
#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__screen, 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);
}
}
press_screen
public class press_screen extends ActionBarActivity {
private int time_left;
private int amountOfTapsNumber;
private int bestScore;
TextView amountOfTaps;
TextView timeLeftNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_press_screen);
getSupportActionBar().hide();
timer.start();
loadInfo();
}
//Create Timer
CountDownTimer timer = new CountDownTimer(21000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftNumber = (TextView) findViewById(R.id.time_left_number_tv);
time_left = Integer.valueOf(timeLeftNumber.getText().toString()) - 1;
timeLeftNumber.setText(time_left + "");
}
#Override
public void onFinish() {
bestScore = amountOfTapsNumber;
TextView best_score_number_tv = (TextView)findViewById(R.id.best_score_number_tv);
Intent sendBestScore = new Intent(press_screen.this, Main_Screen.class);
sendBestScore.putExtra("BEST_SCORE", bestScore);
Intent goBackToMainActivity = new Intent(press_screen.this, Main_Screen.class);
startActivity(goBackToMainActivity);
}
};
#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_press_screen, 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 triggerTapOnMainButton(View view) {
amountOfTaps = (TextView) findViewById(R.id.amount_of_taps);
amountOfTapsNumber = Integer.valueOf(amountOfTaps.getText().toString()) + 1;
amountOfTaps.setText(amountOfTapsNumber + "");
}
public void saveInfo(String key, int bestScore){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putInt("BEST_SCORE", bestScore);
edit.commit();
}
public void loadInfo(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
int BEST_SCORE = sp.getInt("BEST_SCORE", 0);
}
}
If you want to use and Intent you should put the extra in the intent you pass to
startActivity
so
Intent goBackToMainActivity = new Intent(press_screen.this, Main_Screen.class);
goBackToMainActivity.putExtra("BEST_SCORE", bestScore);
startActivity(goBackToMainActivity);
Alternatively you could just save the score from your press_screen activity
after
bestScore = amountOfTapsNumber;
saveInfo("BEST_SCORE", bestScore);
Also, if you are going to pass in a key to save the info, you might consider using it
public void saveInfo(String key, int bestScore){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putInt(key, bestScore);
edit.commit();
}
And when retrieving
public int retrieveInt(String key){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
return sp.getInt(key, 0);
}