[Tutorial] Learn to create a Countdown Timer on Android - Android Software Development

Hello,
I create that thread to present you a tutorial showing you how to create a a Countdown Timer on Android. The tutorial is also available on my website here : http://www.ssaurel.com/blog/learn-to-create-a-countdown-timer-on-android/ .
Sometimes, when you make Android applications, you need to create a countdown. It can be useful in a board game for example if the player have a defined time to play.
A lot of solutions exist to create a countdown in Java. Some are more complex than other.
On Android, the SDK offers to developers an easy way to create a countdown timer : a dedicated class named CountDownTimer.
1/ Create the CountDown Timer
Here, we consider a countdown of 60 seconds. So, we need to use the following code to create the CountDownTimer instance :
Code:
CountDownTimer countDownTimer = new CountDownTimer(60 * 1000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("Seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("Done !");
}
};
The second parameter lets you to define at which interval you must be notified during the countdown. You can update your User Interface in that method.
2/ Manage your CountDown Timer
Once you have created your CountDownTimer object, you have to manage it. First, you can start it :
Code:
countDownTimer.start();
If you want to cancel your countdown timer before its end, you have just to call its cancel() method :
Code:
countDownTimer.cancel();
3/ Conclusion
Powerful and easy to use, the CountDownTimer class is the ideal solution to create countdown timer on Android.
4/ Extra
You can also enjoy this tutorial on Youtube :
Don't hesitate to give me your feedbacks and ideas for new tutorials.
Thanks.
Sylvain

Some feedbacks ?

Related

event handling in dynamically created control

