I want to set an alarm on android but its not working, here is my code.. I used the pending intent to start the alarm at a specific time, but when I run the app on my device it doesn't starts.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
findViewById(R.id.startAlarm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 16);
calendar.set(Calendar.MINUTE, 39);
/* Repeating on every 20 minutes interval */
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 20, pendingIntent);
Toast.makeText(MainActivity.this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
});
findViewById(R.id.stopAlarm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Toast.makeText(MainActivity.this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
});
}
I am new to android, so please help. And here is my receiver class
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
}
Have you declared your receiver in the manifest?
<receiver android:name="myPackage.AlarmReceiver"
android:enabled="true" >
</receiver>