Android TimePickerDialog selected time not passing through to the actual Countdown Timer - android

I've been working on getting a timepicker dialog to set my countdown timer. I have tried many ways with many different results... none of them worked right. I decided to experiment with some basic code which I will put below.
I cannot get the selected time (I called it selectedStartTime in the code below) to pass through into the actual countdown timer as startTime. I can only get the timer to work right when I use the preset startTime = 10000 (or any number). I don't want the startTime to be a set number. I need it to come from the OnTimeSetListener in the time picker box.
I will be forever grateful to anyone that can show me how to change the code so that the selected time in the dialog box is actually used in the timer.
Complete XML code for: activity_simple_timer_test.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start" />
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="10dip">
<TableRow>
<TextView
android:id="#+id/timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dip"
android:text="Time: " />
<TextView
android:id="#+id/timeElapsed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dip"
android:text="Time elapsed: " />
</TableRow>
</TableLayout>
</LinearLayout>
Complete Java code for: SimpleTimerTest.java
package com.YOURPACKAGE INFO;
import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class SimpleTimerTest extends Activity implements OnClickListener {
private MalibuCountDownTimer countDownTimer;
private long timeElapsed;
private boolean timerHasStarted = false;
private Button startB;
private TextView text;
private TextView timeElapsedView;
int selectedStartTime;
// don't want to use a predefined startTime
private final long startTime = 10000;
private final long interval = 1000;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_timer_test);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
timeElapsedView = (TextView) this.findViewById(R.id.timeElapsed);
countDownTimer = new MalibuCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime));
}
TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
selectedStartTime = ((hourOfDay*3600000)+(minute*60000));
// I can't get this variable to pass through into the countdown timer
}
};
#Override
public void onClick(View v) {
TimePickerDialog d = new TimePickerDialog(SimpleTimerTest.this, onTimeSetListener, 1, 0, true);
d.setTitle("Pick Sleep Duration hour:min");
d.setCancelable(true);
d.setButton(DialogInterface.BUTTON_POSITIVE, "Start", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("Stop");
} else {
countDownTimer.cancel();
timerHasStarted = false;
startB.setText("Timer was already running");
}
}
}
});
d.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
countDownTimer.cancel();
timerHasStarted = false;
startB.setText("Restart");
}
}
});
d.show();
}
public class MalibuCountDownTimer extends CountDownTimer {
public MalibuCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onFinish() {
text.setText("Time's up!");
timeElapsedView.setText("Time Elapsed: " + String.valueOf(startTime));
Toast toast = Toast.makeText(getApplicationContext(), "finished", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("Time remain:" + millisUntilFinished);
timeElapsed = startTime - millisUntilFinished;
timeElapsedView.setText("Time Elapsed: " + String.valueOf(timeElapsed));
}
}
}

I'm not completely sure what you're trying to achieve, just create instance of your MalibuCountDownTimer in method onTimeSet, this method will be called only when user selected time.

Related

How to stop a countdown timer.....?

I am having problem in stopping a CountDownTimer. I have searched a lot but couldn't understand how to do that.
Below is my MainActivity. How can I stop the timer if RadioButton b is pressed?
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView mTextField;
RadioButton a, b, c, d, e;
final static long interval = 1000;
long timeout = 15000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextField = (TextView) findViewById(R.id.tv);
a = (RadioButton) findViewById(R.id.rB1a);
b = (RadioButton) findViewById(R.id.rB2a);
c = (RadioButton) findViewById(R.id.rB3a);
d = (RadioButton) findViewById(R.id.rB4a);
e = (RadioButton) findViewById(R.id.rB5a);
//Timer timer = new Timer();
//timer.scheduleAtFixedRate(task, interval, interval);
TimerTask task = new TimerTask() {
#Override
public void run() {
timeout = timeout - interval;
if (timeout == 0) {
this.cancel();
displayText("finished");
return;
}
if (timeout >= 0) {
displayText("time remaining: " + String.valueOf(timeout / 1000));
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), "Wrong Answer!!! ", Toast.LENGTH_LONG).show();
Intent openWordlist = new Intent("com.example.the_vocab_master.AA");
startActivity(openWordlist);
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), "GREAT...!!! ", Toast.LENGTH_LONG).show();
}
});
}
//displayText("time remaining: " + String.valueOf(timeout / 1000));
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, interval, interval);
}
private void displayText(final String text) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
mTextField.setText(text);
}
});
}
}
To cancel the timer use
timer.cancel();
in your onClick listener. It's very difficult to see in your code, because the indentation is very bad, but I think you need to declare your timer variable in the class, instead of in onCreate();
Additionally, I'd suggest you to take both setOnClickListener calls OUTSIDE of the timer run() method. What you're doing doesn't make sense.

