Android timer,Broadcast Receiver, - android

Developing a timer application,
Have 4 buttons
start--Will start the timer
stop-- will stop timer
pause--will pause timer
lap time--will calculate lap time.
when button click it s working Good.
Now i am Modify the application like timer should start when phone is connected to charger and pause when phone is disconnected from charger.
The timer is starting fine when connected to the charger,
but during discharging the stop timer is not stopping at the accurate time it will be misplaced with some other time.i.e delay in minutes and seconds.
How to make the timer pause and show correct timer when disconnected from the charger...?
MainActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends Activity {
private static final String TAG ="Main Activity";
TextView textView;
Button start, pause, reset, lap;
long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L;
Handler handlerr;
int Seconds, Minutes, MilliSeconds;
ListView listView;
String[] ListElements = new String[]{};
List<String> ListElementsArrayList;
ArrayAdapter<String> adapter;
TextView textview;
Button button;
IntentFilter intentfilter;
int deviceStatus;
String currentBatteryStatus = "Battery Info";
int batteryLevel;
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.textViewBatteryStatus);
intentfilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
MainActivity.this.registerReceiver(broadcastreceiver, intentfilter);
textView = (TextView)findViewById(R.id.textView);
start = (Button)findViewById(R.id.button);
pause = (Button)findViewById(R.id.button2);
reset = (Button)findViewById(R.id.button3);
lap = (Button)findViewById(R.id.button4) ;
listView = (ListView)findViewById(R.id.listview1);
handler = new Handler() ;
ListElementsArrayList = new ArrayList<String>(Arrays.asList(ListElements));
adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1,
ListElementsArrayList
);
listView.setAdapter(adapter);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StartTime = SystemClock.uptimeMillis();
handler.postDelayed(runnable, 0);
reset.setEnabled(false);
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TimeBuff += MillisecondTime;
handler.removeCallbacks(runnable);
reset.setEnabled(true);
}
});
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MillisecondTime = 0L ;
StartTime = 0L ;
TimeBuff = 0L ;
UpdateTime = 0L ;
Seconds = 0 ;
Minutes = 0 ;
MilliSeconds = 0 ;
textView.setText("00:00:00");
ListElementsArrayList.clear();
adapter.notifyDataSetChanged();
}
});
lap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ListElementsArrayList.add(textView.getText().toString());
adapter.notifyDataSetChanged();
}
});
}
public Runnable runnable = new Runnable() {
public void run() {
MillisecondTime = SystemClock.uptimeMillis() - StartTime;
UpdateTime = TimeBuff + MillisecondTime;
Seconds = (int) (UpdateTime / 1000);
Minutes = Seconds / 60;
Seconds = Seconds % 60;
MilliSeconds = (int) (UpdateTime % 1000);
textView.setText("" + Minutes + ":"
+ String.format("%02d", Seconds) + ":"
+ String.format("%03d", MilliSeconds));
handler.postDelayed(this, 0);
}
};
// Broadcasts receiver//
private BroadcastReceiver broadcastreceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
deviceStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int batteryLevel=(int)(((float)level / (float)scale) * 100.0f);
if(deviceStatus == BatteryManager.BATTERY_STATUS_CHARGING){
StartTime = SystemClock.uptimeMillis();
handler.postDelayed(runnable, 0);
reset.setEnabled(false);
textview.setText(currentBatteryStatus+" = Charging at "+batteryLevel+" %");
}
if(deviceStatus == BatteryManager.BATTERY_STATUS_DISCHARGING){
textview.setText(currentBatteryStatus+" = Discharging at "+batteryLevel+" %");
}
if (deviceStatus == BatteryManager.BATTERY_STATUS_FULL){
textview.setText(currentBatteryStatus+"= Battery Full at "+batteryLevel+" %");
}
if(deviceStatus == BatteryManager.BATTERY_STATUS_UNKNOWN){
textview.setText(currentBatteryStatus+" = Unknown at "+batteryLevel+" %");
}
if (deviceStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING){
TimeBuff += MillisecondTime;
handler.removeCallbacks(runnable);
reset.setEnabled(true);
textview.setText(currentBatteryStatus+" = Not Charging at "+batteryLevel+" %");
}
}
};
}
activity_main.xml
<TextView
android:text="00:00:00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="50dp"
android:textStyle="bold"
android:textColor="#009688"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:text="Start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="41dp"
android:id="#+id/button" />
<Button
android:text="Pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button2"
android:layout_alignBaseline="#+id/button"
android:layout_alignBottom="#+id/button"
android:layout_centerHorizontal="true" />
<Button
android:text="Reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/button3" />
<Button
android:text="Save Lap"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:id="#+id/button4"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button4"
android:layout_centerHorizontal="true"
android:layout_marginTop="12dp"
android:id="#+id/listview1"/>
<TextView
android:id="#+id/textViewBatteryStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/button2"
android:layout_below="#+id/textView"
android:text="Current Battery Status"
android:textAppearance="?android:attr/textAppearanceLarge" />
Guidance in editing code will be helpful.

