Reputation: 309
I create an alarm, it works but the problem is that also after the time I set, the alarm start in the moment I open the application and sometimes, also when is closed and I don't open app. I have this problem since a lot of days, could someone help me?
This is my code:
ScarsdaleHome.java
public class ScarsdaleHome extends Fragment implements OnClickListener{
private AlarmManager alarmManager;
private PendingIntent pendingIntent;
public ScarsdaleHome() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.scarsdale_home_activity, container, false);
Calendar calend = Calendar.getInstance();
calend.setTimeInMillis(System.currentTimeMillis());
calend.set(Calendar.HOUR_OF_DAY, 19);
calend.set(Calendar.MINUTE, 31);
calend.set(Calendar.SECOND, 00);
Intent myIntent = new Intent(getActivity(), MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent,0);
alarmManager = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calend.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
return rootView;
}
public static ScarsdaleHome newIstance(){
ScarsdaleHome frag= new ScarsdaleHome();
return frag;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
MyReceiver.java
public class MyReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
}
}
Upvotes: 0
Views: 771
Reputation: 30611
You have called the setRepeating()
method of the AlarmManager
class, which schedules a repeating alarm that is fired irrespective of whether the user has opened the app or not. If you want to start your Service
only when the user opens the app, then use
alarmManager.set();
or
alarmManager.setExact();
to do so. This will schedule the Service
to start only when the user opens the app.
EDIT:
Define your alarm like this:
if(PendingIntent.getBroadcast(getActivity(), 0,
myIntent,
PendingIntent.FLAG_NO_CREATE) == null){
pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent,0);
alarmManager = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calend.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
This will not reset the alarm if it is already set.
Upvotes: 2