I've created an app which sets the alarm with a certain delay, etc. which is saved in shared preferences. I wanted to create a widget which would start the alarm cycle by pressing it, with all those settings I've written into app while it was open. Here's my widget code:
public class SetAlarmWidget extends AppWidgetProvider {
Double delay;
int howManyTimes;
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
double delayHours;
double delayMinutes;
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
boolean amountRestricted = sharedPreferences.getBoolean("amountSwitchState", false);
if (sharedPreferences.getString("delayHours", "0").equals("") && sharedPreferences.getString("delayMinutes", "0").equals("")) {
delay = 0.0;
} else if(sharedPreferences.getString("delayHours", "0").equals("")){
delayMinutes = Double.parseDouble(sharedPreferences.getString("delayMinutes", "0"));
delay = 60*1000*delayMinutes;
}else if(sharedPreferences.getString("delayMinutes", "0").equals("")){
delayHours = Double.parseDouble(sharedPreferences.getString("delayHours", "0"));
delay = (60 * 60 * 1000) * delayHours;
}else{
delayMinutes = Double.parseDouble(sharedPreferences.getString("delayMinutes", "0"));
delayHours = Double.parseDouble(sharedPreferences.getString("delayHours", "0"));
delay = (60 * 60 * 1000) * delayHours+ (60*1000) * delayMinutes;
}
if (sharedPreferences.getString("amount", "0").equals("")) {
howManyTimes = 0;
} else {
howManyTimes = Integer.parseInt(sharedPreferences.getString("amount", "0"));
}
if (delay>0) {
double tmpDelay = delay;
startAlarm(context);
}
}
}
private void startAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent, 0);
assert alarmManager != null;
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + delay.longValue(),
delay.longValue(), pendingIntent);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
boolean amountRestricted = sharedPreferences.getBoolean("amountSwitchState", false);
boolean hourRestricted = sharedPreferences.getBoolean("hourSwitchState", false);
Calendar calendar = Calendar.getInstance();
int currentHours = calendar.get(Calendar.HOUR_OF_DAY);
int currentMinutes = calendar.get(Calendar.MINUTE) + currentHours * 60;
int minutesToLast=0;
if(hourRestricted)
{
String setTime = sharedPreferences.getString("lastHour", "false");
String[] parts = setTime.split(":");
String part1 = parts[0]; // 004
String part2 = parts[1];
int setHours = Integer.parseInt(part1);
int setMinutes = Integer.parseInt(part2) + setHours * 60;
if (!setTime.equals("false")) {
if (currentMinutes < setMinutes) {
minutesToLast = setMinutes - currentMinutes;
} else {
minutesToLast = 24 * 60 - currentMinutes + setMinutes;
}
}
}
int howManyTimesFromHour=-1;
int minutesTemp=minutesToLast;
while(minutesTemp>=0)
{
minutesTemp-=delay/60000;
howManyTimesFromHour++;
}
if(amountRestricted && hourRestricted)
{
editor.putInt("desiredBursts", Math.min(howManyTimes, howManyTimesFromHour));
editor.putBoolean("setRestricted", true);
}else if(amountRestricted){
editor.putInt("desiredBursts", howManyTimes);
editor.putBoolean("setRestricted", true);
}else if(hourRestricted){
editor.putInt("desiredBursts", howManyTimesFromHour);
editor.putBoolean("setRestricted", true);
}else{
editor.putInt("desiredBursts", 1);
editor.putBoolean("setRestricted", false);
}
editor.putInt("elapsedBursts", 0);
editor.putString("setDelay", delay.toString());
editor.apply();
}
}
The problem is that when I press the widget it does nothing. The method startAlarm is different from the method from MainActivity only with using context instead of this
Related
I'm trying to start a service that adds an item to RecyclerView every 24 hours (every day). I used this code but it doesn't work:
BackgroundService.java
public class BackgroundService extends Service {
private boolean isRunning;
private Context context;
private Thread backgroundThread;
SharedPreferences pref;
String isMorningChecked;
String isEveningChecked;
String isNightChecked;
String isEchuraistChecked;
String isConfessChecked;
String isBibleChecked;
String Date;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
this.context = this;
this.isRunning = false;
this.backgroundThread = new Thread(addNewNote);
}
private Runnable addNewNote = new Runnable() {
#Override
public void run() {
Log.e("isRunning", "Yeeeeeeeeeees!");
pref = getApplicationContext().getSharedPreferences("checkStates", 0);
String checkMorningState = pref.getString("morning", "False");
String checkEveningState = pref.getString("evening", "False");
String checkNightState = pref.getString("night", "False");
String checkEchuraistState = pref.getString("echuraist", "False");
String checkConfessState = pref.getString("confess", "False");
String checkBibleState = pref.getString("bible", "False");
String writeYourNotes = pref.getString("writeNotes", "");
SimpleDateFormat sdf = new SimpleDateFormat("E", new Locale("ar"));
final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd");
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Date = sdf2.format(timestamp).toString();
if(checkMorningState.equals("True")){
isMorningChecked = "+";
}else{
isMorningChecked = "-";
}
if(checkEveningState.equals("True")){
isEveningChecked = "+";
}else{
isEveningChecked = "-";
}
if(checkNightState.equals("True")){
isNightChecked = "+";
}else{
isNightChecked = "-";
}
if(checkEchuraistState.equals("True")){
isEchuraistChecked = "+";
}else{
isEchuraistChecked = "-";
}
if(checkConfessState.equals("True")){
isConfessChecked = "+";
}else{
isConfessChecked = "-";
}
if(checkBibleState.equals("True")){
isBibleChecked = "+";
}else{
isBibleChecked = "-";
}
AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "Note").allowMainThreadQueries().build();
db.userDao().insertAll(new Note(sdf.format(timestamp), sdf2.format(timestamp).toString(), isMorningChecked, isEveningChecked, isNightChecked, isEchuraistChecked, isConfessChecked, isBibleChecked, writeYourNotes));
stopSelf();
}
};
#Override
public void onDestroy() {
super.onDestroy();
this.isRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!this.isRunning){
this.isRunning = true;
this.backgroundThread.start();
}
return START_STICKY;
}
}
BoardCastReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, BackgroundService.class));
}
}
Home.java
Intent alarm = new Intent(this, AlarmReceiver.class);
boolean alarmRunning = ((PendingIntent.getBroadcast(this,0,alarm,PendingIntent.FLAG_NO_CREATE)) != null);
if(alarmRunning == false){
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,alarm,0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 1000, pendingIntent);
I have tried this but the Service works once or twice and then it stops and sometimes it gives me the following error:
java.lang.IllegalStateException: Not allowed to start service Intent
Background service can not be used for long running tasks on Android 8.0 onwards. Please use JobScheduler API or Workmanager to achieve the desired results. Consult the following link for details.
https://developer.android.com/topic/libraries/architecture/workmanager
This time reminder class, time reminder is crashing on click and erroe goes on "custom.showDialogue" and the error is the following:
FATAL EXCEPTION: main
Process: com.appmetrik.notestakingapp, PID: 18607
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.app.notes.CustomDateTimePicker.showDialog()' on a null object reference
at com.app.notes.AddReminder.onClick(AddReminder.java:261)
public class AddReminder extends AppCompatActivity implements
android.view.View.OnClickListener`{
CustomDateTimePicker custom = null;
TextView txt_Time;
TextView txt_Date;
TextView txt_Day;
EditText et_Reminder_Title;
EditText et_Reminder_Description;
ImageButton btn_Submit_Reminder;
public static String var_Reminder_Title;
public String var_Reminder_Description;
public String var_Reminder_Time;
public String var_Reminder_Date;
public String var_Reminder_Day;
public int var_Not_Day;
public int var_Not_Month;
public int var_Not_Year;
public int var_Not_Hour;
public int var_Not_Min;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_reminder);
txt_Time = (TextView) findViewById(R.id.txtEditTime);
txt_Time.setOnClickListener(this);
txt_Date = (TextView) findViewById(R.id.txtEditDate);
txt_Date.setOnClickListener(this);
txt_Day = (TextView) findViewById(R.id.txtEditDay);
txt_Day.setOnClickListener(this);
et_Reminder_Title= (EditText) findViewById(R.id.etEditReminderTitle);
et_Reminder_Description = (EditText) findViewById(R.id.etReminderDescription);
btn_Submit_Reminder = (ImageButton) findViewById(R.id.imgBtnSubmitReminder);
btn_Submit_Reminder.setOnClickListener(this);
try {
custom = new CustomDateTimePicker(AddReminder.this,
new CustomDateTimePicker.ICustomDateTimeListener() {
#Override
public void onSet(Dialog dialog, Calendar calendarSelected,
Date dateSelected, int year, String monthFullName,
String monthShortName, int monthNumber, int date,
String weekDayFullName, String weekDayShortName,
int hour24, int hour12, int min, int sec,
String AM_PM) {
txt_Time.setText(hour12 + ":" + min + " " + AM_PM);
txt_Date.setText(calendarSelected
.get(Calendar.DAY_OF_MONTH)
+ "/" + (monthNumber + 1) + "/" + year);
txt_Day.setText(weekDayFullName);
var_Not_Hour = hour24;
var_Not_Min = min;
var_Not_Month = monthNumber;
var_Not_Day = calendarSelected
.get(Calendar.DAY_OF_MONTH);
var_Not_Year = year;
}
#Override
public void onCancel() {
}
});
/**
* Pass Directly current time format it will return AM and PM if you set
* false
*/
custom.set24HourFormat(false);
/**
* Pass Directly current data and time to show when ita pop up
*/
custom.setDate(Calendar.getInstance());
}
catch (Exception ex){
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Calendar Initialization Failed...", Toast.LENGTH_LONG).show();
}
findViewById(R.id.button_date).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
custom.showDialog();
}
});
}
public void getValues(){
var_Reminder_Title = et_Reminder_Title.getText().toString();
var_Reminder_Time = txt_Time.getText().toString();
var_Reminder_Date = txt_Date.getText().toString();
var_Reminder_Day = txt_Day.getText().toString();
var_Reminder_Description = et_Reminder_Description.getText().toString();
}
public boolean validate()
{
boolean allValid = true;
if(et_Reminder_Title.getText().toString().trim().length() == 0)
{
allValid = false;
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
et_Reminder_Title.setError("Please Enter a Reminder Title here");
}
});
}
if(txt_Time.getText() == "Time")
{
allValid = false;
runOnUiThread(new Runnable() {
#Override
public void run() {
et_Reminder_Title.setError("Tap Here to Select a Due Date and Time");
}
});
}
return allValid;
}
public void addReminder(){
SQLiteDatabase db = null;
db = openOrCreateDatabase("NTA_DB", MODE_PRIVATE, null);
try {
db.execSQL("CREATE TABLE IF NOT EXISTS reminders(ReminderId INTEGER PRIMARY KEY AUTOINCREMENT, ReminderTitle Text,ReminderTime Text,ReminderDate Text,ReminderDay Text, ReminderDescription Text);");
db.execSQL("INSERT INTO reminders(ReminderTitle,ReminderTime,ReminderDate,ReminderDay,ReminderDescription) VALUES('"+var_Reminder_Title+"','"+var_Reminder_Time+"','"+var_Reminder_Date+"','"+var_Reminder_Day+"','"+var_Reminder_Description+"');");
db.close();
Toast.makeText(AddReminder.this, "" +
"Reminder Added Successfully", Toast.LENGTH_LONG).show();
}catch(Exception ex) {
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Reminder Cannot be Saved", Toast.LENGTH_LONG).show();
db.close();
}
}
public void addNotification(){
SQLiteDatabase db = null;
db = openOrCreateDatabase("NTA_DB", MODE_PRIVATE, null);
try {
db.execSQL("CREATE TABLE IF NOT EXISTS notifications(NotificationId INTEGER PRIMARY KEY AUTOINCREMENT, NotificationTitle Text);");
db.execSQL("INSERT INTO notifications(NotificationTitle) VALUES('"+var_Reminder_Title+"');");
db.close();
Toast.makeText(AddReminder.this, "" +
"Notification Added Successfully", Toast.LENGTH_LONG).show();
}catch(Exception ex) {
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Notification Cannot be Saved", Toast.LENGTH_LONG).show();
db.close();
}
}
public void remind(){
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// set for 30 seconds later
alarmMgr.set(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis() + 30000, alarmIntent);
Toast.makeText(AddReminder.this, "Set Alarm", Toast.LENGTH_LONG).show();
}
public void al(){
// for Alarm 25/12/2012 at 12.00
Calendar myAlarmDate = Calendar.getInstance();
myAlarmDate.setTimeInMillis(System.currentTimeMillis());
myAlarmDate.set(var_Not_Year, var_Not_Month, var_Not_Day, var_Not_Hour, var_Not_Min, 0);
//Toast.makeText(AddReminder.this, ""+var_Not_Year+" "+ var_Not_Month+" "+ var_Not_Day+" "+var_Not_Hour+" "+var_Not_Min+" "+ 0, Toast.LENGTH_LONG).show();
//Create alarm manager
AlarmManager alarmMgr0 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
//Create pending intent & register it to your alarm notifier class
Intent intent0 = new Intent(this, AlarmReceiver.class);
//intent0.putExtra("Ringtone",getResources().getResourceName(R.raw.bbm_tone));
intent0.putExtra("Heading",var_Reminder_Title);
PendingIntent pendingIntent0 = PendingIntent.getBroadcast(this, 0, intent0, 0);
//set timer you want alarm to work (here I have set it to 7.20pm)
//Intent intent0 = new Intent(this, OldEntryRemover.class);
/* Calendar timeOff9 = Calendar.getInstance();
timeOff9.set(Calendar.MONTH,12);
timeOff9.set(Calendar.DAY_OF_MONTH,1);
timeOff9.set(Calendar.YEAR,2015);
timeOff9.set(Calendar.HOUR_OF_DAY, 16);
timeOff9.set(Calendar.MINUTE, 45);
timeOff9.set(Calendar.SECOND, 0);
*/
//set that timer as a RTC Wakeup to alarm manager object
alarmMgr0.set(AlarmManager.RTC_WAKEUP, myAlarmDate.getTimeInMillis(), pendingIntent0);
// Toast.makeText(AddReminder.this, "Alarm", Toast.LENGTH_LONG).show();
}
#Override
public void onBackPressed ()
{
Intent intent = new Intent(AddReminder.this, FrontScreen.class);
startActivity(intent);
finish();
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.txtEditTime || v.getId() == R.id.txtEditDate || v.getId() == R.id.txtEditDay){
// custom.showDialog();
}
else if(v.getId() == R.id.imgBtnSubmitReminder) {
if (validate() == true) {
getValues();
addReminder();
// addNotification();
al();
Intent intent = new Intent(AddReminder.this, FrontScreen.class);
startActivity(intent);
finish();
}
}
}
}
this is custom date time picker class which is having the method showDialogue and it is using in the previous class. It is working perfectly on the version is less than 5.0 API but it is crashing on the version of 5.1 error is datetimepicker cannot be initialized.
public class CustomDateTimePicker implements android.view.View.OnClickListener {
private DatePicker datePicker;
private TimePicker timePicker;
private ViewSwitcher viewSwitcher;
private final int SET_DATE = 100, SET_TIME = 101, SET = 102, CANCEL = 103;
private Button btn_setDate, btn_setTime, btn_set, btn_cancel;
private Calendar calendar_date = null;
private Activity activity;
private ICustomDateTimeListener iCustomDateTimeListener = null;
private Dialog dialog;
private boolean is24HourView = true, isAutoDismiss = true;
private int selectedHour, selectedMinute;
public CustomDateTimePicker(Activity a,
ICustomDateTimeListener customDateTimeListener) {
activity = a;
iCustomDateTimeListener = customDateTimeListener;
dialog = new Dialog(activity);
// Context context = new ContextThemeWrapper(new MyContextWrapper, android.R.style.Theme_Holo_Light_Dialog);
dialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
resetData();
}
});
/*
dialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
resetData();
}
});*/
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
View dialogView = getDateTimePickerLayout();
dialog.setContentView(dialogView);
}
public View getDateTimePickerLayout() {
LinearLayout.LayoutParams linear_match_wrap = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
LinearLayout.LayoutParams linear_wrap_wrap = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
FrameLayout.LayoutParams frame_match_wrap = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams button_params = new LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
LinearLayout linear_main = new LinearLayout(activity);
linear_main.setLayoutParams(linear_match_wrap);
linear_main.setOrientation(LinearLayout.VERTICAL);
linear_main.setGravity(Gravity.CENTER);
LinearLayout linear_child = new LinearLayout(activity);
linear_child.setLayoutParams(linear_wrap_wrap);
linear_child.setOrientation(LinearLayout.VERTICAL);
LinearLayout linear_top = new LinearLayout(activity);
linear_top.setLayoutParams(linear_match_wrap);
btn_setDate = new Button(activity);
btn_setDate.setLayoutParams(button_params);
btn_setDate.setText("Set Date");
btn_setDate.setId(SET_DATE);
btn_setDate.setOnClickListener(this);
btn_setTime = new Button(activity);
btn_setTime.setLayoutParams(button_params);
btn_setTime.setText("Set Time");
btn_setTime.setId(SET_TIME);
btn_setTime.setOnClickListener(this);
linear_top.addView(btn_setDate);
linear_top.addView(btn_setTime);
viewSwitcher = new ViewSwitcher(activity);
viewSwitcher.setLayoutParams(frame_match_wrap);
datePicker = new DatePicker(activity);
timePicker = new TimePicker(activity);
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
selectedHour = hourOfDay;
selectedMinute = minute;
}
});
viewSwitcher.addView(timePicker);
viewSwitcher.addView(datePicker);
LinearLayout linear_bottom = new LinearLayout(activity);
linear_match_wrap.topMargin = 8;
linear_bottom.setLayoutParams(linear_match_wrap);
btn_set = new Button(activity);
btn_set.setLayoutParams(button_params);
btn_set.setText("Set");
btn_set.setId(SET);
btn_set.setOnClickListener(this);
btn_cancel = new Button(activity);
btn_cancel.setLayoutParams(button_params);
btn_cancel.setText("Cancel");
btn_cancel.setId(CANCEL);
btn_cancel.setOnClickListener(this);
linear_bottom.addView(btn_set);
linear_bottom.addView(btn_cancel);
linear_child.addView(linear_top);
linear_child.addView(viewSwitcher);
linear_child.addView(linear_bottom);
linear_main.addView(linear_child);
//Invisible Calender View
datePicker.getCalendarView().setVisibility(View.GONE);
return linear_main;
}
public void showDialog() {
if (!dialog.isShowing()) {
if (calendar_date == null)
calendar_date = Calendar.getInstance();
selectedHour = calendar_date.get(Calendar.HOUR_OF_DAY);
selectedMinute = calendar_date.get(Calendar.MINUTE);
timePicker.setIs24HourView(is24HourView);
timePicker.setCurrentHour(selectedHour);
timePicker.setCurrentMinute(selectedMinute);
datePicker.updateDate(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DATE));
dialog.show();
btn_setDate.performClick();
btn_setTime.performClick();
}
}
public void setAutoDismiss(boolean isAutoDismiss) {
this.isAutoDismiss = isAutoDismiss;
}
public void dismissDialog() {
if (!dialog.isShowing())
dialog.dismiss();
}
public void setDate(Calendar calendar) {
if (calendar != null)
calendar_date = calendar;
}
public void setDate(Date date) {
if (date != null) {
calendar_date = Calendar.getInstance();
calendar_date.setTime(date);
}
}
public void setDate(int year, int month, int day) {
if (month < 12 && month >= 0 && day < 32 && day >= 0 && year > 100
&& year < 3000) {
calendar_date = Calendar.getInstance();
calendar_date.set(year, month, day);
}
}
public void setTimeIn24HourFormat(int hourIn24Format, int minute) {
if (hourIn24Format < 24 && hourIn24Format >= 0 && minute >= 0
&& minute < 60) {
if (calendar_date == null)
calendar_date = Calendar.getInstance();
calendar_date.set(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
minute);
is24HourView = true;
}
}
public void setTimeIn12HourFormat(int hourIn12Format, int minute,
boolean isAM) {
if (hourIn12Format < 13 && hourIn12Format > 0 && minute >= 0
&& minute < 60) {
if (hourIn12Format == 12)
hourIn12Format = 0;
int hourIn24Format = hourIn12Format;
if (!isAM)
hourIn24Format += 12;
if (calendar_date == null)
calendar_date = Calendar.getInstance();
calendar_date.set(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
minute);
is24HourView = false;
}
}
public void set24HourFormat(boolean is24HourFormat) {
is24HourView = is24HourFormat;
}
public interface ICustomDateTimeListener {
public void onSet(Dialog dialog, Calendar calendarSelected,
Date dateSelected, int year, String monthFullName,
String monthShortName, int monthNumber, int date,
String weekDayFullName, String weekDayShortName, int hour24,
int hour12, int min, int sec, String AM_PM);
public void onCancel();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case SET_DATE:
btn_setTime.setEnabled(true);
btn_setDate.setEnabled(false);
viewSwitcher.showNext();
break;
case SET_TIME:
btn_setTime.setEnabled(false);
btn_setDate.setEnabled(true);
viewSwitcher.showPrevious();
break;
case SET:
if (iCustomDateTimeListener != null) {
int month = datePicker.getMonth();
int year = datePicker.getYear();
int day = datePicker.getDayOfMonth();
calendar_date.set(year, month, day, selectedHour,
selectedMinute);
iCustomDateTimeListener.onSet(dialog, calendar_date,
calendar_date.getTime(), calendar_date
.get(Calendar.YEAR),
getMonthFullName(calendar_date.get(Calendar.MONTH)),
getMonthShortName(calendar_date.get(Calendar.MONTH)),
calendar_date.get(Calendar.MONTH), calendar_date
.get(Calendar.DAY_OF_MONTH),
getWeekDayFullName(calendar_date
.get(Calendar.DAY_OF_WEEK)),
getWeekDayShortName(calendar_date
.get(Calendar.DAY_OF_WEEK)), calendar_date
.get(Calendar.HOUR_OF_DAY),
getHourIn12Format(calendar_date
.get(Calendar.HOUR_OF_DAY)), calendar_date
.get(Calendar.MINUTE), calendar_date
.get(Calendar.SECOND), getAMPM(calendar_date));
}
if (dialog.isShowing() && isAutoDismiss)
dialog.dismiss();
break;
case CANCEL:
if (iCustomDateTimeListener != null)
iCustomDateTimeListener.onCancel();
if (dialog.isShowing())
dialog.dismiss();
break;
}
}
/**
* #param date
* date in String
* #param fromFormat
* format of your <b>date</b> eg: if your date is 2011-07-07
* 09:09:09 then your format will be <b>yyyy-MM-dd hh:mm:ss</b>
* #param toFormat
* format to which you want to convert your <b>date</b> eg: if
* required format is 31 July 2011 then the toFormat should be
* <b>d MMMM yyyy</b>
* #return formatted date
*/
public static String convertDate(String date, String fromFormat,
String toFormat) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fromFormat);
Date d = simpleDateFormat.parse(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
simpleDateFormat = new SimpleDateFormat(toFormat);
simpleDateFormat.setCalendar(calendar);
date = simpleDateFormat.format(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
private String getMonthFullName(int monthNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, monthNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM");
simpleDateFormat.setCalendar(calendar);
String monthName = simpleDateFormat.format(calendar.getTime());
return monthName;
}
private String getMonthShortName(int monthNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, monthNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM");
simpleDateFormat.setCalendar(calendar);
String monthName = simpleDateFormat.format(calendar.getTime());
return monthName;
}
private String getWeekDayFullName(int weekDayNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
simpleDateFormat.setCalendar(calendar);
String weekName = simpleDateFormat.format(calendar.getTime());
return weekName;
}
private String getWeekDayShortName(int weekDayNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EE");
simpleDateFormat.setCalendar(calendar);
String weekName = simpleDateFormat.format(calendar.getTime());
return weekName;
}
private int getHourIn12Format(int hour24) {
int hourIn12Format = 0;
if (hour24 == 0)
hourIn12Format = 12;
else if (hour24 <= 12)
hourIn12Format = hour24;
else
hourIn12Format = hour24 - 12;
return hourIn12Format;
}
private String getAMPM(Calendar calendar) {
String ampm = (calendar.get(Calendar.AM_PM) == (Calendar.AM)) ? "AM"
: "PM";
return ampm;
}
enter image description here
private void resetData() {
calendar_date = null;
is24HourView = true;
}
public static String pad(int integerToPad) {
if (integerToPad >= 10 || integerToPad < 0)
return String.valueOf(integerToPad);
else
return "0" + String.valueOf(integerToPad);
}
}
I'm trying to build this app which checks a folder size on an interval, and if the folder size is bigger than whatever user have set, a notification appears. The problem is when user disables the notification, it still keeps on notifying ("ShowNotif" is called), what am I doing wrong?
ScheduleFragment.java
public class ScheduleFragment extends Fragment {
SharedPreferences.Editor editor;
AlarmManager manager;
PendingIntent pendingIntent;
SharedPreferences share;
EditText telegSizeText;
CheckBox telegramSize;
private boolean telegramSizeIsSet = false;
CheckBox notif;
public ScheduleFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_schedule, container, false);
telegramSize = (CheckBox)view.findViewById(R.id.telegramSize);
telegSizeText = (EditText)view.findViewById(R.id.telegSizeText);
notif = (CheckBox) view.findViewById(R.id.notif);
share = getActivity().getSharedPreferences("setting", 0);
editor = this.share.edit();
telegramSize.setChecked(share.getBoolean("telegram_selected", false));
telegramSizeIsSet = true;
int var2 = share.getInt("telegram_size", -1);
if(var2 != -1) {
telegSizeText.setText(String.valueOf(var2));
} else {
telegSizeText.setText("");
}
this.telegramSize.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton var1, boolean var2) {
if (telegramSizeIsSet) {
if(!var2) {
manager = (AlarmManager)getContext().getSystemService(Context.ALARM_SERVICE);
Intent var11 = new Intent(getActivity(), ShowNotif.class);
pendingIntent = PendingIntent.getBroadcast(getActivity(), 1,var11,PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntentNoti = PendingIntent.getBroadcast(getActivity(), 1, var11,PendingIntent.FLAG_UPDATE_CURRENT);
manager.cancel(pendingIntent);
manager.cancel(pendingIntentNoti);
Toast.makeText(getContext(), "Disabled!", Toast.LENGTH_SHORT).show();
editor.putBoolean("telegram_selected", false);
editor.putInt("telegram_size", -1);
telegSizeText.setText("");
editor.commit();
return;
}
if(telegSizeText.getText().toString() == null || telegSizeText.getText().toString().equals("")) {
Toast.makeText(getContext(), "Can't be empty", Toast.LENGTH_SHORT).show();
telegramSizeIsSet = false;
telegramSize.setChecked(false);
telegramSizeIsSet = true;
return;
}
Intent var9 = new Intent(getActivity(), CheckTelegramSizeReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, var9, 0);
manager = (AlarmManager)getContext().getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
editor.putInt("telegram_size", Integer.valueOf(telegSizeText.getText().toString()).intValue());
editor.putBoolean("telegram_selected", true);
editor.commit();
manager = (AlarmManager)getContext().getSystemService(Context.ALARM_SERVICE);
manager.setRepeating(0, System.currentTimeMillis(), (long) 10000, pendingIntent); //check every 10 seconds
Toast.makeText(getContext(), "Enabled!", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}}
CheckTelegramSizeReceiver.java
public class CheckTelegramSizeReceiver extends BroadcastReceiver {
private AlarmManager manager;
private AlarmManager manager2;
private AlarmManager manager3;
private boolean notificationCanceled;
boolean notificationCreated = false;
String path;
private PendingIntent pendingIntent;
private PendingIntent pendingIntent2;
long totalSizes = 0L;
int userSelectedSize = 0;
private long getFileSize(String var1) {
long var2 = 0L;
File[] var4 = (new File(var1)).listFiles();
if (var4 != null) {
for (int var5 = 0; var5 < var4.length; ++var5) {
File var6 = var4[var5];
if (var6.isDirectory()) {
var2 += this.getFileSize(var6.getPath());
} else {
var2 += var6.length();
}
}
}
return var2;
}
public void onReceive(final Context var1, Intent var2) {
File var3 = Environment.getExternalStorageDirectory();
this.path = var3 + "/Telegram";
(new AsyncTask<Void, Integer, Integer>() {
protected Integer doInBackground(Void... var1x) {
totalSizes = getFileSize(path) / 1048576L;
//
SharedPreferences var2 = var1.getSharedPreferences("setting", 0);
userSelectedSize = var2.getInt("telegram_size", -1);
return 1;
}
protected void onPostExecute(Integer var1x) {
SharedPreferences var2 = var1.getSharedPreferences("setting", 0);
Editor var3 = var2.edit();
CheckTelegramSizeReceiver.this.userSelectedSize = var2.getInt("telegram_size", -1);
CheckTelegramSizeReceiver.this.notificationCreated = var2.getBoolean("notificationIsShowing", false);
CheckTelegramSizeReceiver.this.notificationCanceled = var2.getBoolean("notificationIsShowingCanceled", false);
if ((int) CheckTelegramSizeReceiver.this.totalSizes > CheckTelegramSizeReceiver.this.userSelectedSize && !CheckTelegramSizeReceiver.this.notificationCreated) {
Intent var11 = new Intent(var1, ShowNotif.class);
CheckTelegramSizeReceiver.this.pendingIntent = PendingIntent.getBroadcast(var1, 1, var11, 0);
CheckTelegramSizeReceiver.this.manager2 = (AlarmManager) var1.getSystemService(Context.ALARM_SERVICE);
CheckTelegramSizeReceiver.this.manager2.setRepeating(0, System.currentTimeMillis(), (long) 28800000, CheckTelegramSizeReceiver.this.pendingIntent);
var3.putBoolean("notificationIsShowing", true).commit();
var3.putBoolean("notificationIsShowingCanceled", false).commit();
CheckTelegramSizeReceiver.this.notificationCreated = true;
CheckTelegramSizeReceiver.this.notificationCanceled = false;
}
if ((int) CheckTelegramSizeReceiver.this.totalSizes < CheckTelegramSizeReceiver.this.userSelectedSize && CheckTelegramSizeReceiver.this.notificationCreated && !CheckTelegramSizeReceiver.this.notificationCanceled) {
System.out.println("test");
Intent var5 = new Intent(var1, ShowNotif.class);
CheckTelegramSizeReceiver.this.pendingIntent = PendingIntent.getBroadcast(var1, 1, var5, 0);
CheckTelegramSizeReceiver.this.manager2 = (AlarmManager) var1.getSystemService(Context.ALARM_SERVICE);
CheckTelegramSizeReceiver.this.manager2.cancel(CheckTelegramSizeReceiver.this.pendingIntent);
CheckTelegramSizeReceiver.this.notificationCreated = false;
CheckTelegramSizeReceiver.this.notificationCanceled = true;
var3.putBoolean("notificationIsShowingCanceled", true).commit();
var3.putBoolean("notificationIsShowing", false).commit();
}
}
}).execute(null, null, null);
}}
ShowNotif.java
public class ShowNotif extends BroadcastReceiver {
public void onReceive(Context var1, Intent var2) {
int var3 = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if (var3 <= 22 && var3 >= 10) {
Uri var4 = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Bitmap var5 = BitmapFactory.decodeResource(var1.getResources(), R.drawable.icon_notif);
NotificationCompat.Builder var6 = (new NotificationCompat.Builder(var1)).setSmallIcon(R.drawable.icon_notif).setLargeIcon(var5).setContentTitle("My App").setContentText("Notification Text").setSound(var4).setAutoCancel(true);
var6.setContentIntent(PendingIntent.getActivity(var1, 0, new Intent(var1, MainActivity.class), 0));
((NotificationManager) var1.getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, var6.build());
}
}}
Thanks in advance.
if (telegramSizeIsSet) {
if(!var2) {
Intent var3 = new Intent(getActivity(), CheckTelegramSizeReceiver.class);
manager = (AlarmManager)getContext().getSystemService(Context.ALARM_SERVICE);
pendingIntent = PendingIntent.getBroadcast(var1, 1,var11,PendingIntent.FLAG_UPDATE_CURRENT);
pendingIntentNoti = PendingIntent.getBroadcast(var1, 1, var11,PendingIntent.FLAG_UPDATE_CURRENT);
manager.cancel(pendingIntent);
manager.cancel(pendingIntentNoti);
Toast.makeText(getContext(), "Disabled!", Toast.LENGTH_SHORT).show();
editor.putBoolean("telegram_selected", false);
editor.putInt("telegram_size", -1);
telegSizeText.setText("");
editor.commit();
return;
}
Basically you just cancel the Alarm for CheckTelegramSizeReceiver receiver. but you forget to cancel the alarm set up by CheckTelegramSizeReceiver receiver that is ShowNoti Receiver. So ShowNoti receiver shows the notification again and again so you need to cancel the ShowNoti alaram too and use FLAG_UPDATE_CURRENT instead of 0. Thanks It may help you!
I'm trying to use pressure sensor.
After every 6 sec read sensor value and show.
But it always shows "0.0"
First time I tried static variable...but not working.
Now using singleton, still it is not working.
I don't know where I am wrong.
Help me. Please.
/* broadcastReceiver */
public class Alarm extends BroadcastReceiver {
static int count = 0;
#Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
SensorValue sv = SensorValue.getInstance();
Toast.makeText(context, "Barometer : " + String.valueOf( sv.getBaroVal() ) + " count : " + String.valueOf( count ), Toast.LENGTH_SHORT ).show(); // For example
count++;
wl.release();
}
public void SetAlarm(Context context){
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10 * 60 * 10, pi); // Millisec * Second * Minute
}
public void CancelAlarm(Context context) {
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
/* singleton */
public class SensorValue {
private static SensorValue singleton = new SensorValue();
private double baroVal = 0.0;
private SensorValue(){
}
public static SensorValue getInstance(){
return singleton;
}
public void setBaroVal( double val ) {
baroVal = val;
}
public double getBaroVal() {
return baroVal;
}
}
/* MainActivity */
#Override
public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()) {
case Sensor.TYPE_PRESSURE:
sv.setBaroVal( event.values[0] );
break;
}
}
Thank You!
Change your SensorValue class to below.
public class SensorValue {
private static SensorValue singleton;
private double baroVal = 0.0;
private SensorValue(){
singleton = new SensorValue();
}
public static SensorValue getInstance(){
if(singleton == null)
{
singleton = new SensorValue();
}
return singleton
}
public void setBaroVal( double val ) {
baroVal = val;
}
public double getBaroVal() {
return baroVal;
}
}
I don,t know whether it will work or not though test it with once.
Finally, I found a reason.
in manifest file. i set receiver option like this
android:process=":remote"
it worked another process.
have a good day.
I've searched everywhere for an answer to this dilemma. A CountDownTimer(bsCountDownTimer) will not start when it should. When I click the button, it is supposed to begin the onTick(), correct? However, only after I navigate to a different activity and navigate backwards using the UP button, or exit the app or destroy it and restart it does the onTick() start updating the text and sending information to LogCat like it is told to do.
My best guess is that this problem is exclusive to either the CDT sub-class, onBsButtonClick(), onCreate(), or possible onResume()/onPause().
Here is some of the source code.
public class HomeActivity extends Activity {
#SuppressLint("NewApi") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
if(bsTimeStamp!=0){bsIsRunning=true;}
if(bsTimeStamp==0){bsIsRunning=false;}
lastFed=(TextView)findViewById(R.id.lastFedTextView);
feedAt=(TextView)findViewById(R.id.feedAtTextView);
daysText = (EditText)findViewById(R.id.editTextDays);
hoursText = (EditText)findViewById(R.id.editTextHours);
minutesText = (EditText)findViewById(R.id.editTextMinutes);
daysText.setText("");
hoursText.setText("");
minutesText.setText("");
// get timeStamp and boolean from onFeedButtonClick() START
final SharedPreferences prefs = this.getPreferences(Context.MODE_PRIVATE);
feedClickTimeStamp = prefs.getLong("savedOnFeedClick", placeholder);
bsTimeStamp = prefs.getLong("savedOnBsClick", bsProgress);
bsPlaceholder = prefs.getLong("saved placeholder", bsPlaceholder);
bsIsRunning = prefs.getBoolean("bs is running", bsIsRunning);
progressbs = Long.toString(bsProgress);
placeholderbs = Long.toString(bsPlaceholder);
timestampbs = Long.toString(bsTimeStamp);
timestamp = Long.toString(feedClickTimeStamp);
LAST_FED = prefs.getString("lastFed", LAST_FED);
FEED_AT = prefs.getString("feedAt", FEED_AT);
feedAt.setText("Feed at: " + FEED_AT);
lastFed.setText("Last fed at: " + LAST_FED);
// get timeStamp and boolean from onFeedButtonClick() END
DateTime date = new DateTime();
long currentTime = date.getMillis();
Long bsDiffInMillis;
if(bsIsRunning=false) {
bsDiffInMillis = 0L;
}
else {
bsDiffInMillis = currentTime - bsTimeStamp;
bsPlaceholder -= bsDiffInMillis;
}
Integer bsDiffInt = Integer.valueOf(bsDiffInMillis.intValue());
int roundedDiff = (bsDiffInt + 500) / 1000 * 1000;
j += roundedDiff - 2000;
// BS PROGRESS BAR START
bsProgressBar = (ProgressBar)findViewById(R.id.bsProgressBar);
bsProgressBar.setProgress(j);
Long bsPlaceholderLong = bsPlaceholder;
final Integer setMax = Integer.valueOf(bsPlaceholderLong.intValue());
bsProgressBar.setMax(setMax);
setProgressBarVisibility(true);
if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB){
bsProgressBar.setRotation(180);
} else{
// FIND A WAY TO ROTATE PROGRESSBAR BEFORE API 11 (3.0)
}
timeDisplayBs=(TextView)findViewById(R.id.bs_countdown); ((TextView)findViewById(R.id.bs_countdown)).setText(convertMillisForCrafting(bsPlaceholder-ji));
millisInFuture = bsPlaceholder;
bsCountDownTimer = new CDT(millisInFuture, countDownInterval);
// START BS BUTTON LISTENER //
final Button startBsBtn = (Button) findViewById(R.id.bsButton);
startBsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBsButtonClick(view);
} //close onClick
}); //close onClickListener
// END BS BUTTON LISTENER //
if (savedInstanceState != null) {} else {}
}// onCreate END
#Override
protected void onPause() {
super.onPause();
bsCountDownTimer.cancel();
}
#SuppressLint("NewApi") #Override
protected void onResume() {
super.onResume();
SharedPreferences prefs = this.getPreferences(Context.MODE_PRIVATE);
bsIsRunning = prefs.getBoolean("bs is running", bsIsRunning);
if(feedClickTimeStamp>0){
mountCountDownTimer.start();
}
if(bsIsRunning==true) {
bsCountDownTimer.start();
bsIsRunning=true;
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("bs is running", bsIsRunning).commit();
}
if(bsIsRunning==false){
bsIsRunning=false;
String progressBarTitleBs = "blacksmithing research";
timeDisplayBs = (TextView)findViewById(R.id.bs_countdown);
timeDisplayBs.setText(progressBarTitleBs.toUpperCase(preferredLocale));
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("bs is running", bsIsRunning).commit();
}
}
public class CDT extends CountDownTimer {
public CDT(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
millisInFuture = prefs.getLong("saved placeholder", bsPlaceholder);
timeDisplayBs=(TextView)findViewById(R.id.bs_countdown);
}
#Override
public void onTick(long millisInFuture) {
Log.v("bsTimer", "Tick of Progress " + ji + " " + millisInFuture);
ji+=1;
j+=1000;
bsProgressBar.setProgress(j);
timeDisplayBs.setText(convertMillisForCrafting(millisInFuture-ji));
}
#Override
public void onFinish() {
bsCountDownTimer.cancel();
j=0;
ji=0;
bsPlaceholder = 0;
bsTimeStamp = 0;
bsProgressBar.setProgress(0);
String progressBarTitleBs = "blacksmithing research";
timeDisplayBs = (TextView)findViewById(R.id.bs_countdown);
timeDisplayBs.setText(progressBarTitleBs.toUpperCase(preferredLocale));
}
}
public void onBsButtonClick(View view) {
final SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
bsTimeStamp = prefs.getLong("savedOnBsClick", bsProgress);
bsPlaceholder = prefs.getLong("saved placeholder", bsPlaceholder);
bsIsRunning = prefs.getBoolean("bs is running", bsIsRunning);
EditText daysText = (EditText)findViewById(R.id.editTextDays);
EditText hoursText = (EditText)findViewById(R.id.editTextHours);
EditText minutesText = (EditText)findViewById(R.id.editTextMinutes);
int daysPh;
int hoursPh;
int minutesPh;
String daysStr = daysText.getText().toString();
String hoursStr = hoursText.getText().toString();
String minutesStr = minutesText.getText().toString();
if (daysStr.matches("") && hoursStr.matches("") && minutesStr.matches("")) {
Toast.makeText(this, "You did not enter DAYS, HOURS, or MINUTES.", Toast.LENGTH_LONG).show();
return;
}
if(bsIsRunning==false){
bsPlaceholder = 0;
bsTimeStamp = 0;
bsIsRunning=true;
j=0;
bsProgressBar.setProgress(0);
Long bsPlaceholderLong = bsPlaceholder;
final Integer setMax = Integer.valueOf(bsPlaceholderLong.intValue());
bsProgressBar.setMax(setMax);
if(daysText.getText().toString().equals("")){
daysText.setText("0");
}
if(hoursText.getText().toString().equals("")){
hoursText.setText("0");
}
if(minutesText.getText().toString().equals("")){
minutesText.setText("0");
}
daysPh = Integer.parseInt(daysText.getText().toString());
hoursPh = Integer.parseInt(hoursText.getText().toString());
minutesPh = Integer.parseInt(minutesText.getText().toString());
daysText.setText("");
hoursText.setText("");
minutesText.setText("");
SharedPreferences.Editor editor = prefs.edit();
bsPlaceholder = getMillisForCrafting(daysPh, hoursPh, minutesPh);
millisInFuture = bsPlaceholder; //VITAL
DateTime dt = new DateTime();
bsProgress = dt.getMillis();
editor.putBoolean("bs is running", bsIsRunning).commit();
editor.putLong("savedOnBsClick", bsProgress).commit();
editor.putLong("saved placeholder", bsPlaceholder).commit();
bsCountDownTimer.start();
} //close if bsIsRunning==false
else if(bsIsRunning==true){
view.invalidate();
new AlertDialog.Builder(HomeActivity.this)
.setTitle("New Blacksmithing Research Timer? (erases current)")
.setMessage("Are you sure you want to start a new timer? \n(Current timer will be erased.)")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
bsPlaceholder = 0;
bsTimeStamp = 0;
bsCountDownTimer.cancel();
bsIsRunning=true;
j=0;
bsProgressBar.setProgress(0);
String progressBarTitleBs = "blacksmithing research";
timeDisplayBs = (TextView)findViewById(R.id.bs_countdown);
timeDisplayBs.setText(progressBarTitleBs.toUpperCase(preferredLocale));
EditText daysText = (EditText)findViewById(R.id.editTextDays);
EditText hoursText = (EditText)findViewById(R.id.editTextHours);
EditText minutesText = (EditText)findViewById(R.id.editTextMinutes);
if(daysText.getText().toString().equals("")){
daysText.setText("0");
}
if(hoursText.getText().toString().equals("")){
hoursText.setText("0");
}
if(minutesText.getText().toString().equals("")){
minutesText.setText("0");
}
int daysPh = Integer.parseInt(daysText.getText().toString());
int hoursPh = Integer.parseInt(hoursText.getText().toString());
int minutesPh = Integer.parseInt(minutesText.getText().toString());
SharedPreferences.Editor editor = prefs.edit();
bsPlaceholder = getMillisForCrafting(daysPh, hoursPh, minutesPh);
DateTime dt = new DateTime();
bsProgress = dt.getMillis();
editor.putBoolean("bs is running", bsIsRunning).commit();
editor.putLong("savedOnBsClick", bsProgress).commit();
editor.putLong("saved placeholder", bsPlaceholder).commit();
Long bsPlaceholderLong = bsPlaceholder;
final Integer setMax = Integer.valueOf(bsPlaceholderLong.intValue());
bsProgressBar.setMax(setMax);
daysText.setText("");
hoursText.setText("");
minutesText.setText("");
bsCountDownTimer.start();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}return;
}
public static Long getMillisForCrafting(int daysPh, int hoursPh, int minutesPh) {
Locale.getDefault();
DateTime bs = new DateTime();
daysPulled = daysPh;
hoursPulled = hoursPh;
minutesPulled = minutesPh;
final long nowInMillis = bs.getMillis();
long days = daysPulled * 86400000;
long hours = hoursPulled * 3600000;
long minutes = minutesPulled * 60000;
long millisToAddToNow = days + hours + minutes;
long futureDateInMillis = millisToAddToNow + nowInMillis;
long millisFromDate = futureDateInMillis - nowInMillis;
return millisFromDate;
}
public void onBsResetButtonClick(View view) {
final SharedPreferences prefs = this.getPreferences(Context.MODE_PRIVATE);
bsTimeStamp = prefs.getLong("savedOnBsClick", bsProgress);
new AlertDialog.Builder(this)
.setTitle("Reset Timer?")
.setMessage("Reset Blacksmithing Research timer? \n(Current timer will be erased.)")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
j=0;
bsProgressBar.setProgress(0);
bsCountDownTimer.cancel();
bsIsRunning=false;
String progressBarTitleBs = "blacksmithing research";
timeDisplayBs = (TextView)findViewById(R.id.bs_countdown);
timeDisplayBs.setText(progressBarTitleBs.toUpperCase(preferredLocale));
bsPlaceholder = 0;
bsTimeStamp = 0;
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("bs is running", bsIsRunning).commit();
editor.putLong("savedOnBsClick", 0).commit();
editor.putLong("saved placeholder", 0).commit();
// CLEAR INPUT EDITTEXT AREAS
EditText daysText = (EditText)findViewById(R.id.editTextDays);
EditText hoursText = (EditText)findViewById(R.id.editTextHours);
EditText minutesText = (EditText)findViewById(R.id.editTextMinutes);
daysText.setText("");
hoursText.setText("");
minutesText.setText("");
// CLEAR INPUT EDITTEXT AREAS
}})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
#SuppressLint("DefaultLocale")
public static String convertMillis(long milliseconds){
long seconds, minutes, hours;
seconds = milliseconds / 1000;
minutes = seconds / 60;
seconds = seconds % 60;
hours = minutes / 60;
minutes = minutes % 60;
Locale.getDefault();
String time = String.format("%02d:%02d:%02d", hours, minutes, seconds);
return(time);
}
#SuppressLint("DefaultLocale")
public static String convertMillisForCrafting(long milliseconds){
long seconds, minutes, hours, days;
seconds = milliseconds / 1000;
minutes = seconds / 60;
seconds = seconds % 60;
hours = minutes / 60;
days = hours / 24;
hours = hours % 24;
minutes = minutes % 60;
Locale.getDefault();
String timeBs = String.format("%02d days %02d hours %02d minutes %02d seconds", days, hours, minutes, seconds);
return(timeBs);
}
#Override
protected void onDestroy() {
super.onDestroy(); // Always call the superclass
mProgressBar.destroyDrawingCache();
mountCountDownTimer.cancel();
// bsProgressBar.destroyDrawingCache();
// bsCountDownTimer.cancel();
// android.os.Debug.stopMethodTracing(); // Stop method tracing that the activity started during onCreate()
}
}
I got it!
The countDownTimer wouldn't start because the variable from onBsButtonClick() (bsPlaceholder) wasn't being passed into onCreate() correctly.
Here's what I did:
Declared a global variable
static long timeInput;
Created a sub-class that extends CountDownTimer:
public class bsTimer extends CountDownTimer {
public bsTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisInFuture) {
Log.v("bsTimer", "Tick of Progress " + ji + " " + millisInFuture);
ji+=1;
j+=1000;
bsProgressBar.setProgress(j);
((TextView)findViewById(R.id.bs_countdown)).setText(convertMillisForCrafting(millisInFuture-ji));
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
}
Instantiated the countdown timer in onCreate();
bsCountDownTimer = new bsTimer(timeInput, 1000);
Then just made a new timer and started it in the onBsButtonClick() method!
bsCountDownTimer = new bsTimer(timeInput, 1000).start();