If you want to catch the Charger Connected and Disconnected events, then you should not use the BATTERY_STATUS_CHARGING and BATTERY_STATUS_DISCHARGING at the first place.You should listen for -
<receiver android:name=".YourPowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
Thus you will get the broadcast only during charger connected and disconnected state.
Look here : https://developer.android.com/reference/android/content/Intent.html#ACTION_BATTERY_CHANGED

Related

stopwatch - how to?

I have been trying to build a stopwatch in my app which starts counting on a start button click.I want it to count from seconds then minutes, then Hour but the problem is I can't count Hour but I can count milliseconds which I do not want. is that possible on start button click the app takes the current system time and on stop click just calculate and print the interval between starts and stop clicks?
Here is my activity class
package com.example.rimapps.stopwatch;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button but1,but2;
long MillisecondTIme,StarTime,TimeBuff,UpdateTime=0L;
Handler handler;
int MilliSeconds,Seconds,Minutes,Hour;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.textView);
but1=(Button)findViewById(R.id.buttonstart);
but2=(Button)findViewById(R.id.buttonstop);
handler = new Handler();
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Date d=new Date();
//SimpleDateFormat sdf=new SimpleDateFormat("hh:mm a");
//String currentDateTimeString=sdf.format(d);
//textView.setText(currentDateTimeString);
StarTime=SystemClock.uptimeMillis();
handler.postDelayed(runnable,0);
//reset.setEnabled(false);
}
});
but2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MillisecondTIme=0L;
TimeBuff = 0L ;
UpdateTime = 0L ;
Seconds = 0 ;
Minutes = 0 ;
MilliSeconds = 0 ;
textView.setText("00:00:00");
}
});
}
public Runnable runnable=new Runnable() {
#Override
public void run() {
MillisecondTIme=SystemClock.uptimeMillis()-StarTime;
UpdateTime=TimeBuff+MillisecondTIme;
Seconds=(int)(UpdateTime/1000);
Minutes=Seconds/60;
Seconds=Seconds%60;
MilliSeconds=(int)(UpdateTime%1000);
textView.setText("" + Minutes + ":"
+ String.format("%02d", Seconds) + ":"
+ String.format("%03d", MilliSeconds));
handler.postDelayed(this,0);
}
};
}
here is my xml layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent"
android:layout_height="match_parent"
tools:context="com.example.rimapps.stopwatch.MainActivity">
<TextView
android:text="00:00:00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="50dp"
android:textStyle="bold"
android:textColor="#009688"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp" />
<Button
android:text="Start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="47dp"
android:id="#+id/buttonstart"
android:layout_below="#+id/textView"
android:layout_alignLeft="#+id/textView"
android:layout_alignStart="#+id/textView" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<Button
android:text="Stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/buttonstop"
android:layout_marginRight="89dp"
android:layout_marginEnd="89dp"
android:layout_marginTop="140dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</RelativeLayout>
While I was learning a book I also had a stopwatch coding problem this is a sample of the code I use.
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
int hours=seconds/3600;
int minutes=(seconds%3600)/60;
int secs=seconds%60;
String time = String.format("%d:%02d:%02d",hours,minutes,secs);
timeView.setText(time);
if(running)
{
seconds++;
}
handler.postDelayed(this,1000);
}
});
also understand Handler class, handler will always run the code immediately(like every second forever) so you gotta add a boolean value that know if it is running then set it to your button like if start button is click you got to set the running to true. Handler will always run forever like the famous loop() method of arduino(it is running forever).
Use sendMessage that does have a clearMessage instead of postRunnable
This time I'll write for you (most for fix convention with camel case):
The stop function is at the second button action listener
package com.example.rimapps.stopwatch;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button but1,but2;
long millisecondTIme,starTime,timeBuff,updateTime=0L;
Handler handler;
int milliSeconds,seconds,minutes,hour;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.textView);
but1=(Button)findViewById(R.id.buttonstart);
but2=(Button)findViewById(R.id.buttonstop);
handler = new Handler() {
public void handleMessage(Message what) {
millisecondTIme=SystemClock.uptimeMillis()-starTime;
updateTime=timeBuff+millisecondTIme;
seconds=(int)(UpdateTime/1000);
minutes=Seconds/60;
seconds=Seconds%60;
milliSeconds=(int)(updateTime%1000);
textView.setText("" + minutes + ":"
+ String.format("%02d", seconds) + ":"
+ String.format("%03d", milliSeconds));
handler.sendEmptyMessageDelayed(0, 1000); //repost in a loop
}
}
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
starTime=SystemClock.uptimeMillis();
handler.sendEmptyMessage(0); //Here send message with id 0
}
});
but2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
millisecondTIme=0L;
timeBuff = 0L ;
updateTime = 0L ;
seconds = 0 ;
minutes = 0 ;
milliSeconds = 0 ;
textView.setText("00:00:00");
handler.removeMessages(0); //Here clear all messages with same id
}
});
}
}

