It is necessary that the program read the current time of the user, update it every minute. Also, to output time and minutes with the format: HH + n hours: mm + t minutes

Here's how I got the current time:

DateFormat dfh = new SimpleDateFormat("HH:mm"); final String date = dfh.format(Calendar.getInstance().getTime()); 

I tried other methods, but the application either crashed or showed some sort of rubbish. as I tried to update the time:

  Timer timer = new Timer(); timer.schedule(new getTimeEverySecond(), 0, 1000); // ставим Π½Π° Π²Ρ‹ΠΏΠΎΠ»Π½Π΅Π½ΠΈΠ΅ ΠΊΠ°ΠΆΠ΄ΡƒΡŽ сСкунду static class getTimeEverySecond extends TimerTask { public void run() { DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); Date date = new Date(); s = dateFormat.format(date); // ΠΊΠ°ΠΆΠ΄ΡƒΡŽ сСкунду обновляСм ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½ΡƒΡŽ } } 

when trying to do as above, the application wrote a lot of text.

Also, through while (true), but everything was burning red from this.

as I tried to add time:

  Calendar cal = Calendar.getInstance(); // creates calendar cal.setTime(new Date()); // sets calendar time/date cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour cal.getTime(); 

I asked a similar question yesterday, I was advised to get time like this:

 DateTime.now().toLocalDate().toString(DateTimeFormat.forPattern("HH:mm")) DateTime.now().plusHours(1).plusMinutes(10).toString(DateTimeFormat.forPattern("EEEE dd MMMM, YYYY")) 

but when I tried to do this, DateTime and DateTimeFormat were not recognized and the android offered to make a new class / variable / method with such names.

How to make the application constantly update the current time? How to make it so that you can output time in the format HH + n hours: mm + t minutes?

All my fragment code in which I try to implement it is:

 package com.example.itss; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.v4.app.Fragment; import android.text.Layout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.Timer; import java.util.TimerTask; public class PhaseFragment extends Fragment { Button timeToWakeUp0; Button timeToWakeUp1; Button timeToWakeUp2; Button timeToWakeUp3; Button timeToWakeUp4; Button timeToWakeUp5; Button timeToWakeUp6; Button timeToWakeUp7; Button timeToSleep0; Button timeToSleep1; Button timeToSleep2; Button timeToSleep3; Button timeToSleep4; Button timeToSleep5; Button timeToSleep6; Button timeToSleep7; @RequiresApi(api = Build.VERSION_CODES.O) @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.phase_fragment,container, false); DateFormat dfh = new SimpleDateFormat("HH:mm"); final String date = dfh.format(Calendar.getInstance().getTime()); Calendar cal = Calendar.getInstance(); // creates calendar cal.setTime(new Date()); // sets calendar time/date cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour cal.getTime(); DateTime.now().toLocalDate().toString(DateTimeFormat.forPattern("HH:mm")); Timer timer = new Timer(); timer.schedule(new getTimeEverySecond(), 0, 1000); timeToWakeUp0 = v.findViewById(R.id.sleeptime0); timeToWakeUp0.setText(DateTime.now().plusHours(1).plusMinutes(10).toString(DateTimeFormat.forPattern("HH:mm"))); timeToWakeUp1 = v.findViewById(R.id.sleeptime1); timeToWakeUp1.setText(timer + ""); timeToWakeUp2 = v.findViewById(R.id.sleeptime2); timeToWakeUp2.setText(date); timeToWakeUp3 = v.findViewById(R.id.sleeptime3); timeToWakeUp4 = v.findViewById(R.id.sleeptime4); timeToWakeUp5 = v.findViewById(R.id.sleeptime5); timeToWakeUp6 = v.findViewById(R.id.sleeptime6); timeToWakeUp7 = v.findViewById(R.id.sleeptime7); timeToSleep0 = v.findViewById(R.id.wakeuptime0); timeToSleep1 = v.findViewById(R.id.wakeuptime1); timeToSleep2 = v.findViewById(R.id.wakeuptime2); timeToSleep3 = v.findViewById(R.id.wakeuptime3); timeToSleep4 = v.findViewById(R.id.wakeuptime4); timeToSleep5 = v.findViewById(R.id.wakeuptime5); timeToSleep6 = v.findViewById(R.id.wakeuptime6); timeToSleep7 = v.findViewById(R.id.wakeuptime7); timeToWakeUp0.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToWakeUp1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToWakeUp2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToWakeUp3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToWakeUp4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToWakeUp5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToWakeUp6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToWakeUp7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToSleep0.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToSleep1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToSleep2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToSleep3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToSleep4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToSleep5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToSleep6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); timeToSleep7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); return v; } static class getTimeEverySecond extends TimerTask { public void run() { DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); Date date = new Date(); String s = dateFormat.format(date); // ΠΊΠ°ΠΆΠ΄ΡƒΡŽ сСкунду обновляСм ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½ΡƒΡŽ } } } 
  • one
    Where to display something? - Enikeyschik
  • DateTime and DateTimeFormat are the classes of the Joda Time library, before using them this library must be included in the project. You are writing a program for the Android OS, how does the start method of β€œbig” Java - public static void main(String[] args) get in there? - pavlofff
  • on the button in the form of text - Catherine Derkach
  • I just googled how other people do it, copied, pasted, I know that it is very stupid, but I have a deadline after 3 weeks, so I didn’t really go into it, I just tried to make the program work, yes I - Catherine Derkach
  • so it definitely will not work, nor after 3 weeks, never. The Android framework in no way takes into account the presence of the main () method and does not start it when the application starts, but it starts the activation that is specified in the start manifest, which in turn starts its life-cycle methods, as onCreate () .. you can read that then on the development for Android, and then google something more appropriate - pavlofff