CountDownTimer not counting down but jumping straight to finish() method

I have an app that I am creating that will eventually, be a countdown timer with multiple stores of times so that the user will select the one to use and then start the countdowntimer. The issue that I am having is that the call to the countDownTimer.start(); works but the timer jumps to the onfinish(). I placed log.i's within the override onTick function and those Log.i's did not appear in logcat, which leads me to believe that something went wrong in the logic and that the countdowntimer method did not see something to count down and dropped to the onfinish.
That being said, please see the entire app below:
package com.vertygoeclypse.multitimer;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.TextView;
public class MainActivity extends Activity implements NumberPicker.OnValueChangeListener, OnClickListener{
Button dgbtn, abbtn, exbtn, cvbtn, canlbtn, sbtbtn, starest;
EditText tagvalue;
TextView tgview, minview, secview, timeRemaining;
NumberPicker minnp, secnp;
Dialog cusd;
private MultiCountDownTimer countDownTimer;
private long timeElapsed;
private boolean timerHasStarted = false;
private TextView timeElapsedView;
long startTime;
long interval=100;
long coversionvalues=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dgbtn = (Button) findViewById(R.id.dialogbtn);
abbtn = (Button) findViewById(R.id.aboutbtn);
exbtn = (Button) findViewById(R.id.exitbtn);
cvbtn = (Button) findViewById(R.id.clrvaluesbtn);
starest = (Button) findViewById(R.id.startresetbtn);
tgview = (TextView) findViewById(R.id.tagview);
minview = (TextView) findViewById(R.id.minview);
secview = (TextView) findViewById(R.id.seecview);
timeRemaining = (TextView) findViewById(R.id.timeremainingview);
timeElapsedView = (TextView) findViewById(R.id.countdowntimer);
dgbtn.setOnClickListener(this);
abbtn.setOnClickListener(this);
exbtn.setOnClickListener(this);
cvbtn.setOnClickListener(this);
starest.setOnClickListener(this);
countDownTimer = new MultiCountDownTimer(startTime, interval);
if(startTime==0){
starest.setEnabled(false);
}else if(startTime>0){
starest.setEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// TODO Auto-generated method stub
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.dialogbtn:
showDialog();
break;
case R.id.exitbtn:
finish();
case R.id.clrvaluesbtn:
tgview.setText("");
minview.setText("");
secview.setText("");
break;
case R.id.cancelbtn:
cusd.dismiss();
case R.id.submitbtn:
tgview.setText(String.valueOf(tagvalue.getText()));
minview.setText(String.valueOf(minnp.getValue()));
secview.setText(String.valueOf(secnp.getValue()));
int val1 = Integer.parseInt(String.valueOf(minnp.getValue()));
int val2 = Integer.parseInt(String.valueOf(secnp.getValue()));
int val3 = (val1*60)*1000;
int val4 = val2*1000;
coversionvalues = Long.valueOf(String.valueOf(val3+val4));
startTime = coversionvalues;
starest.setEnabled(true);
cusd.dismiss();
break;
case R.id.startresetbtn:
if(!timerHasStarted){
countDownTimer.start();
timerHasStarted = true;
starest.setText("Start");
} else {
countDownTimer.cancel();
timerHasStarted = false;
starest.setText("Reset");
}
}
}
public void showDialog(){
cusd = new Dialog(MainActivity.this);
cusd.setTitle("Tag and Timer Selector");
cusd.setContentView(R.layout.dialogbox);
canlbtn = (Button) cusd.findViewById(R.id.cancelbtn);
sbtbtn = (Button) cusd.findViewById(R.id.submitbtn);
minnp = (NumberPicker) cusd.findViewById(R.id.numberPicker1);
secnp = (NumberPicker) cusd.findViewById(R.id.numberPicker2);
tagvalue = (EditText) cusd.findViewById(R.id.tagname);
canlbtn.setOnClickListener(this);
sbtbtn.setOnClickListener(this);
minnp.setMaxValue(59);
minnp.setMinValue(0);
minnp.setWrapSelectorWheel(false);
minnp.setOnValueChangedListener(this);
secnp.setMaxValue(59);
secnp.setMinValue(0);
secnp.setWrapSelectorWheel(false);
secnp.setOnValueChangedListener(this);
cusd.show();
}
public class MultiCountDownTimer extends CountDownTimer{
public MultiCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onTick(long millisUntilFinished)
{
Log.i("VertygoEclypse", String.valueOf(millisUntilFinished));
timeRemaining.setText("Time remain:" + millisUntilFinished);
timeElapsed = startTime - millisUntilFinished;
Log.i("VertygoEclypse", String.valueOf(timeElapsed));
timeElapsedView.setText("Time Elapsed: " + String.valueOf(timeElapsed));
}
#Override
public void onFinish()
{
timeRemaining.setText("Time's up!");
timeElapsedView.setText("Time Elapsed: " + String.valueOf(startTime));
}
}
}
For startTime set some value, It cannot be zero. Actually startTime is the time in future when the countdown timer should stop or finish. if possible please change it to finish time
countDownTimer = new MultiCountDownTimer(startTime, interval);