Timer in my quiz application

I need help with the timer. I need a timer to activate in each question and when it is finished it should disable the radio group. The problem in this code is that when the timer finish it disable all the radio groups in all the questions.
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class QuizActivity extends AppCompatActivity {
TextView tv,mTextField;
Button btnNext;
RadioGroup rg;
RadioButton rb1,rb2,rb3,rb4;
String questions[]={"First Android Phone?","Name of Android Version 4.4?","Android is which kind of software?"};
String ans[]={"Motorola Droid","Kitkat","Operating-System"};
String opt[]={"HTC-G1","HTC-One","Motorola Droid","Samsung S4","Jelly Bean","Kitkat","Froyo","Lollipop",
"Operating-System","Antivirus","Application","Tools"};
int flag=0;
public static int marks,correct,wrong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
tv = (TextView)findViewById(R.id.tvque);
mTextField = (TextView)findViewById(R.id.tv2);
btnNext = (Button)findViewById(R.id.btnNext);
rg = (RadioGroup)findViewById(R.id.radioGroup);
rb1 = (RadioButton)findViewById(R.id.radio0);
rb2 = (RadioButton)findViewById(R.id.radio1);
rb3 = (RadioButton)findViewById(R.id.radio2);
rb4 = (RadioButton)findViewById(R.id.radio3);
tv.setText(questions[flag]);
rb1.setText(opt[0]);
rb2.setText(opt[1]);
rb3.setText(opt[2]);
rb4.setText(opt[3]);
new CountDownTimer(20000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
for (int i=0; i< rg.getChildCount();i++){
rg.getChildAt(i).setEnabled(false);
}
//mTextField.setText("done!");
}
}.start();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
RadioButton uans=(RadioButton)findViewById(rg.getCheckedRadioButtonId());
String ansText = uans.getText().toString();
if (ansText.equalsIgnoreCase(ans[flag]))
{
correct++;
}
else
{
wrong++;
}
flag++;
if(flag<questions.length)
{
tv.setText(questions[flag]);
rb1.setText(opt[flag*4]);
rb2.setText(opt[(flag*4)+1]);
rb3.setText(opt[(flag*4)+2]);
rb4.setText(opt[(flag*4)+3]);
}
else
{
marks=correct;
Intent in = new Intent(getApplicationContext(),ResultActivity.class);
startActivity(in);
}
}
});
}
}
UI of the application
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id = "#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Question"
android:id="#+id/tvque" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioGroup"
android:layout_below="#+id/tvque"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="50dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="RadioButton"/>
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton"/>
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton"/>
<RadioButton
android:id="#+id/radio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton"/>
</RadioGroup>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Next Question"
android:id="#+id/btnNext"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnNext"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="41dp"
android:id="#+id/tv2" />
This code now worked for me.
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class QuizActivity extends AppCompatActivity {
TextView tv,mTextField;
Button btnNext;
RadioGroup rg;
RadioButton rb1,rb2,rb3,rb4;
String questions[]={"First Android Phone?","Name of Android Version 4.4?","Android is which kind of software?"};
String ans[]={"Motorola Droid","Kitkat","Operating-System"};
String opt[]={"HTC-G1","HTC-One","Motorola Droid","Samsung S4","Jelly Bean","Kitkat","Froyo","Lollipop",
"Operating-System","Antivirus","Application","Tools"};
int flag=0;
public static int marks,correct,wrong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
tv = (TextView)findViewById(R.id.tvque);
mTextField = (TextView)findViewById(R.id.tv2);
btnNext = (Button)findViewById(R.id.btnNext);
rg = (RadioGroup)findViewById(R.id.radioGroup);
rb1 = (RadioButton)findViewById(R.id.radio0);
rb2 = (RadioButton)findViewById(R.id.radio1);
rb3 = (RadioButton)findViewById(R.id.radio2);
rb4 = (RadioButton)findViewById(R.id.radio3);
tv.setText(questions[flag]);
rb1.setText(opt[0]);
rb2.setText(opt[1]);
rb3.setText(opt[2]);
rb4.setText(opt[3]);
final CountDownTimer Counter1 = new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
for (int i=0; i< rg.getChildCount();i++){
rg.getChildAt(i).setEnabled(false);
}
}
}.start();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
RadioButton uans=(RadioButton)findViewById(rg.getCheckedRadioButtonId());
String ansText = uans.getText().toString();
if (ansText.equalsIgnoreCase(ans[flag]))
{
correct++;
}
else
{
wrong++;
}
flag++;
if(flag<questions.length)
{
tv.setText(questions[flag]);
rb1.setText(opt[flag*4]);
rb2.setText(opt[(flag*4)+1]);
rb3.setText(opt[(flag*4)+2]);
rb4.setText(opt[(flag*4)+3]);
for (int i=0; i< rg.getChildCount();i++){
rg.getChildAt(i).setEnabled(true);
}
Counter1.start();
}
else
{
marks=correct;
Intent in = new Intent(getApplicationContext(),ResultActivity.class);
startActivity(in);
}
}
});
}
}
private CountDownTimer timer;
onCrate()....
....
timer = new CountDownTimer(20000, 1000) {....};
timer.start();
....
onClick(){....
rb4.setText(opt[(flag * 4) + 3]);
timer.start();
};