1 answer 1

The solution of the problem using the Timer class is not very correct, if only because it will not work exactly at the beginning of every minute, and you, as I understand it, have an alarm clock.

I propose to use the system broadcast notification, which is sent at the beginning of every minute. In our application, we subscribe to it and update the time in widgets when an event occurs.

Also, the button update code is called every minute and it will be good to reduce the number of objects created during this. In particular, static system classes (like System.currentTimeMillis() and TimeUnit ), which do not create objects, are used to obtain time and offset calculation, instead of using the Date , Calendar or JodaTime β€” calculations are not so complicated as to use them here.

All the code looks like this (for simplicity in the example there are only three buttons):

 import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import java.text.SimpleDateFormat; import java.util.concurrent.TimeUnit; public class SomeFragment extends Fragment { Button timer1, timer2, timer3; BroadcastReceiver broadcastReceiver; int timeShifts [][] = { {0, 0}, // смСщСниС Π²Ρ€Π΅ΠΌΠ΅Π½ΠΈ - 0 часов {1, 30}, // смСщСниС Π²Ρ€Π΅ΠΌΠ΅Π½ΠΈ 1 час 30 ΠΌΠΈΠ½ {3, 0} // смСщСниС Π²Ρ€Π΅ΠΌΠ΅Π½ΠΈ 3 часа }; final int HOUR = 0; final int MINUTE = 1; SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm"); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_main, container, false); timer1 = v.findViewById(R.id.timer1); timer2 = v.findViewById(R.id.timer2); timer3 = v.findViewById(R.id.timer3); // устанавливаСм врСмя Π½Π° ΠΊΠ½ΠΎΠΏΠΊΠ°Ρ… setTime(); return v; } @Override public void onStart() { super.onStart(); broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context ctx, Intent intent) { // обновляСм врСмя ΠΊΠ°ΠΆΠ΄ΡƒΡŽ ΠΌΠΈΠ½ΡƒΡ‚Ρƒ setTime(); } }; // подписываСмся Π½Π° систСмноС событиС измСнСния Π²Ρ€Π΅ΠΌΠ΅Π½ΠΈ (срабатываСт Ρ€Π°Π· Π² ΠΌΠΈΠ½ΡƒΡ‚Ρƒ) getActivity().registerReceiver(broadcastReceiver, new IntentFilter(Intent.ACTION_TIME_TICK)); } @Override public void onStop() { super.onStop(); // отписываСмся ΠΎΡ‚ события if (broadcastReceiver != null)getActivity().unregisterReceiver(broadcastReceiver); } // ΠΌΠ΅Ρ‚ΠΎΠ΄ устанавливаСт врСмя Π½Π° ΠΊΠ½ΠΎΠΏΠΊΠ°Ρ… private void setTime() { long curentTime = System.currentTimeMillis(); timer1.setText(timeFormat.format(curentTime+ timeToMillis(timeShifts[0][HOUR],timeShifts[0][MINUTE]))); // Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π΅ врСмя timer2.setText(timeFormat.format(curentTime + timeToMillis(timeShifts[1][HOUR],timeShifts[1][MINUTE]))); // Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π΅ врСмя + 1 Ρ‡ 30 ΠΌΠΈΠ½ timer3.setText(timeFormat.format(curentTime + timeToMillis(timeShifts[2][HOUR],timeShifts[2][MINUTE]))); // Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π΅ врСмя + 3 Ρ‡. } // ΠΌΠ΅Ρ‚ΠΎΠ΄ ΠΏΠ΅Ρ€Π΅Π²ΠΎΠ΄ΠΈΡ‚ часы ΠΈ ΠΌΠΈΠ½ΡƒΡ‚Ρ‹ Π² милисСкунды private long timeToMillis(int hour, int minute){ return TimeUnit.HOURS.toMillis(hour) + TimeUnit.MINUTES.toMillis(minute); } } 

You can change the time offset during the program operation as follows (change the time offset on the second button to 2 hours and 15 minutes):

 timeShifts[1][HOUR] = 2; timeShifts[1][MINUTE] = 15; setTime(); 

ps: button countdown starts from 0

This code only displays the text on the buttons and updates it every minute, it does not perform any functions of a real alarm clock. Also, no action will occur if the program is not running or is in the background (that is, the conditional alarm does not work at the same time). If you need to count down the time when the application is closed or in the background, there is a class AlarmManager for this ( example of use ). You can use the code above for the application interface, and set the real alarm clock already via AlarmManager

  • broadcastReceiver is red, although I imported a class, what could be wrong? - Catherine Derkach
  • so you can not say why you are going. when you hover the cursor on the highlighted red, what does it write, what's the problem? In general, I tested the code, which is in response - it works. Try to copy it completely, including imports (you can create a test project), and then modify it to fit your tasks, if it does not work out otherwise. - pavlofff
  • well, thanks, I will try - Catherine Derkach
  • I tried, poked for a long time, but in the end everything worked, but the time is still not updated as it should. If you hang in the fragment for 2-3 minutes, then the time will not be updated, if you switch to another tab, and then again in the desired fragment, then it will be updated. in any case, thank you, I hope I did not get you with stupid questions: `D - Catherine Derkach
  • you are doing something wrong, I repeat that I checked the code and everything works - the time changes every minute. if you need a fragment without fail, tomorrow I will test it on a fragment, maybe there are some nuances .. - pavlofff 5:59 pm