Timer in Background

I'm developing an Android Application to a college work. In this work I want to create a background service with a timer and when I close the application, timer still running. When I open the app, I can see the time since I've started service.
Well, my problem is that when I close the app, the background timer stops and not increments more.
Can you help me please?
Thanks a lot
My launcher class
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
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;
Intent intent;
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) {
intent = new Intent(MainActivity.this, CounterService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(CounterService.BROADCAST_ACTION));
}
});
pauseButton = (Button) findViewById(R.id.pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
});
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
private void updateUI(Intent intent) {
int time = intent.getIntExtra("time", 0);
Log.d("Hello", "Time " + time);
int mins = time / 60;
int secs = time % 60;
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs));
}
}
and here, the service class
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
public class CounterService extends Service {
private Intent intent;
public static final String BROADCAST_ACTION = "com.javacodegeeks.android.androidtimerexample.MainActivity";
private Handler handler = new Handler();
private long initial_time;
long timeInMilliseconds = 0L;
#Override
public void onCreate() {
super.onCreate();
initial_time = SystemClock.uptimeMillis();
intent = new Intent(BROADCAST_ACTION);
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 1000); // 1 seconds
}
};
private void DisplayLoggingInfo() {
timeInMilliseconds = SystemClock.uptimeMillis() - initial_time;
int timer = (int) timeInMilliseconds / 1000;
intent.putExtra("time", timer);
sendBroadcast(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendUpdatesToUI);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
you need to start your service in the onStop() method in your activity like this:
#Override
protected void onStop() {
super.onStop();
//write your code here to start your service
}
Kindly go through the link hope it will be helpful if you want to run timer in background Timer in background
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/et_hours"
android:hint="Hours"
android:inputType="time"
android:layout_marginRight="5dp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btn_timer"
android:layout_above="#+id/btn_cancel"
android:text="Start Timer"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="#+id/btn_cancel"
android:text="cancel timer"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_timer"
android:layout_centerInParent="true"
android:textSize="25dp"
android:textColor="#000000"
android:text="00:00:00"/>
</RelativeLayout>
MainActivity.java
package playstore.com.a02backgroundtimer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_start, btn_cancel;
private TextView tv_timer;
String date_time;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
EditText et_hours;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
listener();
}
private void init() {
btn_start = (Button) findViewById(R.id.btn_timer);
tv_timer = (TextView) findViewById(R.id.tv_timer);
et_hours = (EditText) findViewById(R.id.et_hours);
btn_cancel = (Button) findViewById(R.id.btn_cancel);
mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mEditor = mpref.edit();
try {
String str_value = mpref.getString("data", "");
if (str_value.matches("")) {
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
if (mpref.getBoolean("finish", false)) {
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
et_hours.setEnabled(false);
btn_start.setEnabled(false);
tv_timer.setText(str_value);
}
}
} catch (Exception e) {
}
}
private void listener() {
btn_start.setOnClickListener(this);
btn_cancel.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_timer:
if (et_hours.getText().toString().length() > 0) {
int int_hours = Integer.valueOf(et_hours.getText().toString());
if (int_hours<=24) {
et_hours.setEnabled(false);
btn_start.setEnabled(false);
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
date_time = simpleDateFormat.format(calendar.getTime());
mEditor.putString("data", date_time).commit();
mEditor.putString("hours", et_hours.getText().toString()).commit();
Intent intent_service = new Intent(getApplicationContext(), Timer_Service.class);
startService(intent_service);
}else {
Toast.makeText(getApplicationContext(),"Please select the value below 24 hours",Toast.LENGTH_SHORT).show();
}
/*
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);*/
} else {
Toast.makeText(getApplicationContext(), "Please select value", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_cancel:
Intent intent = new Intent(getApplicationContext(),Timer_Service.class);
stopService(intent);
mEditor.clear().commit();
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
break;
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String str_time = intent.getStringExtra("time");
tv_timer.setText(str_time);
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver,new IntentFilter(Timer_Service.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
Timer_Service.java
package playstore.com.a02backgroundtimer;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class Timer_Service extends Service {
public static String str_receiver = "com.countdowntimerservice.receiver";
private Handler mHandler = new Handler();
Calendar calendar;
SimpleDateFormat simpleDateFormat;
String strDate;
Date date_current, date_diff;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
private Timer mTimer = null;
public static final long NOTIFY_INTERVAL = 1000;
Intent intent;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mEditor = mpref.edit();
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
intent = new Intent(str_receiver);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
strDate = simpleDateFormat.format(calendar.getTime());
Log.e("strDate", strDate);
twoDatesBetweenTime();
}
});
}
}
public String twoDatesBetweenTime() {
try {
date_current = simpleDateFormat.parse(strDate);
} catch (Exception e) {
}
try {
date_diff = simpleDateFormat.parse(mpref.getString("data",""));
} catch (Exception e) {
}
try {
long diff = date_current.getTime() - date_diff.getTime();
int int_hours = Integer.valueOf(mpref.getString("hours", ""));
long int_timer = TimeUnit.HOURS.toMillis(int_hours);
long long_hours = int_timer - diff;
long diffSeconds2 = long_hours / 1000 % 60;
long diffMinutes2 = long_hours / (60 * 1000) % 60;
long diffHours2 = long_hours / (60 * 60 * 1000) % 24;
if (long_hours > 0) {
String str_testing = diffHours2 + ":" + diffMinutes2 + ":" + diffSeconds2;
Log.e("TIME", str_testing);
fn_update(str_testing);
} else {
mEditor.putBoolean("finish", true).commit();
mTimer.cancel();
}
} catch (Exception e) {
mTimer.cancel();
mTimer.purge();
}
return "";
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("Service finish", "Finish");
}
private void fn_update(String str_time) {
intent.putExtra("time", str_time);
sendBroadcast(intent);
}
}
Once the app starts you need to mention the hours you want timer for ... Then also after killing the app when you restarts the app it will show the start time of the timer ... Now you customize you application a per your requirement .