Android TImer: Add a timer

I've been experimenting with Eclipse a bit...
and I almost finished a timer :)
Although, I can't get the Reset button working...
Res/Layout/main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent" >
<TextView
android:id="#+id/timerValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/pauseButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="37dp"
android:textSize="40sp"
android:textColor="#ffffff"
android:text="#string/timerVal" />
<Button
android:id="#+id/startButton"
android:layout_width="90dp"
android:layout_height="45dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="38dp"
android:text="#string/startButtonLabel" />
<Button
android:id="#+id/pauseButton"
android:layout_width="90dp"
android:layout_height="45dp"
android:layout_alignBaseline="#+id/startButton"
android:layout_alignBottom="#+id/startButton"
android:layout_alignParentRight="true"
android:layout_marginRight="38dp"
android:text="#string/pauseButtonLabel" />
<Button
android:id="#+id/resetButton"
android:layout_width="90dp"
android:layout_height="45dp"
android:layout_above="#+id/timerValue"
android:layout_centerHorizontal="true"
android:layout_marginBottom="31dp"
android:text="#string/resetButtonLabel" />
</RelativeLayout>
[/code]
[B]res/values/strings.xml[/B]
[code]<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Timer</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="timerVal">00:00:00</string>
<string name="pauseButtonLabel">Pause</string>
<string name="startButtonLabel">Start</string>
<string name="resetButtonLabel">Reset</string>
</resources>
MainActivity.java
package com.MertensMobile.Timer;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button startButton;
private Button pauseButton;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timerValue = (TextView) findViewById(R.id.timerValue);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
});
pauseButton = (Button) findViewById(R.id.pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});
resetButton = (Button) findViewById(R.id.resetButton);
resetButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
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);
}
public void Reset() {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
};
}
I'm very close, (at least I think I am) :P
I got it working on my cellphone, just the reset isn't working yet :o
I think you can use this to reset the timer.
TimerValue.cancel();
TextView digital_display = (TextView) findViewById(R.id.digital_display);
digital_display.setText("00:00.0");

Show final time in Alert Dialog after 10 button clicks

