I want to use alarm based on some database time value . Currently my alarm is working for one alarm Like : I have 3 alarm set at 8:30am , 10:20am and 12:20Pm
my alarm is working only for one value .This is reminder class there i am creating the alarm
public class OwnGoalReminder extends EventReminder {
GoalOwn goalOwn;
int interValTime;
int goalId;
int hour;
int minute;
int requestCode;
String type;
public void setInterValTime(int interValTime) {
this.interValTime = interValTime;
}
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public void setRequestCode(int requestCode) {
this.requestCode = requestCode;
}
public void setType(String type) {
this.type = type;
}
public int getMinute() {
return minute;
}
#Override
protected int getGoalId(){return this.goalId;}
public void setMinute(int minute) {
this.minute = minute;
}
public OwnGoalReminder(Context context , int goalId, int interValTime){
super(context);
this.interValTime = interValTime;
this.goalId = goalId;
}
#Override
protected String getType() {
return this.type;
}
#Override
protected String getMessage() {
return "Reminder!!! You should check your goals!";
}
#Override
protected int getRequestCode() {
return requestCode;
}
#Override
protected EventTime getEventTime() {
int h = hour;
int m = minute;
return new EventTime(hour,minute,interValTime);
}
#Override
protected Class getBroadcastReceiver() {
return MyBroadcastReceiver.class;
}
}
This is base class of OwnGOalReminder
public abstract class EventReminder{
protected Context context;
protected Alarm alarm;
PushNotificationsManager notificationsManager;
public void remind() {
Bundle bundle = new Bundle();
bundle.putString("type", getType());
bundle.putString("msg", getMessage());
notificationsManager.sendNotification(bundle);
}
protected abstract String getType();
protected abstract String getMessage();
protected abstract int getRequestCode();
protected abstract int getGoalId();
protected abstract EventTime getEventTime();
protected abstract Class getBroadcastReceiver();
protected EventReminder(Context context){
this.context = context;
alarm = new Alarm(context, getBroadcastReceiver());
notificationsManager = new PushNotificationsManager(context);
}
public void startReminder(){
alarm.startAlert(getRequestCode(), getGoalId(), getEventTime().hour, getEventTime().minute, getEventTime().intervalInMinute);
//alarm.setAlarm(context, getEventTime().hour, getEventTime().minute);
}
protected class EventTime{
int hour, minute, intervalInMinute;
public EventTime(int hour, int minute, int intervalInMinute){
this.hour = hour;
this.minute = minute;
this.intervalInMinute = intervalInMinute;
}
}
}
this is alarm class there i am creating the alarmmanager
public class Alarm{
private final Context context;
private Class broadcastReceiver;
public Alarm(Context context, Class broadcastReceiver){
this.context = context;
this.broadcastReceiver = broadcastReceiver;
}
public void startAlert(int requestCode, int gid, int hour, int minute, int intervalMinute) {
Log.d(this.getClass().getName(), "starting alert");
int i = 10;
Long timeToMilliSeconds = timeToMilliSeconds(hour, minute);
Intent intent = new Intent(context, MyBroadcastReceiver.class);
intent.putExtra("reqcode", requestCode);
intent.putExtra("time", timeToMilliSeconds);
intent.putExtra("gid" , gid);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeToMilliSeconds+
+ (i * 1000), 1000*60*intervalMinute, pendingIntent);
//Toast.makeText(context, "Alarm set in " + i + " seconds",Toast.LENGTH_LONG).show();
}
#NonNull
public static long timeToMilliSeconds(int hour, int minute) {
Date dat = new Date();//initializes to now
Calendar cal_alarm = Calendar.getInstance();
Calendar cal_now = Calendar.getInstance();
cal_now.setTime(dat);
cal_alarm.setTime(dat);
cal_alarm.set(Calendar.HOUR_OF_DAY,hour);//set the alarm time
cal_alarm.set(Calendar.MINUTE, minute);
cal_alarm.set(Calendar.SECOND,0);
if(cal_alarm.getTimeInMillis() < System.currentTimeMillis()){
cal_alarm.add(Calendar.DAY_OF_YEAR,1);
}
return cal_alarm.getTimeInMillis();
}
}
This is the method here i am creating the multiple alarm object based on database value
public static void registerAlarm(Context context){
if(!UserPreferences.isAlarmRegistered(context)) {
GoalReminder goalReminder = new GoalReminder(context);
AppraisalReminder appraisalReminder = new AppraisalReminder(context);
goalReminder.startReminder();
appraisalReminder.startReminder();
// ownGoalReminder.startReminder();
//UserPreferences.setIsAlarmRegistered(context,true);
ArrayList<Goal> LIST_OF_OWN_GOALS = new ArrayList<>();
LIST_OF_OWN_GOALS = (ArrayList<Goal>) Goal.getGoalFromOwnGoals();
for (Goal g : LIST_OF_OWN_GOALS) {
OwnGoalReminder ownGoalReminder = new OwnGoalReminder(context , g.getgId(),3 );
int h = Integer.parseInt(g.getrTime())/60;
int min = Integer.parseInt(g.getrTime())%60;
ownGoalReminder.setHour(h);
ownGoalReminder.setMinute(min);
ownGoalReminder.setRequestCode(16);
ownGoalReminder.setType("16");
ownGoalReminder.startReminder();
LIST_OF_OWN_REMINDERS.add(ownGoalReminder);
}
}
}
This is my Broadcast receiver class :
public class MyBroadcastReceiver extends BroadcastReceiver {
private static final String[] goalMessagesArray = ApraiseApplication.getContext().getResources().getStringArray(R.array.goals_messages);
private static Queue<String> goalMessagesQueue = new ArrayDeque<>(Arrays.asList(goalMessagesArray));
private static final String[] appraisalsMessagesArray = ApraiseApplication.getContext().getResources().getStringArray(R.array.appraisals_messages);
private static Queue<String> appraisalsMessagesQueue = new ArrayDeque<>(Arrays.asList(appraisalsMessagesArray));
#Override
public void onReceive(Context context, Intent intent) {
Log.d(this.getClass().getName(), "notify");
PushNotificationsManager notificationsManager = new PushNotificationsManager(context);
PowerManager.WakeLock wl = acquireWakeLock(context);
int requestCode = intent.getIntExtra("reqcode",1);
int gId = intent.getIntExtra("gid",1);
long time = intent.getLongExtra("time",0);
String message = "";
// it will create the instance of Random class
Random randomGenerator = new Random();
// it will generate a random number based on goal message arrayList length
int indexForGoalMessage = randomGenerator.nextInt(goalMessagesArray.length);
// it will generate a random number based on appraisalsMessagesArray length
int indexForAppraisalsMessage = randomGenerator.nextInt(goalMessagesArray.length);
String gid = "";
if(isNotifyTimePassed(time)){
//return;
}
if(requestCode == 123){
// if(goalMessagesQueue.isEmpty()){
// goalMessagesQueue = new ArrayDeque<>(Arrays.asList(goalMessagesArray));
// }
// message = goalMessagesQueue.poll();
message = goalMessagesArray[indexForGoalMessage];
}else if(requestCode == 124){
// if(appraisalsMessagesQueue.isEmpty()){
// appraisalsMessagesQueue = new ArrayDeque<>(Arrays.asList(appraisalsMessagesArray));
// }
// message = appraisalsMessagesQueue.poll();
message = appraisalsMessagesArray[indexForAppraisalsMessage];
}
Bundle bundle = new Bundle();
bundle.putString("type", Integer.toString(requestCode));
bundle.putString("msg", message);
bundle.putString("gid" , String.valueOf(gId));
notificationsManager.sendNotification(bundle);
wl.release();
}
#NonNull
private PowerManager.WakeLock acquireWakeLock(Context context) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
return wl;
}
private boolean isNotifyTimePassed(long time) {
return (System.currentTimeMillis()-time) > 1000L*60L*5L;
}
}
[I have found this solution from searching google ]
I have solved that problem by passing unique id which is depend on current time:-
final int intent_id= (int) System.currentTimeMillis();
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, intent_id , intent, PendingIntent.FLAG_UPDATE_CURRENT);
It is good to set your event id (unique id) as the request code of PendingIntent.getBroadcast() method. So the advantage here is when you update/edit the event then alarm wont duplicate.
Related
Im trying to make a service that would provide data of usagestat every x second. However i always getting the same value after x second. I already clear the map to include new data set from usagemanager. below is my service class thank you in advance.
I do know that in order to retrieve queries every x time, we may use queryevent. However, the total time in foreground for this fit my project, and i already tested using the code for adapter. In the adapter, it do retrieve usage time, however it only provide new value on restarting the activity where the adapter used.
public class PushService extends Service {
private static final int NOTIF_ID = 1;
private static final String NOTIF_CHANNEL_ID = "Channel_Id_1";
private static final String NOTIF_CHANNEL_ID2 = "Channel_Id_2";
private static final int _DISPLAY_ORDER_USAGE_TIME = 0;
private static final int _DISPLAY_ORDER_LAST_TIME_USED = 1;
private static final int _DISPLAY_ORDER_APP_NAME = 2;
private static final boolean localLOGV = false;
private int mDisplayOrder = _DISPLAY_ORDER_USAGE_TIME;
private AppNameComparator mAppLabelComparator;
private LastTimeUsedComparator mLastTimeUsedComparator;
private UsageTimeComparator mUsageTimeComparator;
private PackageManager mPm;
private UsageStatsManager mUsageStatsManager;
public HashMap<String, Long> mapToFirebase = new HashMap<>();;
public ArrayList<UsageStats> mPackageStats;
public ArrayMap<String, String> mAppLabelMap;
public List<UsageStats> stats;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
/*notice*/
startForeground();
if (intent != null){
String uid = intent.getStringExtra("parentUID");
if (!uid.equals("")){
Toast.makeText(this, uid, Toast.LENGTH_SHORT).show();
Handler ha=new Handler();
ha.postDelayed(new Runnable() {
#Override
public void run() {
//call function
pushAppList();
mapToFirebase.clear();
loadDataToMapForFirebase();
Log.d("mapservice", mapToFirebase.toString());
ha.postDelayed(this, 5000);
}
}, 10000);
}
}
return super.onStartCommand(intent, flags, startId);
}
public static class AppNameComparator implements Comparator<UsageStats> {
private Map<String, String> mAppLabelList;
AppNameComparator(Map<String, String> appList) {
mAppLabelList = appList;
}
#Override
public final int compare(UsageStats a, UsageStats b) {
String alabel = mAppLabelList.get(a.getPackageName());
String blabel = mAppLabelList.get(b.getPackageName());
return alabel.compareTo(blabel);
}
}
public void pushAppList(){
mAppLabelMap = new ArrayMap<>();
mPackageStats = new ArrayList<>();
mPm = getPackageManager();
mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -5);
mLastTimeUsedComparator = new LastTimeUsedComparator();
mUsageTimeComparator = new UsageTimeComparator();
stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, cal.getTimeInMillis(), System.currentTimeMillis());
if (stats == null) {
return;
}
ArrayMap<String, UsageStats> map = new ArrayMap<>();
int statCount = stats.size();
for (int i = 0; i < statCount; i++) {
Log.d("", String.valueOf(stats.get(i).getTotalTimeInForeground()));
android.app.usage.UsageStats pkgStats = stats.get(i);
// load application labels for each application
try {
ApplicationInfo appInfo = mPm.getApplicationInfo(pkgStats.getPackageName(), 0);
String label = appInfo.loadLabel(mPm).toString();
mAppLabelMap.put(pkgStats.getPackageName(), label);
UsageStats existingStats =
map.get(pkgStats.getPackageName());
if (existingStats == null) {
map.put(pkgStats.getPackageName(), pkgStats);
} else {
existingStats.add(pkgStats);
}
} catch (PackageManager.NameNotFoundException e) {
// This package may be gone.
}
}
mPackageStats.addAll(map.values());
// Sort list
mAppLabelComparator = new AppNameComparator(mAppLabelMap);
sortList();
}
public static class LastTimeUsedComparator implements Comparator<UsageStats> {
#Override
public final int compare(UsageStats a, UsageStats b) {
// return by descending order
return (int)(b.getLastTimeUsed() - a.getLastTimeUsed());
}
}
public static class UsageTimeComparator implements Comparator<UsageStats> {
#Override
public final int compare(UsageStats a, UsageStats b) {
return (int)(b.getTotalTimeInForeground() - a.getTotalTimeInForeground());
}
}
private void sortList() {
if (mDisplayOrder == _DISPLAY_ORDER_USAGE_TIME) {
if (localLOGV) Log.i(TAG, "Sorting by usage time");
Collections.sort(mPackageStats, mUsageTimeComparator);
} else if (mDisplayOrder == _DISPLAY_ORDER_LAST_TIME_USED) {
if (localLOGV) Log.i(TAG, "Sorting by last time used");
Collections.sort(mPackageStats, mLastTimeUsedComparator);
} else if (mDisplayOrder == _DISPLAY_ORDER_APP_NAME) {
if (localLOGV) Log.i(TAG, "Sorting by application name");
Collections.sort(mPackageStats, mAppLabelComparator);
}
}
public void loadDataToMapForFirebase(){
/*TODO UPDATE DATA ONBACKGROUND*/
String system_sign = "android";
PackageManager pm = getPackageManager();
if (mPackageStats.size() != 0){
for (int i = 0; i < mPackageStats.size(); i++){
if (pm.checkSignatures(system_sign, mPackageStats.get(i).getPackageName()) == PackageManager.SIGNATURE_MATCH) {
Log.d("CheckAppSys", mPackageStats.get(i).getPackageName() + " is sys.");
} else {
String usagetime = DateUtils.formatElapsedTime(mPackageStats.get(i).getTotalTimeInForeground() / 1000);
Pattern special= Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher matcher = special.matcher(Objects.requireNonNull(mAppLabelMap.get(mPackageStats.get(i).getPackageName())));
boolean constainsSymbols = matcher.find();
if(!constainsSymbols){
mapToFirebase.put(mAppLabelMap.get(mPackageStats.get(i).getPackageName()), mPackageStats.get(i).getTotalTimeInForeground());
}
Log.d("maptofirebase", mapToFirebase.toString());
Log.d("CheckApp", mPackageStats.get(i).getPackageName() + " is not sys.");
}
}
}
}
private void startForeground() {
Intent notificationIntent = new Intent(this, UsageStatsActivity.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(
NOTIF_CHANNEL_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is channel 1");
NotificationChannel channel2 = new NotificationChannel(
NOTIF_CHANNEL_ID2,
"Channel 2",
NotificationManager.IMPORTANCE_LOW
);
channel2.setDescription("This is channel 2");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
startForeground(NOTIF_ID, new NotificationCompat.Builder(this,
NOTIF_CHANNEL_ID) // don't forget create a notification channel first
.setOngoing(true)
.setSmallIcon(R.drawable.logo)
.setContentTitle(getString(R.string.app_name))
.setContentText("Monitoring apps.")
.setContentIntent(pendingIntent)
.build());
}
}
I have weird problem woke me up full night, any extra data put in intent in Broadcast, I don't find it later in the Broadcast receiver
here is alarming class ( sender)
private class Alarming {
private AlarmManager alarmManager;
private Intent intent;
private PendingIntent pendingIntent;
Alarming() {
intent = new Intent(TimetableActivity.this, SessionAlarm.class);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
}
public void setSessionAlarm(FiredAlarm firedAlarm) {
/*
we will correct day of month if needed, so we roll elapsed date
to avoid instant alarming.
*/
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(firedAlarm.getDateInMillis());
Calendar now = Calendar.getInstance();
if (calendar.before(now)) {//if session date is before today
calendar.set(Calendar.YEAR, now.get(Calendar.YEAR));
calendar.set(Calendar.WEEK_OF_YEAR, now.get(Calendar.WEEK_OF_YEAR));
}
firedAlarm.setDateInMillis(calendar.getTimeInMillis());
Bundle args = new Bundle();
args.putParcelable(FIRED_ALARM_KEY, firedAlarm);
intent.putExtras(args);
intent.putExtra("INT", 54);
pendingIntent =
PendingIntent.getBroadcast(TimetableActivity.this, firedAlarm.getRequestedCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
firedAlarm.getDateInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES / 5, pendingIntent);
}
}
and here is the broadcast receiver, intent can't receive any kinds of data, primitive, bundle, parcelable...etc
public class SessionAlarm extends BroadcastReceiver {
private static final String TAG = "session_alarm_tag";
public static final String FIRED_ALARM_KEY = "fired_alarm_key";
FiredAlarm firedAlarm;
int requestCode;
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, " Received Integer : " + intent.getIntExtra("INT", -1));
Bundle bundle = intent.getExtras();
firedAlarm = bundle.getParcelable(FIRED_ALARM_KEY);
if (firedAlarm != null) {
//TODO Blabla...
} else Log.i("onReceive", "no parcelable fired alarm found!");
}
private void createNotification(Context context, FiredAlarm firedAlarm) {
//TODO
}
Here is FiredAlarm class :
public class FiredAlarm implements Parcelable {
private int requestedCode;
private long dateInMillis;
private String classroom;
private int duration;
public String getClassroom() {
return classroom;
}
public void setClassroom(String classroom) {
this.classroom = classroom;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public FiredAlarm(int requestedCode, long dateInMillis) {
this.requestedCode = requestedCode;
this.dateInMillis = dateInMillis;
}
public void setRequestedCode(int requestedCode) {
this.requestedCode = requestedCode;
}
public void setDateInMillis(long dateInMillis) {
this.dateInMillis = dateInMillis;
}
public int getRequestedCode() {
return requestedCode;
}
public long getDateInMillis() {
return dateInMillis;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.requestedCode);
dest.writeLong(this.dateInMillis);
dest.writeString(this.classroom);
dest.writeInt(this.duration);
}
public void readFromParcel(Parcel source) {
this.requestedCode = source.readInt();
this.dateInMillis = source.readLong();
this.classroom = source.readString();
this.duration = source.readInt();
}
protected FiredAlarm(Parcel in) {
this.requestedCode = in.readInt();
this.dateInMillis = in.readLong();
this.classroom = in.readString();
this.duration = in.readInt();
}
public static final Parcelable.Creator<FiredAlarm> CREATOR = new Parcelable.Creator<FiredAlarm>() {
#Override
public FiredAlarm createFromParcel(Parcel source) {
return new FiredAlarm(source);
}
#Override
public FiredAlarm[] newArray(int size) {
return new FiredAlarm[size];
}
};
}
I always get negative result, no data, is it really a bug on new SDK 30 level or what?
I disabled sending object, so primitive worked, obviously I'm gonna convert my object to bytes. that solution will work as it's confirmed all the time.
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
I have a togglebutton in the main activity which enables alarm. aid is a unique key.
I need to have an alarm notification when the togglebutton is enabled so on that particular date the alarm will go. When the toggle button is offed the alarm should be canceled.
When the togglebutton is on the toast is not coming. which means the BroadcastReceiver is not called.
But when the toggle is offed the toast comes.
btnToggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (btnToggle.isChecked()) {
AddReminder reminder = new AddReminder(year,
month, day, hour,
min, body, context, aid);
reminder.setNotification();
} else {
AddReminder reminder = new AddReminder(context, mtchid);
reminder.offNotification();
}
}
});
This is the AddReminder Class I coded
public class AddReminder {
private String formattedYear;
private String formattedMonth;
private String formattedDay;
private String formattedHour;
private String formattedMin;
private String body;
private Context context;
private String aid;
private int mYear;
private int mMonth;
private int mDay;
private int mHour;
private int mMin;
private int alrmId = 0;
int aID;
public AddReminder(Context c, String aid){
this.context = c;
this.aid = aid;
aID = Integer.parseInt(aid);
}
public AddReminder(String year, String month, String day, String hour, String min, String body, Context c, String aid){
this.formattedYear = year;
this.formattedMonth = month;
this.formattedDay = day;
this.formattedHour = hour;
this.formattedMin = min;
this.body = body;
this.context = c;
this.aid = aid;
aID = Integer.parseInt(aid);
}
public void setNotification(){
Calendar c = Calendar.getInstance();
mYear = Integer.parseInt(formattedYear);
mMonth = Integer.parseInt(formattedMonth);
mDay = Integer.parseInt(formattedDay) - 1;
mHour = Integer.parseInt(formattedHour);
mMin = Integer.parseInt(formattedMin);
//set Reminder time and date into calendar object
c.set(Calendar.YEAR,mYear);
c.set(Calendar.MONTH, mMonth);
c.set(Calendar.DATE, mDay);// 1 days before
c.set(Calendar.HOUR_OF_DAY, mHour);
c.set(Calendar.MINUTE, mMin);
c.set(Calendar.SECOND, 0);
alrmId = Integer.parseInt(mMonth + "" + mDay + "" + mHour + ""
+ mMin);
Intent in = new Intent(context, ReminderReceiver.class);
in.putExtra("body", body);
in.putExtra("AlrmId", alrmId);
in.putExtra("aid",aid);
PendingIntent sender = PendingIntent.getBroadcast(context, aID, in, PendingIntent.FLAG_CANCEL_CURRENT);
// Get the AlarmManager service
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), sender);
}
public void offNotification(){
Intent intent = new Intent(context, ReminderReceiver.class);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getBroadcast(context, aID, intent,0);
am.cancel(pi);
}
}
This is the broadcast Receiver class
public class ReminderReceiver extends BroadcastReceiver {
String body;
String AlrmId;
String id;
String aid;
#Override
public void onReceive(Context context, Intent intent) {
body = intent.getStringExtra("body");
AlrmId = intent.getStringExtra("AlrmId");
aid = intent.getStringExtra("aid");
Toast.makeText(context, body+"/"+AlrmId+"/"+id+"/"+aid, Toast.LENGTH_SHORT).show();
}
}
The Toast is not shown because it´s not the time for it. The BroadcastReceiver is reached when the alarmManager fires the message at the given time. So to make the simple message when the alarm is turned on, do it inside the setNotification() event:
public void setNotification(){
//Your code
.
.
.
Toast.makeText(context,"ALARM IS ON", Toast.LENGTH_SHORT().show();
}
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.