How can i call my alarm at the time of event occur

2019-09-10 11:42发布

问题:

Explanation: I had created a calendar in my application.Which provides the functionality like add and delete event on the particular day of the month. This event is saved in my SQLite database and display from the db.Whatever, i explained almost things i did.

What i want?

Suppose, i added an event of birthday of my friend on 14th dec in 2016.So, this event will fired at the time when my friend birthday will arrive.

I want to fired that event on particular day like alarm.

Here is my calendar code

public class CalendarFragment extends Fragment{

    View rootView;
    String str_date="";
    String month="";
    String year="";
    ListView event_list;
    String parts[];
    String monthYear="";
    String monthAyear="";

    private SimpleDateFormat dateFormatForMonth = new SimpleDateFormat("MMM - yyyy", Locale.getDefault());
    EventAdapter adapter=null;
    DatabaseHandler db=null;

    List<Event> list_data;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView=inflater.inflate(R.layout.fragment_calendar, container, false);

        event_list=(ListView)rootView.findViewById(R.id.event_listview);


        final ImageButton showPreviousMonthBut = (ImageButton) rootView.findViewById(R.id.prev_button);
        final ImageButton showNextMonthBut = (ImageButton) rootView.findViewById(R.id.next_button);

        db=new DatabaseHandler(getContext());
        final TextView year_name=(TextView)rootView.findViewById(R.id.year_name);

        final CompactCalendarView compactCalendarView = (CompactCalendarView) rootView.findViewById(R.id.compactcalendar_view);
        compactCalendarView.drawSmallIndicatorForEvents(true);
        compactCalendarView.setCurrentDayBackgroundColor(getResources().getColor(R.color.black));

        compactCalendarView.setCurrentSelectedDayBackgroundColor(getResources().getColor(R.color.dark_red));

        compactCalendarView.invalidate();

        year_name.setText(dateFormatForMonth.format(compactCalendarView.getFirstDayOfCurrentMonth()));
        monthYear=dateFormatForMonth.format(compactCalendarView.getFirstDayOfCurrentMonth());

        parts=monthYear.split("-");
        month=parts[0].replace(" ","");
        year=parts[1].replace(" ","");

        monthAyear=month+"-"+year;
        list_data=db.getAllEvents();

        showData(monthAyear);
        compactCalendarView.setListener(new CompactCalendarView.CompactCalendarViewListener() {
            @Override
            public void onDayClick(Date dateClicked) {
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd-MMM-yyyy");
                str_date=simpleDateFormat.format(dateClicked);
                dialogShow();

            }

            @Override
            public void onMonthScroll(Date firstDayOfNewMonth) {
                monthYear=dateFormatForMonth.format(firstDayOfNewMonth);
                parts=monthYear.split("-");
                month=parts[0].replace(" ","");
                year=parts[1].replace(" ","");
                monthAyear=month+"-"+year;
                showData(monthAyear);
                year_name.setText(dateFormatForMonth.format(firstDayOfNewMonth));
            }
        });

        showPreviousMonthBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                compactCalendarView.showPreviousMonth();
            }
        });

        showNextMonthBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                compactCalendarView.showNextMonth();
            }
        });

//
        return rootView;
    }
    public void dialogShow(){

        final Dialog dialog=new Dialog(getContext());
        dialog.setContentView(R.layout.dialog_layout);
        dialog.setTitle("Add Event");

        final TextView event_name=(TextView)dialog.findViewById(R.id.event_name);
        final TextView event_desc=(TextView)dialog.findViewById(R.id.event_description);
        final TextView event_date=(TextView)dialog.findViewById(R.id.event_date);

        event_date.setText(str_date);
        Button btn_save=(Button)dialog.findViewById(R.id.btn_save);

        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                db.addEvent(new Event(event_name.getText().toString(),event_desc.getText().toString(),event_date.getText().toString(),monthAyear));
                dialog.hide();
                Toast.makeText(getContext(), "Event added successfully....", Toast.LENGTH_SHORT).show();
                showData(monthAyear);
            }
        });
        dialog.show();

    }
    public void showData(String monthWyear){
        List<Event> list_data=db.getEvent(monthWyear);
        adapter=new EventAdapter(getActivity(),list_data);
        event_list.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.findItem(R.id.spinner).setVisible(false);
        super.onCreateOptionsMenu(menu, inflater);
    }
}

Please, help me What will i do?

回答1:

You need to use the AlarmManager Class to notify the user through Push Notifications:

So, to get this working, you need to pass the time in milliseconds which represents your target date e.g : 24 Dec 2016 -> Convert to milliseconds and pass it to the AlaramManager

    private Calendar calendar;
    calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
    calendar.set(Calendar.MINUTE, minute);
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.DAY_OF_MONTH, day);
    delay = calendar.getTimeInMillis();

public class SetUpNotification {

public  void setAlarm(long delay, String taskName, String taskDetails, Context context)
{
    Intent alertIntent = new Intent(context, AlertReceiver.class);
    alertIntent.putExtra("TaskName", taskName);
    alertIntent.putExtra("TaskDetails", taskDetails);




    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    final int _id = (int) System.currentTimeMillis();

    Log.d("Delay", delay+"");
    Log.d("ID", _id+"");
    alarmManager.set(AlarmManager.RTC_WAKEUP, delay,
            PendingIntent.getBroadcast(context, _id, alertIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT));
}

}

public class AlertReceiver extends BroadcastReceiver {
static int x = 0;

@Override
public void onReceive(Context context, Intent intent) {

    String taskName = intent.getStringExtra("TaskName");
    String taskDetails = intent.getStringExtra("TaskDetails");

    Log.d("BroadcastReceiver", "OnRecieve");
    createNotification(context, taskName , taskDetails, "EatThatFrog");
    x++;
    Log.d("X", x+"");
}

public void createNotification(Context context, String msg, String msgText, String msgAlert){

    PendingIntent notificIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, DashboardActivity.class), 0);

    NotificationCompat.Builder mBuilder =
            (NotificationCompat.Builder) new NotificationCompat.Builder(context)

                    .setSmallIcon(R.drawable.notification_icon)
                    .setContentTitle(msg)
                    .setTicker(msgAlert)
                    .setContentText(msgText);

    mBuilder.setContentIntent(notificIntent);


    mBuilder.setDefaults(Notification.DEFAULT_SOUND);

    mBuilder.setAutoCancel(true);

    NotificationManager mNotificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(1 + x, mBuilder.build());

}

}



回答2:

You can alarm manager class and put your broadcast receiver to handle that event and for showing event in dialog you can make dialog as an activity which shows your event detail from database

For putting alarm

public void setAlarm(View v){
        Intent intent = new Intent(this,AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ Delay,pendingIntent);


    }

in broad cast receiver

public void onReceive(Context ctxt, Intent intent) {
                Intent i=new Intent(ctxt, EventActivity.class);

                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                ctxt.startActivity(i);
              }