Right now I have my app set to show an alert dialog after 10 button clicks as well as stop the timer. I cannot figure out how to display the final time the timer stops on in the alert dialog. I want to make an alert dialog that displays that the game is over and also displays the players final time. Any idea how I would do this? Please help if you can.
JAVA CODE:
package com.example.thirtytapgametest;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AnalogClock;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
public class MainActivity extends Activity {
private int mCount = 0;
private ImageButton startbutton;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView countTextView = (TextView) findViewById(R.id.TextViewCount);
timerValue = (TextView) findViewById(R.id.timerValue);
startbutton = (ImageButton) findViewById(R.id.imageButton1);
startbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mCount ==0) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
mCount++;
countTextView.setText("Taps: " + mCount);
if(mCount == 10) {
view.setEnabled(false);
customHandler.removeCallbacks(updateTimerThread);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this)
.setTitle("Congratulations!")
.setMessage((R.id.timerValue))
.setIcon(R.drawable.ic_launcher)
.setCancelable(false)
.setPositiveButton(getString(R.string.play_again), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();}})
.setNegativeButton(getString(R.string.levels_menu), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();}});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
});
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
updatedTime = SystemClock.uptimeMillis() - startTime;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("Time: " + "" + mins + ":"
+String.format("%02d", secs) + ":"
+String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
}
};
}
XML CODE:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#drawable/thirty_tap_game_background">
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="138dp"
android:background="#drawable/test_play_button" />
<TextView
android:id="#+id/timerValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/imageButton1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="32dp"
android:textSize="40sp"
android:textColor="#FFFFFF"
android:text="#string/timerVal" />
<TextView
android:id="#+id/TextViewCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="73dp"
android:text="#string/countVal"
android:textSize="30sp"
android:textColor="#FFFFFF"/>
</RelativeLayout>
You can do this
int i =0; // declare this globally.
btn.setonclicklistener(new onClicklistener
onclick(View v){
i++;
if(i==10){
// show alert dialog
}
else{
// to do your stub here
}
}
You'll want to use the set message method in your AlertDialog builder.
.setTitle("Congratulations!")
.setMessage("Your time was: " + updatedTime)
.setIcon(R.drawable.ic_launcher)
why dont you use this?
http://developer.android.com/reference/android/widget/TextClock.html
and your code shows you using :
.setMessage((R.id.timerValue))
R.id.viewName refers to the hex id of the resource .Using this will not set the value that is contained in the textView.
you could try:
.setMessage(((TextView)R.id.timerValue).getText().toString())
or you could declare the text view earlier and call TextView.getText().toString() while creating the dialog.

Timer in three EditTexts not working properly

I have made a Timer Application in android.In application there are three (uneditable)EditText and a Button.When i press Button first time the timer in 1st EditText will start ,when i press it 2nd time the timer in 1st EditText will stop and at the same time the timer in 2nd EditText will be start,when i again press button same thing will be happened with 3rd EdtiText.NOw this code is working properly but when i press back button and again start it,its stopped working in 3rd EditText.The problem is sometimes the timer in 3rd EditText is not working(not displayed)..my code is as below:
mainActivity.java
package com.example.timerdemo2;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import org.w3c.dom.Text;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText et1,et2,et3;
TextView tv;
public int i=0;
long starttime = 0;
long lasttime,lasttime1;
final Handler handler = new Handler();
Handler h2 = new Handler();
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
Runnable run = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
int minutes = (seconds%3600)/60;
int hours = seconds / 3600;
seconds = seconds % 60;
et1.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
// et2.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
// et3.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
h2.postDelayed(this, 500);
}
};
class firstTask extends TimerTask {
public void run() {
handler.sendEmptyMessage(0);
}
};
class secondTask extends TimerTask{
#Override
public void run() {
// TODO Auto-generated method stub
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - starttime;
int seconds = (int)(millis/1000);
int hours =seconds/3600;
int minutes = (seconds % 3600)/60;
seconds = seconds % 60;
et2.setText(String.format("%02d:%02d:%02d", hours,minutes,seconds));
}
});
}
}
class thirdTask extends TimerTask{
#Override
public void run() {
// TODO Auto-generated method stub
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - starttime;
int seconds = (int)(millis/1000);
int hours =seconds/3600;
int minutes = (seconds % 3600)/60;
seconds = seconds % 60;
et3.setText(String.format("%02d:%02d:%02d", hours,minutes,seconds));
h2.postDelayed(this, 500);
}
});
}
}
Timer timer = new Timer();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = this.getIntent().getExtras();
String title = bundle.getString("title");
tv = (TextView)findViewById(R.id.projectTitle);
tv.setText(title);
et1= (EditText)findViewById(R.id.timeEdit1);
et2= (EditText)findViewById(R.id.timeEdit2);
et3= (EditText)findViewById(R.id.timeEdit3);
Button b = (Button)findViewById(R.id.btn);
b.setText("Start");
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Button b =(Button)v;
if(b.getText().equals("Stop")){
timer.cancel();
timer.purge();
h2.removeCallbacks(run);
Intent intent =new Intent(MainActivity.this,Timedetails.class);
Bundle bundle =new Bundle();
//Procedure for Showing time stamps on another page
String a = et1.getText().toString();
String b1 = et2.getText().toString();
String c = et3.getText().toString();
String t = tv.getText().toString();
intent.putExtra("titl1",t);
startActivity(intent);
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
try{
bundle.putString("t1", a);
bundle.putString("t2", b1);
bundle.putString("t3", c);
Date date1 = (Date) format.parse(a);
Date date2 = (Date) format.parse(b1);
Date date3 = (Date) format.parse(c);
//time difference in milliseconds
long timeDiff = date2.getTime() - date1.getTime();
long timeDiff2 = date3.getTime() - date2.getTime();
//new date object with time difference
Date diffDate = new Date(timeDiff);
Date diffDate2 = new Date(timeDiff2);
long timeDiffSecs = timeDiff/1000;
String timeDiffString = timeDiffSecs/3600+":"+
(timeDiffSecs%3600)/60+":"+
(timeDiffSecs%3600)%60;
long timeDiffSecs1 = timeDiff2/1000;
String timeDiffString1 = timeDiffSecs1/3600+":"+
(timeDiffSecs1%3600)/60+":"+
(timeDiffSecs1%3600)%60;
//formatted date string
// String timeDiffString = format.format(diffDate);
//System.out.println("Time Diff = "+ timeDiffString );
bundle.putString("t1", a);
bundle.putString("t2", b1);
bundle.putString("t3", c);
bundle.putString("dif1", timeDiffString);
bundle.putString("dif2", timeDiffString1);
}
catch(Exception e){
e.printStackTrace();
}
intent.putExtras(bundle);
startActivity(intent);
b.setText("Next");
}
else if(b.getText().equals("Lap1"))
{
timer.schedule(new secondTask(),0, 500);
h2.removeCallbacks(run);
b.setText("lap2");
}
else if(b.getText().equals("lap2")){
timer.schedule(new thirdTask(), 0,500);
h2.removeCallbacks(run);
timer.cancel();
timer.purge();
b.setText("Stop");
}
else {
starttime = System.currentTimeMillis();
timer = new Timer();
timer.schedule(new firstTask(), 0,500);
// timer.schedule(new secondTask(), 0,500);
//timer.schedule(new thirdTask(), 0,500);
h2.postDelayed(run, 0);
b.setText("Lap1");
//long lastdown = System.currentTimeMillis();
}
}
});
}
}
MainActivity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/abs5"
android:orientation="vertical" >
<TextView
android:id="#+id/projectTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|center"
android:layout_marginTop="5dp"
android:text="Project Title"
android:textColor="#CCCCCC"
android:textSize= "40dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:text="Timing Point1"
android:textSize="20dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#CCCCCC" />
<EditText
android:id="#+id/timeEdit1"
android:layout_width="172dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:background="#FFFFFF"
android:editable="false"
android:filterTouchesWhenObscured="false"
android:focusable="false" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Timing Point2"
android:textColor="#CCCCCC"
android:textSize="20dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/timeEdit2"
android:layout_width="172dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:focusable="false"
android:filterTouchesWhenObscured="false"
android:background="#FFFFFF"
android:editable="false" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:text="Timing Point3"
android:textColor="#CCCCCC"
android:textSize="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/timeEdit3"
android:layout_width="172dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:background="#FFFFFF"
android:editable="false" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:orientation="horizontal" >
<Button
android:id="#+id/btn"
android:layout_width="129dp"
android:layout_height="64dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="110dp"
android:layout_marginTop="10dp"
android:background="#drawable/aqa"
android:textColor="#FFFFFF"
android:textSize="30dp" />
</LinearLayout>
</LinearLayout>
Please help me for this as fast ...really thanking you.....hav a gud tym
Look at this code in your lap2 handler:
timer.schedule(new thirdTask(), 0,500);
h2.removeCallbacks(run);
timer.cancel();
timer.purge();
b.setText("Stop");
You schedule a task and cancel the timer immediately afterwards.
I would suggest that you get rid of the Timer and just use the Handler.postDelayed() method, as you have done already for the time updates and to start the update of the first field:
h2.postDelayed(run, 0);
Use the same method to start the updates for second and third fields. You don't need the Timer and TimerTask instances at all.
Also, why do you need two handlers (handler, and h2)?

Categories

Resources