I have created an android studio project that contains a countdown until Christmas. I use two images to create the background and the outline for the countdown timer. I have made the application look nice and I was wondering if there is any way to set the project as my phone's background and if it is possible how to do it. The code below is how I set the timer and give it its value. Is there anything I need to change to make this possible?
package com.example.holidaycountdown;
import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private TextView txtTimerDay, txtTimerHour, txtTimerMinute, txtTimerSecond;
private TextView tvEvent;
private Handler handler;
private Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtTimerDay = (TextView) findViewById(R.id.txtTimerDay);
txtTimerHour = (TextView) findViewById(R.id.txtTimerHour);
txtTimerMinute = (TextView) findViewById(R.id.txtTimerMinute);
txtTimerSecond = (TextView) findViewById(R.id.txtTimerSecond);
tvEvent = (TextView) findViewById(R.id.tvhappyevent);
countDownStart();
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setWallpaper();
}
});
}
private void setWallpaper() {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper);
WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
try{
manager.setBitmap(bitmap);
Toast.makeText(this, "Wallpaper set!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "Error!", Toast.LENGTH_SHORT).show();
}
}
public void countDownStart() {
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 1000);
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd");
// Please here set your event date//YYYY-MM-DD
Date futureDate = dateFormat.parse("2020-12-25");
Date currentDate = new Date();
if (!currentDate.after(futureDate)) {
long diff = futureDate.getTime()
- currentDate.getTime();
long days = diff / (24 * 60 * 60 * 1000);
diff -= days * (24 * 60 * 60 * 1000);
long hours = diff / (60 * 60 * 1000);
diff -= hours * (60 * 60 * 1000);
long minutes = diff / (60 * 1000);
diff -= minutes * (60 * 1000);
long seconds = diff / 1000;
txtTimerDay.setText("" + String.format("%02d", days));
txtTimerHour.setText("" + String.format("%02d", hours));
txtTimerMinute.setText(""
+ String.format("%02d", minutes));
txtTimerSecond.setText(""
+ String.format("%02d", seconds));
} else {
tvEvent.setVisibility(View.VISIBLE);
tvEvent.setText("The event started!");
textViewGone();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
handler.postDelayed(runnable, 1 * 1000);
}
public void textViewGone() {
findViewById(R.id.LinearLayout10).setVisibility(View.GONE);
findViewById(R.id.LinearLayout11).setVisibility(View.GONE);
findViewById(R.id.LinearLayout12).setVisibility(View.GONE);
findViewById(R.id.LinearLayout13).setVisibility(View.GONE);
findViewById(R.id.textView1).setVisibility(View.GONE);
findViewById(R.id.textView2).setVisibility(View.GONE);
}
}
Seems like you need to create an app widget for your application(App Widgets are miniature application views that can be embedded in other applications (such as the Home screen) and receive periodic updates).
Here is a useful tutorial
Google's tutorial
Related
Below is the code which I have for my countdown timer displaying into a text view when I run the app. However when I run it, it does not appear.
private TextView countdowndisplay;
private Handler handler;
private Runnable runnable;
countdowndisplay = (TextView) view.findViewById(R.id.countdowntv);
countDownStart();
public void countDownStart() {
handler = new Handler();
runnable = new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void run() {
handler.postDelayed(this, 1000);
try {
SimpleDateFormat dateFormat = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
} else {
//Set the optional Date format here for Devices Running ANDROID VERSION BELOW N
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
}
// Please here set your event date//YYYY-MM-DD
Date futureDate = dateFormat.parse("2017-09-23");
Date currentDate = new Date();
if (!currentDate.after(futureDate)) {
long diff = futureDate.getTime()
- currentDate.getTime();
long days = diff / (24 * 60 * 60 * 1000);
diff -= days * (24 * 60 * 60 * 1000);
long hours = diff / (60 * 60 * 1000);
diff -= hours * (60 * 60 * 1000);
long minutes = diff / (60 * 1000);
diff -= minutes * (60 * 1000);
long seconds = diff / 1000;
countdowndisplay.setText("" + String.format("%02d", days, hours, minutes, seconds));
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
handler.postDelayed(runnable, 1 * 1000);
}
Below is the XML which I have for the textView where I want the output to be displayed.
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/nextdrifttv"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/countdowntv"/>
I would do this a different way but this works using your code – android.
package com.example.coundown.countdownapp;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private TextView countdowndisplay;
private Handler handler;
private Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countdowndisplay = (TextView) findViewById(R.id.coundowntimer);
countDownStart();
}
public void countDownStart() {
handler = new Handler();
runnable = new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void run() {
handler.postDelayed(this, 1000);
try {
SimpleDateFormat dateFormat = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
} else {
//Set the optional Date format here for Devices Running ANDROID VERSION BELOW N
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
}
// Please here set your event date//YYYY-MM-DD
Date futureDate = dateFormat.parse("2017-09-23");
Date currentDate = new Date();
if (!currentDate.after(futureDate)) {
long diff = futureDate.getTime() - currentDate.getTime();
long days = diff / (24 * 60 * 60 * 1000);
diff -= days * (24 * 60 * 60 * 1000);
long hours = diff / (60 * 60 * 1000);
diff -= hours * (60 * 60 * 1000);
long minutes = diff / (60 * 1000);
diff -= minutes * (60 * 1000);
long seconds = diff / 1000;
if (countdowndisplay != null)
countdowndisplay.setText(String.valueOf(days) + " days \n" + String.valueOf(hours) + " hours \n " + String.valueOf(minutes) + " minutes \n" + String.valueOf(seconds)+ " seconds");
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
handler.postDelayed(runnable, 1 * 1000);
}
}
Try this. Your problem is updating the UI from runnable.
public class MainActivity extends AppCompatActivity {
TextView countdowndisplay;
int count=0;
Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countdowndisplay = (TextView) findViewById(R.id.mainText);
countdowndisplay.setText("really");
countDownStart();
}
void countDownStart(){
//Post handler after 1 second.
handler.postDelayed(runnable, 1000);
}
Runnable runnable = new Runnable() {
#Override
public void run() {
count++;
handler.postDelayed(runnable, 1000);
///**Update your UI from here**///
countdowndisplay.setText(count+" Second");
}
};
}
I want to make a Timer Application which plays an alarm after a specific time has elapsed. I am new to Android Development so i picked up an example timer code from the Internet and am trying to modify it to my needs.
I have completed part where the timer plays the alarm when 1 minute has elapsed, but the alarm sound does not stop how can i do that.
My code is given below:
package com.example.aditya.timerapp;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity {
private ProgressBar progress;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
int progressStatus = 0;
private boolean stopped = false;
#Override
public void onCreate(Bundle savedInstanceState) {
//final CountDown timer = new CountDown();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerValue = (TextView) findViewById(R.id.timerVal);
Button startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//timer.start();
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
});
Button pauseButton = (Button) findViewById(R.id.stopButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
/*try {
timer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}*/
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});
Button resetButton = (Button) findViewById(R.id.resetButton);
resetButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//timeSwapBuff += timeInMilliseconds;
timeInMilliseconds = 0L;
timeSwapBuff = 0L;
updatedTime = 0L;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
customHandler.removeCallbacks(updateTimerThread);
onStop();
}
});
progress = (ProgressBar) findViewById(R.id.progressBar);
}
/*public void stopRun() {
//if (updatedTime == 0) {
//Toast.makeText(new MainActivity(), "StopRun",Toast.LENGTH_LONG).show();
timeSwapBuff = 0;
timerValue.setText("00:00:000");
//updateTimerThread.
customHandler.removeCallbacks(updateTimerThread);
//}
}*/
private Runnable updateTimerThread = new Runnable() {
#Override
public void run() {
//long totalMilliseconds = 1500000;
//while (!stopped){
//long totalMilliseconds = 15000;
//updatedTime = totalMilliseconds - SystemClock.currentThreadTimeMillis();
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
if (mins == 1 && secs == 0) {
playTimer();
}
}
};
public ProgressBar getProgress() {
return progress;
}
public void setProgress(ProgressBar progress) {
this.progress = progress;
}
public void playTimer(){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone ring = RingtoneManager.getRingtone(getApplicationContext(), notification);
ring.play();
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
protected void onStop() {
customHandler.removeCallbacks(updateTimerThread);
super.onStop();
}
}
So now i need a method to stop the alarm when the user presses the Reset Button. Please suggest.
One way to do it is as follows:
Define a boolean inside your Runnable and check it before doing anything in run().
Flip it using a method inside your Runnable.
Here is the code snippet:
private Runnable updateTimerThread = new Runnable() {
private volatile boolean flag = true;
public void stopTimer() {
this.flag = false;
}
#Override
public void run() {
while(flag) {
//long totalMilliseconds = 1500000;
//while (!stopped){
//long totalMilliseconds = 15000;
//updatedTime = totalMilliseconds - SystemClock.currentThreadTimeMillis();
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
if (mins == 1 && secs == 0) {
playTimer();
}
}
}
};
Now, you just have to call stopTimer() to stop the Runnable.
Another way could be to handle the InterruptedException in the Runnable and send an interrupt from the main program.
If I understood question right,you can try to stop alarm sound by declaring your private Ringtone ring and call ring.stop() method in your onStop() method.
private Ringtone ring;
//...//
public void playTimer(){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
ring = RingtoneManager.getRingtone(getApplicationContext(), notification);
ring.play();
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
protected void onStop() {
customHandler.removeCallbacks(updateTimerThread);
ring.stop();
super.onStop();
}
Im really new to Android programming(started yesterday) and im currently working on an App that should give me the time between first time clicking a button and second time clicking the button.
It works fine when i stay in the Activity. But if i change the activity while the time is "running" and then reenter the main activity it gives me a strange timestamp.
How the timestamp works:
I have a button for Start/Stop
On clicking start it calls a Method where i get the current system time in milliseconds and saves it to a variable.
On clicking stop it does the same and subtracts endTime-startTime. Thats how i get the total time.
(Works fine)
But when changing activity(I got a button where it changes to an activity where i can add a customer) and reentering main and stopping the timer, it adds the totalTime up to something i cant relate to.. currently my stop time is at 45 minutes.
Maybe i do something wrong on saving my values?
I'll just post my code. Maybe someone can help me and give me a hint. Thanks and sorry for my bad english!
Class "Timerecording"
package com.example.cmsolutions.zeiterfassung;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.view.View;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
public class ZeitErfassen extends AppCompatActivity {
public static LinkedList<Kunde> kunden = new LinkedList();
boolean running = false;
long startTime,endTime,totalTime;
public Date date = new Date();
private SharedPreferences app_preferences;
private SharedPreferences.Editor editor;
private static final int PREFERENCE_MODE_PRIVAT=0;
private TextView displayTime;
public Button startEndButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zeit_erfassen);
//Einstellungen laden
app_preferences = getPreferences(PREFERENCE_MODE_PRIVAT);
displayTime = (TextView)findViewById(R.id.zeit_bei_Kunde);
startTime= app_preferences.getLong("startTime", 0);
endTime = app_preferences.getLong("endTime", 0);
running = app_preferences.getBoolean("running", false);
totalTime = app_preferences.getLong("totalTime", 0);
displayTime.setText((CharSequence) app_preferences.getString("zeitAnzeige", "Zeit bei Kunde"));
startEndButton = (Button)findViewById(R.id.start_Timer);
startEndButton.setText((CharSequence)app_preferences.getString("timerButton","Start Timer"));
editor = app_preferences.edit();
editor.commit();
createDropDown();
}
public void startTimer(View view) {
if(running == false) {
startTime = getTime();
displayTime.setText("Zeitstoppung läuft");
editor.putString("zeitAnzeige",(String)displayTime.getText());
running = true;
editor.putBoolean("running",true);
editor.putLong("startTimer", startTime);
startEndButton.setText("End Timer");
editor.putString("timerButton", (String)startEndButton.getText());
editor.commit();
} else {
endTime = getTime();
editor.putLong("endTime",endTime);
totalTime = endTime - startTime;
editor.putLong("totalTime",totalTime);
int hours = (int) ((totalTime / (1000*60*60)) % 24);
int minutes = (int) ((totalTime / (1000*60)) % 60);
int seconds = (int) (totalTime / 1000) % 60;
displayTime.setText(String.valueOf(hours)+ ":"+String.valueOf(minutes)+":"+ String.valueOf(seconds));
startEndButton.setText("Start Timer");
editor.putString("timerButton",(String)startEndButton.getText());
editor.commit();
running = false;
}
}
public void neuerKunde(View view) {
Intent intent = new Intent(this, AddKunde.class);
startActivity(intent);
}
public long getTime() {
long millis = System.currentTimeMillis();
return millis;
}
public void createDropDown() {
if(kunden.size() > 0) {
Spinner spinner = (Spinner) findViewById(R.id.chooseCustomer);
ArrayList<String> names = new ArrayList<>();
for(Kunde k:kunden) {
names.add(k.getName());
}
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, names);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
}
}
}
Class"AddCusomter"
package com.example.cmsolutions.zeiterfassung;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import java.util.LinkedList;
public class AddKunde extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_kunde2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void addKunde(View view) throws Exception {
try {
EditText strings = (EditText) findViewById(R.id.customerName);
String name = strings.getText().toString();
strings = (EditText) findViewById(R.id.addressField);
String address = strings.getText().toString();
Kunde customer = new Kunde(name,address);
ZeitErfassen.kunden.add(customer);
} catch (Exception e) {
throw new Exception("Fehler in addKunde!");
}
startActivity(new Intent(this,ZeitErfassen.class));
}
}
I just realised, maybe its because at the end of method addKunde() I start the MainActivity again?
PS: I think that I could also improve my Coding Style. If you have any Tips regarding better coding(methods to other class,....), im also greatuful! Thanks!
Instead of start activity you can finish activity.
//startActivity(new Intent(this,ZeitErfassen.class));
finish();
Check the shared pref is XML is storing values using ddms.
Open shared prefs only when you need
//OnCreate
app_preferences = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
public void startTimer(View view) {
SharedPreferences.Editor editor = = app_preferences.edit();
if(running == false) {
startTime = getTime(); displayTime.setText("Zeitstoppung läuft");
editor.putString("zeitAnzeige",(String)displayTime.getText());
running = true;
editor.putBoolean("running",true); editor.putLong("startTimer", startTime);
startEndButton.setText("End Timer");
editor.putString("timerButton", (String)startEndButton.getText());
editor.commit();
} else {
endTime = getTime();
editor.putLong("endTime",endTime); totalTime = endTime - startTime;
editor.putLong("totalTime",totalTime);
int hours = (int) ((totalTime / (1000*60*60)) % 24); int minutes = (int) ((totalTime / (1000*60)) % 60);
int seconds = (int) (totalTime / 1000) % 60;
displayTime.setText(String.valueOf(hours)+ ":"+String.valueOf(minutes)+":"+ String.valueOf(seconds));
startEndButton.setText("Start Timer"); editor.putString("timerButton",(String)startEndButton.getText());
editor.commit();
running = false;
}
}
I'm working on a watch face and its up and running but when I put it on my 360 it becomes slow to respond to interactions.
I should note that the screen wakes when a notification is received but not when one turns their wrist to look at the time.
Last thing I did was move code out of doWork and into CountDownRunner. Below is my code:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.Time;
import android.support.wearable.view.WatchViewStub;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Date;
public class ClockActivity extends Activity {
private TextView mTextView;
private Handler mHandler = new Handler();
private ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clock);
Runnable runnable = new CountDownRunner();
Thread myThread = new Thread(runnable);
myThread.start();
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
}
class CountDownRunner implements Runnable{
public void run() {
while(!Thread.currentThread().isInterrupted()){
try {
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
img=(ImageView)findViewById(R.id.hand_second);
RotateAnimation rotateAnimation = new RotateAnimation((seconds-1)*6, seconds*6,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotateAnimation.setInterpolator(new LinearInterpolator());
rotateAnimation.setDuration(1000);
rotateAnimation.setFillAfter(true);
img.startAnimation(rotateAnimation);
runOnUiThread(new Runnable() {
public void run() {
try{
}catch (Exception e) {
}
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}catch(Exception e){
}
}
}
}
}
You should not implement Runnable to change time on your wearable. Use BroadcastReceiver (Intent.ACTION_TIME_TICK, Intent.ACTION_TIMEZONE_CHANGED, Intent.ACTION_TIME_CHANGED) and receive a "tick" when time change (consumes less battery power and CPU).
Moreover, you must managed screen states (screen dim, screen awake, etc.)
Here is a great exemple of Watchface for Android Wear: http://www.binpress.com/tutorial/how-to-create-a-custom-android-wear-watch-face/120
And a last tips, you can manage seconds for your watchface only when your wearable is awake (like postdaleyed but must be killed when your wearable go back to sleep mode).
I am a bit of a keen novice at Android! I have a snippet of code for timer I want to use in my app however it works when the button is clicked and I want it to work when I open the activity that it is on. I have tried so many solutions but cannot get it to operate. Would really appreciate any help, I have tried putting an if statement in, I have tried using the onStart, and putting it the OnCreate all with no joy. The closest I can get is that it just starts with "Time Up!" in the field.
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity
{
Button buttonStartTime;
TextView textViewShowTime;
CountDownTimer countDownTimer;
long totalTimeCountInMilliseconds;
long timeBlinkInMilliseconds;
boolean blink;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getReferenceOfViews ();
setActionListeners ();
totalTimeCountInMilliseconds = 60 * 1000;
timeBlinkInMilliseconds = 30 * 1000;
}
private void setActionListeners() {
buttonStartTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textViewShowTime.setTextAppearance(getApplicationContext(), R.style.normalText);
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
if ( leftTimeInMilliseconds < timeBlinkInMilliseconds ) {
textViewShowTime.setTextAppearance(getApplicationContext(), R.style.blinkText);
if ( blink ) {
textViewShowTime.setVisibility(View.VISIBLE);
} else {
textViewShowTime.setVisibility(View.INVISIBLE);
}
blink = !blink;
}
textViewShowTime.setText(String.format("%02d", seconds / 60) + ":" + String.format("%02d", seconds % 60));
}
#Override
public void onFinish()
textViewShowTime.setText("Time up!");
textViewShowTime.setVisibility(View.VISIBLE);
}
}.start();
}
}
);
}
private void getReferenceOfViews() {
buttonStartTime = (Button) findViewById(R.id.btnStartTime);
textViewShowTime = (TextView) findViewById(R.id.tvTimeCount);
}
}
You can modify your onResume() as :
#Override
public void onResume(){
buttonStartTime.performClick();
super.onResume();
}
You should make buttonStartTime a global variable for the class.