Search code examples
androidalarmmanager

How to programatically set the reminder to a specific date


Here i have a code to set the date and time by the user.When the time arrives the notification will pop up. The problem is that the user have to set the time manually.I want to set it programatically to a specific date, lets say 23 January 2016.So that the user have to just click the set button and forget about other things.

java file of the AlarmReceiiver:-

 package com.defcomdevs.invento16;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {
int notifyId=1;
@Override
public void onReceive(Context context, Intent intent) {
    //Toast.makeText(context,"Alarm has been set",Toast.LENGTH_SHORT).show();
    /*Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Ringtone r = RingtoneManager.getRingtone(context, notification);
    r.play();*/
    NotificationCompat.Builder mNotify=new NotificationCompat.Builder(context);
    mNotify.setSmallIcon(R.drawable.index);
    mNotify.setContentTitle("Coding");
    mNotify.setContentText("INVENTO: Coding competition is going to be conducted today.");
    Intent resultIntent=new Intent(context,Coding.class);
    TaskStackBuilder stackBuilder=TaskStackBuilder.create(context);
    stackBuilder.addParentStack(Coding.class); //add the to-be-displayed activity to the top of stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
    mNotify.setContentIntent(resultPendingIntent);
    NotificationManager notificationManager=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(notifyId,mNotify.build());
}
}

AlarmActivity.java :-

package com.defcomdevs.invento16;

import android.os.Bundle;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

public class AlarmActivity extends AppCompatActivity {
private TextView t1,t2,info;
private DatePicker dp;
private TimePicker tp;
private View v1,v2;
private Button b1;
final static int req1=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alarm);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    b1= (Button) findViewById(R.id.submitalarm);
    t1= (TextView) findViewById(R.id.setdate);
    t2= (TextView) findViewById(R.id.settime);
    tp= (TimePicker) findViewById(R.id.timePicker);
    info= (TextView) findViewById(R.id.alarminfo);
    dp= (DatePicker) findViewById(R.id.datepicker);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    Calendar now=Calendar.getInstance(); //initialize calendar variable
    dp.init(
            now.get(Calendar.YEAR),
            now.get(Calendar.MONTH),
            now.get(Calendar.DAY_OF_MONTH),
            null
    );      //read current day,month & year
            //now is a variable,it doesn't mean 'now'
    tp.setCurrentHour(now.get(Calendar.HOUR_OF_DAY));   //set current hour
    tp.setCurrentMinute(now.get(Calendar.MINUTE));  //set current minute
    b1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar current = Calendar.getInstance();    //initialize an instance of Calendar
            Calendar cal = Calendar.getInstance();
            cal.set(dp.getYear(),
                    dp.getMonth(),
                    dp.getDayOfMonth(),
                    tp.getCurrentHour(),
                    tp.getCurrentMinute(),
                    00);        //get current time and date
            if (cal.compareTo(current) <= 0) {
                Toast.makeText(getApplicationContext(),"Invalid Date/Time.Please Re-enter",Toast.LENGTH_LONG).show();
            }
            else{
                setAlarm(cal);
            }
        }
    });



}
private void setAlarm(Calendar target){

    info.setText("\n\n***\n"
            + "Alarm is set@ " + target.getTime() + "\n"
            + "***\n");
    Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), req1, intent, 0);
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, target.getTimeInMillis(), pendingIntent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }
    if(id==android.R.id.home){
        Intent intent=new Intent(this,MainActivity.class);
        startActivity(intent);
        this.finish();
    }
    return super.onOptionsItemSelected(item);
}
}

How could i do this?please help.Thanks.


Solution

  • This code will set the alarm to 23 January, 2016, 18:05:00. So you don't need TimePicker and DatePicker. See doc here: Calendar

    Calendar cal = Calendar.getInstance();
    cal.set(2016, 0, 23, 18, 5, 0);
    
    setAlarm(cal);