In my project I want to change a flag value in SharedPreference in particular time every day ,I have implemented the AlarmManager but It is not performing the task . My function to call my receiver class :
public void changeAttendaceFlag(){
Log.d(TAG,"changeAttendaceFlag !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,14);
calendar.set(Calendar.MINUTE,23);
calendar.set(Calendar.SECOND,10);
Intent activateLogin = new Intent(getApplicationContext(),Attendance.class);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(getApplicationContext(),101,activateLogin,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}
My receiver class :
public class Attendance extends BroadcastReceiver {
FcmSession fcmSession;
private static final String TAG = "Attendance";
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, " Attendance Called !!!!!!!!!!!!!!!!!!!!", Toast.LENGTH_SHORT).show();
fcmSession = new FcmSession(context);
fcmSession.store_dialog_value(true);
UtilsMethods utilsMethods = new UtilsMethods();
String time = utilsMethods.getCurrentDateAndTime();
Log.d(TAG,"change attendance flag :"+time);
}
}
Try to use Inexact instead of just simple Repeating for targetSdk greater than 19 API. Check Note at this LINK.
So, Change and try with below line:-
Updated:
Also, In some phone devices(like Xiaomi, Lenovo) app needs to put in AutoStart list. For reference answer check this link.
This is just part of the answer. Here is how you implement the service
onStartCommand
The following return type will be available once your class extends
Service
Note: Data will be reinstantiate once app is closed since the service will be recreated. Save your data in SharedPreferences or SQLite DB.
For autostart, you can do that in settings but when you restart your phone, it will disable autostart and you need to enable it which is a really bad user experience(I think this is for some phone). You can do autostart on your service as well by implementing a
BroadcastReceiver
for BOOT_COMPLETED. Here is a great example https://stackoverflow.com/a/4562747/5870896