I am trying to schedule a task " a toast message" to appear in the time chosen by the user, but nothing is showing after that time and i can't see what is wrong in the code.
That's my code
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//set The Calendar to to the wanted time!
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
Intent setMsg = new Intent(MainActivity.this, TaskReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, setMsg, 0);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.setExact(AlarmManager.ELAPSED_REALTIME, calendar.getTimeInMillis(), pendingIntent);
}
}
public class TaskReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "it is working!", Toast.LENGTH_SHORT).show();
}
}
If there is a better way to schedule such a task please go ahead and introduce it.
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import com.yourcomp.yourapp.R;
import java.lang.ref.WeakReference;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class TestAct extends Activity {
private static class MyHandler extends Handler{
private WeakReference<Activity> activityWr;
public MyHandler(Activity activityMain){
activityWr = new WeakReference<>(activityMain);
}
#Override
public void handleMessage(Message inputMessage) {
if (activityWr.get() != null){
Toast.makeText(activityWr.get(),"Your text",Toast.LENGTH_LONG).show();
}
}
}
private MyHandler mHandler;
private Future<?> mToastTaskRef;
private static int NUMBER_OF_CORES =
Runtime.getRuntime().availableProcessors();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new MyHandler(this);
/**
* initialize UI & take input from user && call method
*/
}
private void showToastAfterUserSpecifiedDelay(int seconds){
mToastTaskRef = Executors.newScheduledThreadPool(NUMBER_OF_CORES).scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
mHandler.sendMessage(new Message());
}
}, /**initial delay*/60
,/**time*/seconds
,/**time unit*/ TimeUnit.MILLISECONDS);
}
private void stopToastTask(){
if (mToastTaskRef != null && !mToastTaskRef.isCancelled() && !mToastTaskRef.isDone()){
mToastTaskRef.cancel(true); //tru -- >interrupt even if it's running
}
}
}
Use this in your code Instead of manager.setExact method as follows:
manager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), interval, pendingIntent);
Related
I want to fire a local notification every 24 hours at a specific time say evening 6 o clock
i have refered this code
here
and
here
This is the code i am trying
package com.banane.alarm;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
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 static final String TAG = "BANANEALARM";
public AlarmManager alarmManager;
Intent alarmIntent;
PendingIntent pendingIntent;
Button bananaButton;
TextView notificationCount;
TextView notificationCountLabel;
int mNotificationCount;
static final String NOTIFICATION_COUNT = "notificationCount";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
// Restore value of members from saved state
mNotificationCount = savedInstanceState.getInt(NOTIFICATION_COUNT);
}
setContentView(R.layout.activity_main);
bananaButton = (Button)findViewById(R.id.bananaButton);
notificationCount = (TextView)findViewById(R.id.notificationCount);
notificationCountLabel = (TextView)findViewById(R.id.notificationCountLabel);
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(NOTIFICATION_COUNT, mNotificationCount);
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onNewIntent( Intent intent ) {
Log.i( TAG, "onNewIntent(), intent = " + intent );
if (intent.getExtras() != null)
{
Log.i(TAG, "in onNewIntent = " + intent.getExtras().getString("test"));
}
super.onNewIntent( intent );
setIntent( intent );
}
public void triggerAlarm(View v){
setAlarm();
bananaButton.setVisibility(View.GONE);
notificationCountLabel.setVisibility(View.VISIBLE);
notificationCount.setVisibility(View.VISIBLE);
notificationCount.setText("0");
}
public void setAlarm(){
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast( MainActivity.this, 0, alarmIntent, 0);
Calendar alarmStartTime = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR, 18); // At the hour you wanna fire
alarmStartTime.set(Calendar.MINUTE, 00); // Particular minute
alarmStartTime.set(Calendar.SECOND, 0);
// alarmStartTime.add(Calendar.MINUTE, 2);
alarmManager.setRepeating(AlarmManager.RTC, alarmStartTime.getTimeInMillis(), getInterval(), pendingIntent);
//Log.i(TAG,"Alarms set every two minutes.");
}
private int getInterval(){
int seconds = 60;
int milliseconds = 1000;
int repeatMS = seconds * 1440 * milliseconds;
return repeatMS;
}
#Override
protected void onStart(){
super.onStart();
updateUI();
}
public void cancelNotifications(){
Log.i(TAG,"All notifications cancelled.");
}
public void updateUI(){
MyAlarm app = (MyAlarm)getApplicationContext();
mNotificationCount = app.getNotificationCount();
notificationCount.setText(Integer.toString(mNotificationCount));
}
#Override
protected void onResume(){
super.onResume();
if(this.getIntent().getExtras() != null){
Log.i(TAG,"extras: " + this.getIntent().getExtras());
updateUI();
}
}
}
when try the code given in the example it works perfectly hwoever when i try to fire a notification i just wont show up what error
I am writing a code in Android code to create dynamic service or run-time service in Android app. I want to create one service and it will run two dynamic service internally , with the unique id. But i am not able to figure out how to do it? Please go though my sample code :
MyCode:
MainActivity.java
package com.example.multipleservice;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.TextView;
public class MainActivity extends Activity
{
TextView timer1;
TextView timer2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer1 = (TextView) findViewById(R.id.timer1);
timer2 = (TextView) findViewById(R.id.timer2);
Calendar calendar1 = Calendar.getInstance();
Intent myIntent1 = new Intent(MainActivity.this, MyService.class);
myIntent1.putExtra("Id", "1");
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent1,0);
AlarmManager alarmManager1 = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager1.set(AlarmManager.RTC, calendar1.getTimeInMillis(), pendingIntent1);
long tm1 = 0;
String ticket1 = "1";
SharedPreferences timer_saved1 = getApplicationContext().getSharedPreferences("TimerSave"+ticket1, 0);
long timerData1 = timer_saved1.getLong("timer"+ticket1, 0);
long timerValue1 = 0;
long diff_value1 = 36680;
if(timerData1!=0)
{
timerValue1 = timerData1*1000;
}
else
{
timerValue1 = diff_value1*1000;
}
tm1 = timerValue1;
RemainTime1 timera = new RemainTime1(tm1,1000);
timera.start();
Calendar calendar2 = Calendar.getInstance();
Intent myIntent2 = new Intent(MainActivity.this, MyService.class);
myIntent2.putExtra("Id", "2");
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent2,0);
AlarmManager alarmManager2 = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager2.set(AlarmManager.RTC, calendar2.getTimeInMillis(), pendingIntent2);
long tm2 = 0;
String ticket2 = "2";
SharedPreferences timer_saved2 = getApplicationContext().getSharedPreferences("TimerSave"+ticket2, 0);
long timerData2 = timer_saved2.getLong("timer"+ticket2, 0);
long timerValue2 = 0;
long diff_value2 = 36880;
if(timerData2!=0)
{
timerValue2 = timerData2*1000;
}
else
{
timerValue2 = diff_value2*1000;
}
tm2 = timerValue2;
RemainTime2 timerb = new RemainTime2(tm2,1000);
timerb.start();
}
public class RemainTime1 extends CountDownTimer
{
public RemainTime1(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
}
#Override
public void onTick(long arg0)
{
long millis = arg0;
long hour = TimeUnit.MILLISECONDS.toHours(millis);
long min = TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
long sec = TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
long hr = 0;
if(hour>=24)
{
hr = hour - 24*7;
}
else
{
hr = hour;
}
timer1.setText(hr+" hr : "+min+" mins : "+sec+" sec ");
}
}
public class RemainTime2 extends CountDownTimer
{
public RemainTime2(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
}
#Override
public void onTick(long arg0)
{
long millis = arg0;
long hour = TimeUnit.MILLISECONDS.toHours(millis);
long min = TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
long sec = TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
long hr = 0;
if(hour>=24)
{
hr = hour - 24*7;
}
else
{
hr = hour;
}
timer2.setText(hr+" hr : "+min+" mins : "+sec+" sec ");
}
}}
MySerivce.java
package com.example.multipleservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyService extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
} }
MyAlarmService.java
package com.example.multipleservice;
import java.util.concurrent.TimeUnit;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Chronometer;
import android.widget.Toast;
public class MyAlarmService extends Service
{
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onStart(Intent intent, int startId)
{
String ticket = intent.getStringExtra("Id");
SharedPreferences timer_saved = getApplicationContext().getSharedPreferences("TimerSave"+ticket, 0);
long timerData = timer_saved.getLong("timer"+ticket, 0);
long timerValue = 0;
long diff_value = 0;
if(timerData!=0)
{
timerValue = timerData*1000;
}
else
{
timerValue = diff_value*1000;
}
RemainTime timer = new RemainTime(timerValue,1000);
timer.start();
super.onStart(intent, startId);
}
public class RemainTime extends CountDownTimer
{
public RemainTime(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
}
#Override
public void onTick(long arg0)
{
long millis = arg0;
long hour = TimeUnit.MILLISECONDS.toHours(millis);
long min = TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
long sec = TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
long hr = 0;
if(hour>=24)
{
hr = hour - 24*7;
}
else
{
hr = hour;
}
}
} }
This is my above code , i am getting NullPointerException in getStringExtra section. I want to create two different timer and when i will close the application , but still the two timer should run in the service and when i will open the app again then i should see the updated timer value from the two clock.
Please help me out !!! Please suggest me some possible solution.
I have 2 TextViews from which I can call a time picker. But Im not able to figure out from which TextBox I callt the time Picker.
Following is the code snippset from the Activity:
case R.id.tv_to_night:
// show the time picker dialog
TimePickerFragment newFragmentNight = new TimePickerFragment();
newFragmentNight.show(getSupportFragmentManager(), "timePicker to");
break;
case R.id.tv_from_night:
// show the time picker dialog
TimePickerFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker from");
break;
Here I want to know from which TextBox I get the Time:
public void onTimePicked(Calendar time) {
if(depending from were it was called)
tv_from_night.setText(DateFormat.format("h:mm a", time));
else
tv_to_night.setText(DateFormat.format("h:mm a", time));
}
TimePickerFragment
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
import java.util.Calendar;
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
private TimePickedListener mListener;
public Dialog onCreateDialog(Bundle savedInstanceState) {
// use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onAttach(Activity activity) {
// when the fragment is initially shown (i.e. attached to the activity),
// cast the activity to the callback interface type
super.onAttach(activity);
try {
mListener = (TimePickedListener) activity;
} catch(ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement " + TimePickedListener.class.getName());
}
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// when the time is selected, send it to the activity via its callback
// interface method
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
mListener.onTimePicked(c);
}
public static interface TimePickedListener {
public void onTimePicked(Calendar time);
}
}
Solution
Activity:
case R.id.tv_to_night:
TimePickerFragment newFragmentNight = TimePickerFragment.newInstance(TO_TIME_PICKER_ID);
newFragmentNight.show(getSupportFragmentManager(), "timePicker");
break;
case R.id.tv_from_night:
TimePickerFragment newFragment = TimePickerFragment.newInstance(FROM_TIME_PICKER_ID);
newFragment.show(getSupportFragmentManager(), "timePicker");
break;
Here you get the time with the id:
public void onTimePicked(Calendar time, int id) {
Log.i("TimePicker", "Time picker called from id " + id);
switch(id) {
case FROM_TIME_PICKER_ID:
// do thomething
break;
case TO_TIME_PICKER_ID:
// do thomething
break;
}
}
TimePickerFragment:
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
import java.util.Calendar;
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
private int mId;
private TimePickedListener mListener;
static TimePickerFragment newInstance(int id) {
Bundle args = new Bundle();
args.putInt("picker_id", id);
TimePickerFragment fragment = new TimePickerFragment();
fragment.setArguments(args);
return fragment;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
// use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
mId = getArguments().getInt("picker_id");
// create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onAttach(Activity activity) {
// when the fragment is initially shown (i.e. attached to the activity),
// cast the activity to the callback interface type
super.onAttach(activity);
try {
mListener = (TimePickedListener) activity;
} catch(ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement " + TimePickedListener.class.getName());
}
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// when the time is selected, send it to the activity via its callback
// interface method
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
if(mListener != null)
mListener.onTimePicked(c, mId);
}
public static interface TimePickerDialogListener {
public void onTimeSet(int id, TimePicker view, int hourOfDay, int minute);
}
public static interface TimePickedListener {
public void onTimePicked(Calendar time, int id);
}
}
I am creating alarm alert for appointment reminder for that I am using following code.Code is working very well it showing me alarm alert but only problem is that, it is not differentiate alarm between am and pm, suppose if I set alarm for 7am and currently 7pm in device then also my alert dialog shows. How can I manage that am and pm? I used this link for ref
http://wptrafficanalyzer.in/blog/setting-up-alarm-using-alarmmanager-and-waking-up-screen-and-unlocking-keypad-on-alarm-goes-off-in-android/
AlertDemo.class
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.WindowManager.LayoutParams;
public class AlertDemo extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
/** Turn Screen On and Unlock the keypad when this alert dialog is displayed */
getActivity().getWindow().addFlags(LayoutParams.FLAG_TURN_SCREEN_ON | LayoutParams.FLAG_DISMISS_KEYGUARD);
/** Creating a alert dialog builder */
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
/** Setting title for the alert dialog */
builder.setTitle("Alarm");
/** Setting the content for the alert dialog */
builder.setMessage("An Alarm by AlarmManager");
/** Defining an OK button event listener */
builder.setPositiveButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/** Exit application on click OK */
getActivity().finish();
}
});
/** Creating the alert dialog window */
return builder.create();
}
/** The application should be exit, if the user presses the back button */
#Override
public void onDestroy() {
super.onDestroy();
getActivity().finish();
}
}
Appointment.class
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;
public class Appointment extends Activity {
Button date, time, save;
private static final int DIALOG_DATE = 1;
private static final int DIALOG_TIME = 2;
private int year;
private int month;
private int day;
int i;
String strmonth, strday, stryear;
String months[] = { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" };
int intmonth, intday, intyear, inthour, intminutes;
Calendar c = Calendar.getInstance();
private SimpleDateFormat timeFormatter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doctor_appointment);
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
date = (Button) findViewById(R.id.btnsetdate);
time = (Button) findViewById(R.id.btnsettime);
save = (Button) findViewById(R.id.btnsave);
timeFormatter = new SimpleDateFormat("hh:mm a");
// c.set(Calendar.MONTH, 4);
date.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(DIALOG_DATE);
}
});
time.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(DIALOG_TIME);
}
});
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent("com.example.healthmanager.DemoActivity");
/** Creating a Pending Intent */
PendingIntent operation = PendingIntent.getActivity(
getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
/** Getting a reference to the System Service ALARM_SERVICE */
AlarmManager alarmManager = (AlarmManager) getBaseContext()
.getSystemService(ALARM_SERVICE);
String strtime = time.getText().toString();
Log.v("str btntime", strtime);
String[] splitstrtime = strtime.split(":");
Log.v("timestr1", splitstrtime[0]);
Log.v("timestr2", splitstrtime[1]);
int splithour = Integer.parseInt(splitstrtime[0]);
String[] splitsecond = splitstrtime[1].split(" ");
Log.v("split str second", splitsecond[0]);
int splitmin = Integer.parseInt(splitsecond[0]);
/**
* Creating a calendar object corresponding to the date and time
* set by the user
*/
// GregorianCalendar calendar = new
// GregorianCalendar(year,month,day, hour, minute);
GregorianCalendar calendar = new GregorianCalendar(intyear,
intmonth, intday, splithour, splitmin);
/**
* Converting the date and time in to milliseconds elapsed since
* epoch
*/
long alarm_time = calendar.getTimeInMillis();
/** Setting an alarm, which invokes the operation at alart_time */
alarmManager
.set(AlarmManager.RTC_WAKEUP, alarm_time, operation);
/** Alert is set successfully */
Toast.makeText(getBaseContext(), "Alarm is set successfully",
Toast.LENGTH_SHORT).show();
}
});
}
// For date dialog
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DATE:
return new DatePickerDialog(this, datePickerListener, year, month,
day);
case DIALOG_TIME:
return new TimePickerDialog(this, new OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
time.setText(timeFormatter.format(c.getTime()));
}
}, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), false);
}
return null;
}
// For date
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year1, int monthOfYear,
int dayOfMonth) {
year = year1;
month = monthOfYear;
day = dayOfMonth;
// date.setText(dateFormatter.format(dateTime.getTime()));
updateDisplay();
}
};
public String getMonthForInt(int m) {
String month = "invalid";
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
if (m >= 0 && m <= 11) {
month = months[m];
}
return month;
}
private void updateDisplay() {
// String strDOB = month + 1 + "/" + day + "/" + year;
// Log.v("strDOB : ", strDOB);
intmonth = month;
intday = day;
intyear = year;
strmonth = Integer.toString(intmonth);
strday = Integer.toString(intday);
stryear = Integer.toString(intyear);
Log.v("month value", strmonth);
Log.v("day value", strday);
Log.v("year value", stryear);
// int one=7;
// Log.v("string limit",one.length());
for (i = 0; i < intmonth; i++) {
String strone = Integer.toString(intmonth);
strone = months[i];
// String intmonth=Integer.toString(months);
}
Log.v("month value", months[i].toString());
date.setText(months[i] + " " + day + "," + year);
}
}
DemoActivity.class
public class DemoActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Creating an Alert Dialog Window */
AlertDemo alert = new AlertDemo();
/** Opening the Alert Dialog Window */
alert.show(getSupportFragmentManager(), "AlertDemo");
}
}
You are not handling the AM/PM. Just put these lines of code...
int timeDifference=0;
String ampm=splitampmtime[1];
if(ampm.matches("PM")){
timeDifference=12;
}
int splithour = timeDifference+Integer.parseInt(splitstrtime[0]);
String[] splitsecond = splitstrtime[1].split(" ");
Well you can add the check for AM and PM in your save.setOnClickListener() and change the value of hour accordingly:
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
.....
int splithour = Integer.parseInt(splitstrtime[0]); //10
String[] splitsecond = splitstrtime[1].split(" "); //40, am
Log.v("split str second", splitsecond[0]);
int splitmin = Integer.parseInt(splitsecond[0]); //40
if(splitsecond[1].equalsIgnoreCase("pm")) {
splithour += 12;
} else if(splitsecond[1].equalsIgnoreCase("am") && splithour == 12) {
splithour = 0;
}
....
}
}
Please use:-
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + alarm_time,
operation);
in place of
alarmManager.set(AlarmManager.RTC_WAKEUP, alarm_time, operation);
Read:-
SystemClock.elapsedRealtime() is the current time in millis add the total time to skip from now to alarm in millis.
I used to set the alarm using this method:
/**
* Set the Alarm
*
* #param context the activity context
* #param id the alarm ID for this app
* #param hour the alarm hour
* #param minute the alarm minute
* #param timeZone the timezone am = Calendar.AM or pm = Calendar.PM
*/
public static void setAlarm(Context context, int id, int hour, int minute, int timeZone) {
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.AM_PM, timeZone);
Intent intent = new Intent(context, PopupActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, id, intent, 0);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 10, pIntent);
}
I have a TimePickerDialog that I would like to show the user when she pushes on a button, so that she can choose a time to set the display to (some time other than the current time). Currently when the button is pushed the current time is displayed in a TextView and a Toast. Also the screen Darkens and a small box in the center of screen appears. The TimePickerDialog does not display to the user.
Here's the code;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class AddAlarmActivity extends FragmentActivity implements TimePickerDialog.OnTimeSetListener, TimePickerDialog.OnDismissListener {
Button setTime;
public int hour_local;
public int minute_local;
public Dialog onCreateDialog;
public TimePicker timePicker;
public TextView displayAlarm;
static final int TIME_DIALOG_ID = 999;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_alarm);
//add a TextView thing to this part
setTime = (Button) findViewById(R.id.button_set_time);
displayAlarm = (TextView) findViewById(R.id.tvDisplayTime);
setTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onCreateDialog(savedInstanceState);
showTimePickerDialog(timePicker);
displayAlarm.setText(hour_local + ":" + minute_local);
}
});
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
hour_local = c.get(Calendar.HOUR_OF_DAY);
minute_local = c.get(Calendar.MINUTE);
Context context = getApplicationContext();
CharSequence text = hour_local + ":" + minute_local;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getApplicationContext(), this, hour_local, minute_local,
DateFormat.is24HourFormat(getApplicationContext()));
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new DialogFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void onDismiss(DialogInterface dialog){
System.out.println("oui c'est très bon !");
}
public void onTimeSet(TimePicker view, int hour_l, int minute_l) {
hour_local = hour_l;
minute_local = minute_l;
System.out.println("voila");
}
}
I would advice that you follow the developer sites way of doing it:
Create a static class that handles the dialog fragment
public static class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
}
}
Call this method in your button on click listener:
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
Source here.
public class AddAlarmActivity extends FragmentActivity {
Button setTime;
public static int hour_local;
public static int minute_local;
public Dialog onCreateDialog;
public TimePicker timePicker;
public static TextView displayAlarm;
public static int hour_alarm;
public static int minute_alarm;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_alarm);
setTime = (Button) findViewById(R.id.button_set_time);
displayAlarm = (TextView) findViewById(R.id.tvDisplayTime);
final Calendar c = Calendar.getInstance();
hour_local = c.get(Calendar.HOUR_OF_DAY);
minute_local = c.get(Calendar.MINUTE);
displayAlarm.setText(hour_local + ":" + minute_local);
setTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog(timePicker);
}
});
}
public void onTimeSet(TimePicker view, int hour_l, int minute_l) {
// intentionally blank
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
/*New static class*/
public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
hour_local = c.get(Calendar.HOUR_OF_DAY);
minute_local = c.get(Calendar.MINUTE);
Context context = getActivity();
CharSequence text = hour_local + ":" + minute_local;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour_local, minute_local,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hour_l, int minute_l) {
hour_alarm = hour_l;
minute_alarm = minute_l;
displayAlarm.setText(hour_alarm + ":" + minute_alarm);
}
}
}
TimePickerDialog dialog = new TimePickerDialog(this,OnTimeSet,DateTime.Now.Hour,DateTime.Now.Minute,true);
dialog.Show();
void OnTimeSet (object sender, TimePickerDialog.TimeSetEventArgs e)
{
}