AlarmManager, TimePicker and Wifi control. How to?

Well, my application would display wifi information (still work in progress for this) and set with a time picker when the wifi turns on. The problem is that i don't know how to connect the button inside the dialog of the picker "set" at the AlarmManager method. This is the code
package com.pkg.androidmemoryinfo;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends Activity implements OnClickListener {
private Button mTimeButton;
private Calendar mCalen;
private int hourOfDay;
private int minute;
private int ampm;
private static final int Time_PICKER_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTimeButton = (Button) findViewById(R.id.time_button);
mCalen = Calendar.getInstance();
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
mTimeButton.setOnClickListener(this);
// Creating a memory_info Object
MemoryInfo memory_info = new MemoryInfo();
// Using Activity Manager System Service
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(memory_info);
// Assign Memory Value to free_memory Variable
long free_memory = memory_info.availMem / 1048576L;
// Display free Ram Memory
TextView memoryInfoView = (TextView) findViewById(R.id.device_memory_status_txt);
memoryInfoView.setText("Free RAM Memory :-"+ free_memory + " MB");
}
public void run() {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String ssid = info.getSSID();
TextView ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView.setText(ssid);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
switch (id) {
case Time_PICKER_ID:
return new TimePickerDialog(this, TimePickerListener,
hourOfDay, minute, false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener TimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
// while dialog box is closed, below method is called.
public void onTimeSet(TimePicker view, int hour, int minute) {
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr = (ampm == 0) ? "AM" : "PM";
// Set the Time String in Button
TextView dateInfoView = (TextView) findViewById(R.id.dateinfo);
dateInfoView.setText("L'attivazione del Wi-Fi รจ impostata per le ore: " + hour12format + " : " + minute + " / " + ampmStr);
/// Here is the problem: Where have i to put this? ///
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
};
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(Time_PICKER_ID);
}
}
As you can see i don't know how put the wifi control. How can i do it? How can i create an AlarmManager with my code? I Need an example if possible. Thanks
This is one example of time picker that I think you can use.
--------Main Activity-------
package com.example.chxboxtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button start_intent_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start_intent_button = (Button) findViewById(R.id.start_intent_button);
start_intent_button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_intent_button: {
Intent intent = new Intent(this,TimePickerTest.class);
startActivity(intent);
}
break;
}
}
}
-------------Main Activity XML-----------------
<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"
>
<Button
android:id="#+id/start_intent_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Intent Time Picker"
android:layout_centerInParent="true"
/>
</RelativeLayout>
-------------TimePicker class ---------------
package com.example.chxboxtest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class TimePickerTest extends Activity implements OnClickListener{
private CheckBox cBox;
private TimePicker tPicker;
private TextView showTime;
private Button done;
private String hour;
private String minute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time_picker_layout);
initButtons();
}
private void initButtons() {
tPicker = (TimePicker) findViewById(R.id.time_picker);
showTime = (TextView) findViewById(R.id.get_time);
done = (Button)findViewById(R.id.done);
cBox = (CheckBox) findViewById(R.id.time_picker_checkbox);
cBox.setOnClickListener(this);
done.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
//If check enable or disble timePicker
case R.id.time_picker_checkbox: {
if (((CheckBox) v).isChecked()) {
Toast.makeText(this, "CHECKED", Toast.LENGTH_SHORT).show();
tPicker.setEnabled(false);
} else {
Toast.makeText(this, "NOT CHECKED", Toast.LENGTH_SHORT).show();
tPicker.setEnabled(true);
}
}
break;
//If Done button pressed get time selected by user
case R.id.done:{
tPicker.clearFocus();
// re-read the values, in my case i put them in a Time object.
hour = tPicker.getCurrentHour().toString();
minute = tPicker.getCurrentMinute().toString();
if(tPicker.getCurrentMinute().intValue() < 10){
String setTimeText = hour+ " : " + "0" + minute;
showTime.setText(setTimeText);
}else{
String setTimeText = hour+ " : " + minute;
showTime.setText(setTimeText);
}
}
break;
default:
break;
}
}
}
-------------TimerPicker XML------------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/timer_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/time_picker"
android:layout_toRightOf="#+id/time_picker_checkbox"
android:text="Check this to Cancel Alarm" />
<CheckBox
android:id="#+id/time_picker_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/time_picker"
android:layout_centerHorizontal="true" />
<TimePicker
android:id="#+id/time_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<Button
android:id="#+id/done"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/time_picker"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Done" />
<TextView
android:id="#+id/get_time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:text="Time"
android:textColor="#FF0000"
android:textSize="25sp" />
</RelativeLayout>
-------------Manifest.xml-----------
**<activity
android:name="com.example.chxboxtest.TimePickerTest"
android:configChanges="orientation|keyboardHidden">
</activity>**
Dont forget to add TimePicker class as activity.
BestPracice add all xml text in strings.xml
Cheers