Hi all,
I am using eVC++ 4.0, and i've dynamically created a CListView like this:
Code:
lv.Create(0,_T(""),WS_CHILD|WS_VISIBLE,r,this,5);
but I dont know how to handle the events of this control... any ideas??
Mohammad
To get events from a listview (win32) I normally subclass it. I use the subclassing routine to post a message back to the parent when the user is doing something like tapping on it, then the windows routine can check whats selected etc and act on it. Is subclassing possible in mfc ?( I don't use it).
Thank u
but can anybody post some code??
thnx
Ok, I am a bit lazy to look up code at the moment, but here's something:
Yes, subclassing is possible in MFC. You just derive your class from the basic class provided like this:
Code:
class MyListView : pubic CListView
Then you add message handlers in the normal matter.
EDIT: The following passage is incorrect:
But I think subclassing may not be necessary in you case. List box controls send WM_COMMAND messages with notifications of major events like selection change to the parent window. All you have to do is to create a WM_COMMAND handler in your parent class.
Sorry I was thinking of ListBox not list view when I wrote it.
To manually add message handlers you need to put macros like ON_MESAGE or ON_COMMAND in the DECLARE_MESSAGE_MAP section of the class cpp file. All the detaisl are available on MSDN.
Are you saying that a listview will send the same WM_COMMAND as a list box in mfc? Dose this also happen in win32 made listviews. I have always thought it was a bit too tedious to find out when the user taps an item in the listview.
After reading your post levenum I had a quick look and it says that a WM_NOTIFY gets sent to the parent with a LVN_ITEMCHANGED for example. I had not used the LVN_**** because when I looked at them there was none that seem to deal with selections. I would guess that LVN_ITEMACTIVATE or LVN_ODSTATECHANGED would be usefull for this but then a second tap would not be picked up still leaving me wanting subclassing in many situations to get the users tap.
Ok, I have read what u wrote guys and my problem is almost solved, I used the OnNotify() method to handle messages sent from child controls like this:
Code:
BOOL CTest2Dlg::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
{
// TODO: Add your specialized code here and/or call the base class
if(wParam ==5 ) //5 is control ID
{
NMHDR *ph =(NMHDR*)lParam;
if(ph->code==NM_CLICK)
MessageBox("Click");
else if(ph->code==HDN_ITEMCLICK)
MessageBox("Item Click");
else
{
CString str;
str.Format("%d",ph->code);
MessageBox(str);
}
}
return CDialog::OnNotify(wParam, lParam, pResult);
}
Now there still a very small prolem: what messages should I handle for 'Selected Item Changed' event ?? I know its easy but I couldnt find it
Regards
mohgdeisat: I am sorry, I made a mistake about WM_COMMAND.
OdeeanRDeathshead is right, I was thinking of a list box not list view.
To make up for this, here is some sample code from a win32 dialog app that uses list view control. I hope it will be of some help:
Code:
//this is from the dialog window function:
case WM_NOTIFY: //handle events:
nmhdr = (LPNMHDR)lParam;
switch (nmhdr->idFrom)
{
case IDC_LEDLIST: //list control ID.
return OnLEDListEvent(hwndDlg, (LPNMLISTVIEW)lParam);
break;
}
break;
BOOL OnLEDListEvent(HWND hwndDlg, LPNMLISTVIEW nmlv)
{
/////
// Handles list view control notification messages
switch (nmlv->hdr.code)
{
case LVN_ITEMCHANGED:
return OnLEDListItemChanged(hwndDlg, nmlv);
break;
}
return 0;
}
BOOL OnLEDListItemChanged(HWND hwndDlg, LPNMLISTVIEW nmlv)
{
if (ListView_GetSelectionMark(nmlv->hdr.hwndFrom) != nmlv->iItem) return 0;
/* do what you need here */
return 0;
}
Don't mind the fact that I used 3 different functions. This is part of a bigger program and I am trying to keep things well organized without resorting to classes.
As I understand it, LVN_ITEMCHANGE is received for different reasons so I try to handle only the one coming from selected item. LVN_ITEMACTIVATE is only sent when you double click the item so if you just want to catch selection change you need to use LVN_ITEMCHANGE.
Once again, sorry for confusing you before.
thanx pals, good job!!!
I think my problem is now solved with ur help :wink:
Mohammad
Ok guys, I said that my problem was solved, yet, another problem arises...
When the list view is in the report mode, how can I determine when a header button is clicked, and determine which one was clicked???????
thanx in advance
To identify a header column click, you need to handle the WM_NOTIFY/HDN_ITEMCLICK message. Normally this message will be received by the header's parent control (i.e. the listview) -- some frameworks may redirect the message to the header control itself. I haven't worked with MFC in 10 years so I can't really if it reflects notification messages back to the control.
If you're trying to implement column sort, do yourself a favor and check out the Windows Template Library (WTL) at sourceforge.net. It's a set of C++ template classes that provide a thin yet useful wrapper around the standard Windows UI components. One of the classes is a sortable listview control. I've been using WTL with big Windows for more than 5 years -- you couldn't pay me to go back to MFC.
hi,
I have seen the WTL library and it seems very useful and time-saver, but I have a couple of questions about it:
1. can WTL 8.0 be installed with VC++ 6.0, specifically the appwizard stuff??how?? I see only javascript files of vc7.0 and 7.1 and 8.0!!
2. is there a good documentation about those classes??
Mohammad
I don't know about WTL 8; I'm still using WTL 7.5 with VS .Net 2003 for all my Win32 development. My guess is that it wouldn't work too well, as WTL is based on ATL, which has substantially changed between VC 6 and 7.
Good references for WTL include www.codeproject.com/wtl, and the WTL group over at Yahoo groups (reflected at www.gmane.org).

add new calendar event

please help ,
i'm trying to make an app which i need to add event to the phone calendar by development of-course, how can i start, any sample code, i'm new to android development
moamenam said:
please help ,
i'm trying to make an app which i need to add event to the phone calendar by development of-course, how can i start, any sample code, i'm new to android development
Click to expand...
Click to collapse
if there is any document i can read please support me with it, i really need to make my first android app
code snipped
Code:
private void SetCalenderEntry(String calID, long date, String subject, String body, String location)
{
ContentValues event = new ContentValues();
event.put("calendar_id", calID);
event.put("title", subject);
event.put("description", body);
event.put("eventLocation", location);
long startTime = date;
event.put("dtstart", startTime);
event.put("dtend", startTime);
Uri eventsUri = Uri.parse("content://calendar/events");
getContentResolver().insert(eventsUri, event);
}

[17/03] Basic Java Tutorials and Android Examples!

I'm by no means a good java developer, but i've had to search ALOT for some of these java examples and i thought others might benifeit from them.
For someone starting out in android app developing (especially someone with no prior Java background like me) it can be a very tedious and irritating process.
Hopefully this thread will help some people
This list is not very complete yet, but over the next few days i will be adding more examples (especially more Basic Java examples) and will be generally improving everything.
This is all written from my own memory and in my own words, but i can't remember where i learned it all from. If i'm using your or someone else's code please let me know so i can add credit where it's due!
Basic Java (general java examples)
All these 'Basic' tutorials are taken from my lectures at Manchester Metropolitan University where i'm taking Software Engineering. More will be added week by week!
Please be aware that these should be viewed in order, as any tutorial will assume you understand the ones before it.
All the files are included in a zip file attached to this post.
ALL CREDIT FOR THESE GO TO NICK COSTEN AND MMU UNIVERSITY!!
Those in RED are the latest tutorials.
******************************
Contents
- Lecture 1 - Values, Variables and Expressions
- Lecture 2 - Integers and Floating Point Numbers
- Lecture 3 - Casting and Type Boolean
- Lecture 4 - Object Types and Strings
- Lecture 5 - Input and Selection
- Lecture 6 - Complex Decision Making
- Lecture 7 - The 'for' Loop
- Lecture 8 - The 'while' Loop
- Lecture 9 - The 'do while' Loop
- Lecture 10 - Methods 1
- Lecture 11 - Methods 2
- Lecture 12 - Methods 3
- Lecture 13 - Test Case Design
- Lecture 14 - (OUTDATED. USE LECTURE 15)
- Lecture 15 - Applets 1
- Lecture 16 - Applets 2
- Lecture 17 - Applets 3
- Lecture 18 - Methods 3 (continued)
- Lecture 19 - Applet Test
- Code for 19 - Applet Code
- Lecture 20 - Objects 2
- Lecture 21 - Inheritance
*******************************
Android Java (Android specific examples)
******************************
Contents
- Root Access
- Buttons
- Exit Button
- Intents (next screen)
- Writing files to SDcard
*******************************
- Root Access
If you're developing an application that requires root access this is something you will need to know.
There are a few variations and diferent ways of acheiving this, but in my opinion, this is the most stable and problem free way i've found.
Simply insert this bit of code after the 'setContentView'.
Code:
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
{
os.writeBytes("mount -o rw,remount -t yaffs2 /dev/block/mtdblock03 /system\n" +
"exit \n");
os.flush();
process.waitFor();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
What does this do?
Well, not only does it attempt to gain root access, it will pause the application untill the user grants it SU access. Without the "process.waitFor();' line (and the second 'catch'), your application can get a little messy because the screen will be displayed underneath.
The 'os.writeBytes' statement is, as you probable guessed, holds the command you want to execute as SU. In the above example, it will remount the filesystem as Read/Write and then exit. Remember, whatever commands you use, you will need to put a '\n' to signify the end of a line.
Warning: NEVER leave this bit completely blank, as your application will lock up. This is because you're opening up a command line and not closing it.
Simply chaning it to "exit\n" would not issue any command, but would still ask for root access, so this could be quite useful.
- Buttons
Perhaps one of the most important parts of your application; buttons are very simple to implement but can be a little confusing at first.
First of all you will need to place one on your "main.xml", or whatever yours is called, or type in the code below (which i prefer, as dragging it across from the Views list messes up the indentation and makes it hard to edit).
You don't have to bother with code for the button layout if you don't want to, as it can all be done from the properties menu, but i wouldn't advise you do it this way.
Type this in your 'main.xml':
Code:
<Button
android:text="Button01"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
As you probably guessed, "wrap_content" can be replaced by either "fill_parent" or a numerical value in either 'px' or 'dp'. You should also give your button a more relevent name than Button01. For ease, i will call it ExampleButton.
Now that's done, move across to your .Java file. For your button to work we will need to implement a 'click listener', but first you will need to add the following to the top of your java file (before the Public Void bit).
Code:
private Button ExampleButton;
and then, in the main body add:
Code:
ExampleButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {;
*/ code goes here /*
}
});
Then your button is ready for code! (see below!)
- Exit Button
This one stumped me for a while, but as it turns out, it's incredibly simple to do. First you will need to create a button (see above) to act as the Exit button.
Once you've done that, add the following before the public void (this code can be added directly to the button, but i prefer doing it like this so it can be called from anywhere instead of typing it all out again).
For example:
Code:
public class Example extends Activity {
[B]public void killActivity() {
this.finish();
}[/B]
public void ...etc
Once done, this will allow you to simply insert "KillActivity();" to close your application!
So here's my exit button:
Code:
Exit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {;
killActivity();
}
});
Easy!
- Intents (next screen)
When your app starts getting a bit more advanced you may want more than one screen. This is quite easy to acheieve but can be quite messy if not done right.
Ok, first you'll have to create another .xml file (just copy and paste main.xml and delete all it's contents, that's the easy way! We'll call it screen2.xml).
Now, in your main.xml add the following code:
Code:
Intent a = new Intent(main.this, screen2.class);
startActivity(a);
You'll notice it will kick out a few errors. That's because your new screen2.xml hasn't been given an activity yet.
Open up your AndroidManifest.xml and add the following under your main activity (After the </activity> tag, but before the </application> tag!):
Code:
<activity android:name=".screen2"
android:label="@string/app_name">
<intent-filter>
</intent-filter>
</activity>
This should open up another identical activity over the top of the original one. If you want to close your original one instead of having both open you can just add your 'KillActivity();' after the code above!
- Writing files to SDcard
This little tutorial will tell you how to store files in your program and then on a button press, move them to a directory on your SDcard.
First of all, this tut requires you to create an additional folder for your app, so locate where the project is stored and under the folder 'res' (where you have drawable, layout, etc.) create another folder called "raw".
Now, whatever files you wish to store will have to be renamed.
For the files to be accepted you must remove any capital letters from the file name, any symbols and you also must remove any extension. So, a text file called 'Text1.2.txt' would have to be renamed to 'text1'. You must remember the extention though, as this will have to be restored manually later.
once your file is in place, you can create a directory for your files to go in. Using the command we learned for the 'Gaining Root Access' tutorial, we will create an 'Example' folder on your sdcard:
Code:
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
{
os.writeBytes("mkdir sdcard/example\n" +
"exit \n");
os.flush();
process.waitFor();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Once that's done, you can add the code to move the file (usually to a button press):
Code:
try {
InputStream ins = getResources().openRawResource(R.raw.text1);
int size = ins.available();
// Read the entire resource into a local byte buffer.
byte[] buffer = new byte[size];
ins.read(buffer);
ins.close();
FileOutputStream fos = new FileOutputStream("/sdcard/Example/Text1.2.txt");
fos.write(buffer);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
More to come!
Thank you thank you thank you!!!!! I am learning java for android apps right now and I really needed a quick source for some extra info. If u have any tutorials on learning java for development outside of android that would be great also.
Thanks a bunch,
Ljbaumer
Meltus said:
Once done, this will allow you to simply insert "KillActivity();" to close your application!
So here's my exit button:
Click to expand...
Click to collapse
That will only kill the activity that calls it. If your application has many activities you need to call finish() on all of them individually.
jgittins said:
That will only kill the activity that calls it. If your application has many activities you need to call finish() on all of them individually.
Click to expand...
Click to collapse
Yeah, but i'm writing it from the perspective of a basic android app with only 1 activity.
These are only proper basic tutorials to help people starting out
i've just started developing in general, with the hope of one day being a rom developer. These are the kind of resources that I need thanks!
Basic Universal java tutorials added to the first post.
ALL CREDIT FOR THESE GO TO NICK COSTEN (whoever he is!) AND MMU UNIVERSITY!!
[UPDATE]
Universal Java tutorials 'Methods 1' and 'Methods 2' added.
[UPDATE]
Universal Java Tutorials "Methods 3", "Test Case Design" and "Applets 1" added.
Good stuff...
I will def have to take a look sometime...hardware +...software/programming...D+ lol
[UPDATE]
Universal Java Tutorials "Applets 1" and "Applets 2" added.
Note: Lecture 14 has been replaced by a more up-to-date and concise Lecture 15.
Hi Meltus, just started on Android not long ago I'm still new to coding as well.
Would you assist me in how to code this part for my Android App?
I have a list of Name & Number both stored in String[] phoneNumbers, name.
How can I make a ListView with Checkbox and then upon clicking a button it does a check on those checked and add their position into an int[] ?
+-----------+----------+----------+
| Checkbox | Name | phoneNumbers|
+-----------+----------+----------+
Would be great if you could do up the code I'll definitely donate as a token of appreciation.
You could PM me if you prefer.
Cheers!
Cool,
Thanks for the tuts! You can never have enough material. I am a beginner, but i'm picking it up pretty fast.
Hehe. I took the easy way out and just use ListView with Multi Choice option.
Awesome man thanks for sharing. I'm not a dev but I can see how helpful this could be to someone who is starting out, because I know how much of a pain it can be searching for very specific things sometimes.
Thanks for the contribution!
Universal Tutorials added.
- Lecture 17 - Applets 3
- Lecture 18 - Methods 3 (continued)
- Lecture 19 - Applet Test
- Code for 19 - Applet Code
- Lecture 20 - Objects 2
- Lecture 21 - Inheritance
can u make a video tutorial pliz3?i realy bad at reading english and when i translate it on google translate its going wrong..

[Q] Where is the best place to check for license?

I wrote an app that most (98%) of the work is done by service.
Where is the best place to do a license check?
In your Main activity, the first time it is launched and where the service is initiated. I wouldn't do it too often so don't put the check into the service.
You could also check periodically, let's say, every 15 minutes.
But don't use Timer for that, as it creates a new thread (well, you could use it, but you could do it in a better way). It's better to use a Handler:
Code:
// Fifteen minutes
int checkFrequency = 15 * 60 * 1000;
Handlerhandler = new Handler();
Runnable runnable = new Runnable() {
[user=439709]@override[/user]
public void run() {
if (!checkLicense()) {
// no license, do whatever you need to do
}
handler.postDelayed(this, checkFrequency);
}
};
handler.postDelayed(runnable, checkFrequency);
So I will check every time he open the main window but the main window is a setup window so it won't be opned so ofen.
you can set preference and check weather user has accepted licence or not and if accepted then no need to display it again .
wasim memon said:
you can set preference and check weather user has accepted licence or not and if accepted then no need to display it again .
Click to expand...
Click to collapse
We've been talking about the Play Store licensing, not about an End User License Agreement.
He wanted to check whether the user has bought his app.
Otherwise your solution would be right though.
11alex11 said:
I wrote an app that most (98%) of the work is done by service.
Where is the best place to do a license check?
Click to expand...
Click to collapse
i would (this is how i do that) check it when the app starts (SplashActivity) and write "encrypted" how often the app got started.
Then everytime when (pseudocode)
if (read_and_decrypt(cntAppStart) % 10) == 0) { checklicense(); }
in the splashactivity.

[Q] How To: Randomize a list??

Dear Friends,
I'm working on an application which has a list of 5 items connected to a database at the back end. I would like to know how can I randomize the order of appearance of these 5 items in these list every time the app start?
Ex
Item 1: A
Item 2: B
Item 3: C
Item 4: D
Item 5: E
Next time the app launches the order of appearance is at random.
Ex
Item 1: C
Item 2: E
Item 3: A
Item 4: D
Item 5: B
So, on and so forth for every instances of app launch.
Also, how can I add transition animation (fade in, fade out, slide in, etc) like most of the modern web-pages have for the app UI. I do not have much programming experience. Just a learner. All help will be appreciated.
Look on the animations tutorial at androidhive.info ( i think it's proper address ).
Answering the first question, I would write method for database that returns list of items and implement randomization in it. Then just create instance of database in onCreate and make just like this : List<Item> randomList = db.returnRandomList();
I think this would be the easiest and most explanatory way that you could understand for the random list
Code:
private ArrayList<String> random(ArrayList<String> list)
{
ArrayList<String> randomList = new ArrayList<String>();
while(list.size() > 0)
{
int randomInt = new Random(System.currentTimeMillis()).nextInt(list.size());
randomList.add(list.get(randomInt));
list.remove(randomInt);
}
return randomList;
}
So with that imagine doing it with "_id"'s before asking the cursor for rows (though you would need all the primary keys to start with to do that on)... hope that gives you enough to start with
as for anims thats part of the view class and much info on d.android.com
To randomize the list use Java's Collections. Shuffle method and pass in ur list.
In order to display animations, after u call startactivity, make a call to overridependingtransition and pass in animations for the entering and exiting activity.
Sent from my XT1022 using XDA Free mobile app

Categories

Resources