A
A
amimamoya2021-04-18 11:12:31
Java
amimamoya, 2021-04-18 11:12:31

How to continue the application from the place that was before it was closed?

Initially, there is only one button in my application, when you click on it, the text on it changes and a TextView appears with the current time and is updated every second. How can I make it so that if the button is pressed and after the application is closed, the next time it is launched, the current time is already displayed without pressing the button?
Here is the xml code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat 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="wrap_content"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_marginLeft="150dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/label2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/but"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="125dp"
        android:text="Начать!"
        android:onClick="butpress"/>

</androidx.appcompat.widget.LinearLayoutCompat>

java code:
public class MainActivity extends AppCompatActivity {
    TextView label;
    Button but;
    private Handler handler;
    boolean prov = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        but = (Button) findViewById(R.id.but);
        label = (TextView) findViewById(R.id.label2);
        handler = new Handler(){
            public void handleMessage(Message msg){
                String time = new SimpleDateFormat("kk:mm:ss").format(Calendar.getInstance().getTime());
                label.setText(time);
            }
        };
    }

    public void butpress(View view){
        String time = new SimpleDateFormat("YYYY-MM-dd").format(Calendar.getInstance().getTime());
        but.setText("Остановить");
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (prov) {
                    handler.sendEmptyMessage(1);
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        System.out.println(e);
                    }
                }
            }
        });
        t.start();
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
foonfyrick, 2021-04-18
@foonfyrick

Save the time in the database, take the value from there at startup.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question