stop watch logic

I want to develop a simple stop watch logic in android.
On clicking a list view the timer should start and on clicking the button the timer should stop. Can anyone please guide me. Any sample code will be of great help
Use the Stopwatch Class (For higher precision use System.nanoTime())
Add a Start() event and Stop() event on Button Presses. You'll need to update the UI so use a Thread/Handler Combination.
This should get you started.
EDIT: Added Code. (Nice Exercise! :) )
Use the Refresh_Rate to configure how often your UI is updated.
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity implements OnClickListener{
final int MSG_START_TIMER = 0;
final int MSG_STOP_TIMER = 1;
final int MSG_UPDATE_TIMER = 2;
Stopwatch timer = new Stopwatch();
final int REFRESH_RATE = 100;
Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_START_TIMER:
timer.start(); //start timer
mHandler.sendEmptyMessage(MSG_UPDATE_TIMER);
break;
case MSG_UPDATE_TIMER:
tvTextView.setText(""+ timer.getElapsedTime());
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIMER,REFRESH_RATE); //text view is updated every second,
break; //though the timer is still running
case MSG_STOP_TIMER:
mHandler.removeMessages(MSG_UPDATE_TIMER); // no more updates.
timer.stop();//stop timer
tvTextView.setText(""+ timer.getElapsedTime());
break;
default:
break;
}
}
};
TextView tvTextView;
Button btnStart,btnStop;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvTextView = (TextView)findViewById(R.id.TextView01);
btnStart = (Button)findViewById(R.id.Button01);
btnStop= (Button)findViewById(R.id.Button02);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
}
public void onClick(View v) {
if(btnStart == v)
{
mHandler.sendEmptyMessage(MSG_START_TIMER);
}else
if(btnStop == v){
mHandler.sendEmptyMessage(MSG_STOP_TIMER);
}
}
}
As st0le gave an excellent example by using Stopwatch class. I modified this class a little and add a few methods to it.
/*
Copyright (c) 2005, Corey Goldberg
StopWatch.java is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Modified: Bilal Rabbani bilalrabbani1#live.com (Nov 2013)
*/
package bilalrabbani1.at.live.com;
public class Stopwatch {
private long startTime = 0;
private boolean running = false;
private long currentTime = 0;
public void start() {
this.startTime = System.currentTimeMillis();
this.running = true;
}
public void stop() {
this.running = false;
}
public void pause() {
this.running = false;
currentTime = System.currentTimeMillis() - startTime;
}
public void resume() {
this.running = true;
this.startTime = System.currentTimeMillis() - currentTime;
}
//elaspsed time in milliseconds
public long getElapsedTimeMili() {
long elapsed = 0;
if (running) {
elapsed =((System.currentTimeMillis() - startTime)/100) % 1000 ;
}
return elapsed;
}
//elaspsed time in seconds
public long getElapsedTimeSecs() {
long elapsed = 0;
if (running) {
elapsed = ((System.currentTimeMillis() - startTime) / 1000) % 60;
}
return elapsed;
}
//elaspsed time in minutes
public long getElapsedTimeMin() {
long elapsed = 0;
if (running) {
elapsed = (((System.currentTimeMillis() - startTime) / 1000) / 60 ) % 60;
}
return elapsed;
}
//elaspsed time in hours
public long getElapsedTimeHour() {
long elapsed = 0;
if (running) {
elapsed = ((((System.currentTimeMillis() - startTime) / 1000) / 60 ) / 60);
}
return elapsed;
}
public String toString() {
return getElapsedTimeHour() + ":" + getElapsedTimeMin() + ":"
+ getElapsedTimeSecs() + "." + getElapsedTimeMili();
}
}
Regards
Instead of using listview you simply use a text view for timer and 3 buttons for stop start and reset . Using these you can make the java code accordingly
Good example, just in case if someone wants that layout file to go with this (pretty simple though).
<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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<EditText
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginLeft="18dp"
android:layout_marginTop="49dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextView01"
android:layout_marginTop="42dp"
android:layout_toRightOf="#+id/textView1"
android:text="Start" />
<Button
android:id="#+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Button01"
android:layout_marginTop="14dp"
android:layout_toRightOf="#+id/textView1"
android:text="Stop" />
IntentService based, no non-SDK dependencies and on a single file:
import android.app.Activity;
import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Main extends Activity {
static final String BROADCAST_ACTION = "com.cirosantilli.android_cheat.intent_service_text_view.BROADCAST";
static final String EXTENDED_DATA_STATUS = "com.cirosantilli.android_cheat.intent_service_text_view.BROADCAST";
static final String TAG = "com.cirosantilli";
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
final LinearLayout linearLayout = new LinearLayout(this);
Button button;
final Intent intent = new Intent(Main.this, MyService.class);
button = new Button(this);
button.setText("start service");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "start button");
Main.this.startService(intent.putExtra(Main.EXTENDED_DATA_STATUS, Main.this.i));
}
});
linearLayout.addView(button);
button = new Button(this);
button.setText("stop service");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "stop button");
Main.this.stopService(intent);
}
});
linearLayout.addView(button);
final TextView textView = new TextView(this);
textView.setText(Integer.toString(i));
linearLayout.addView(textView);
this.setContentView(linearLayout);
LocalBroadcastManager.getInstance(this).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Main.this.i = intent.getIntExtra(Main.EXTENDED_DATA_STATUS, 0);
textView.setText(Integer.toString(Main.this.i));
}
}, new IntentFilter(Main.BROADCAST_ACTION)
);
}
public static class MyService extends IntentService {
private Handler mHandler;
private int i = 1;
private boolean done;
public MyService() {
super("MyService");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "onHandleIntent");
this.i = intent.getIntExtra(Main.EXTENDED_DATA_STATUS, 0);
this.done = false;
while(!done) {
Log.d(TAG, "while true");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
LocalBroadcastManager.getInstance(this).sendBroadcast(
new Intent(Main.BROADCAST_ACTION)
.putExtra(Main.EXTENDED_DATA_STATUS, MyService.this.i));
this.i++;
}
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
this.done = true;
super.onDestroy();
}
}
}
For low precision only. We could get increased precision by using System.currentTimeMillis inside onHandleIntent instead of using the integer value, and reducing the sleep time to reduce latency.
Tested on Android 22. Standard build boilerplate here.

Categories

Resources