如何在android studio中响铃

时间:2018-04-18 11:15:55

标签: android firebase

您好我正在使用Android中的提醒应用程序并使用 Firebase 作为数据库。我的提醒正确设置没有任何问题但是当我从Firebase检索数据时,我得到特定日期的数据但不知道如何按时输入用户。 这是我的代码:

Miscelleneous.java

package com.example.dell.reminder;

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.DatePickerDialog;
    import android.app.TimePickerDialog;
    import android.content.Intent;
    import android.graphics.Color;
    import android.graphics.drawable.ColorDrawable;
    import android.support.annotation.NonNull;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.Toolbar;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.Button;
    import android.widget.CalendarView;
    import android.widget.DatePicker;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.TimePicker;
    import android.widget.Toast;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.FirebaseUser;
    import com.google.firebase.database.DataSnapshot;
    import com.google.firebase.database.DatabaseError;
    import com.google.firebase.database.DatabaseReference;
    import com.google.firebase.database.FirebaseDatabase;
    import com.google.firebase.database.ValueEventListener;

    import java.sql.Time;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;

    public class Miscelleneous extends Activity {
        private static Button setting,resetting;
        private EditText text;
        private TextView rem1,date1,time1;
        private FirebaseDatabase fdb;
        private DatabaseReference db5;
        private  Button btn1,btn2;
        private DatePickerDialog.OnDateSetListener dateSetListener;
        private TimePickerDialog.OnTimeSetListener timeSetListener;
        String strDate;
        String timeString = "";
        public static final String REM_KEY = "com.example.dell.reminder.REM_KEY";
        public static final String DATE_KEY = "com.example.dell.reminder.DATE_KEY";
        public static final String TIME_KEY = "com.example.dell.reminder.TIME_KEY";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.miscelleneous);

            setting = (Button)findViewById(R.id.remset);
            Toolbar tool = (Toolbar)findViewById(R.id.setreminder);
            text = (EditText)findViewById(R.id.editText);
            btn1 = (Button)findViewById(R.id.selectdate);
            btn2 = (Button)findViewById(R.id.selecttime);
            rem1 = (TextView)findViewById(R.id.rem1);
            date1 = (TextView)findViewById(R.id.date1);
            time1 = (TextView)findViewById(R.id.time11);
            btn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Calendar cal = Calendar.getInstance();
                    int year = cal.get(Calendar.YEAR);
                    int month = cal.get(Calendar.MONTH);
                    int day = cal.get(Calendar.DAY_OF_MONTH);

                    DatePickerDialog dialog = new DatePickerDialog(Miscelleneous.this,
                        android.R.style.Theme_DeviceDefault_Dialog_MinWidth,dateSetListener,year,month,day);
                    //dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                        dialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
                    dialog.show();
                }
            });
           dateSetListener = new DatePickerDialog.OnDateSetListener() {
               @Override
               public void onDateSet(DatePicker datePicker, int year, int month, int day)     {

                   // Log.d("Miscelleneous","OnDateSet: mm/dd/yyyy" +month + "/" + day + "/" + year);
                   Calendar calendar = Calendar.getInstance();
                   calendar.set(year, month, day);
                   month = month - 1;
                   SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
                   strDate = format.format(calendar.getTime());
                   // date = day + "/" + month + "/" + year;
                    btn1.setText(strDate);
               }
           };
            btn2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Calendar cal = Calendar.getInstance();
                    int hours = cal.get(Calendar.HOUR_OF_DAY);
                    int minute = cal.get(Calendar.MINUTE);
                    //int second = cal.get(Calendar.SECOND);
                    TimePickerDialog tdialog = new TimePickerDialog(Miscelleneous.this,
                        android.R.style.Theme_Holo_Light_Dialog,timeSetListener,hours,minute,false);
                    tdialog.show();
                }
            });
            timeSetListener = new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int hours_x, int minute_x) {
                    //String timeString = "";
                    if (hours_x == 0) {
                        timeString = "12:"+minute_x+" "+"a.m.";
                        btn2.setText(timeString);
                    } else if (hours_x < 12) {
                        timeString = hours_x + ":" + minute_x +" "+ "a.m.";
                        btn2.setText(timeString);
                    } else if (hours_x == 12) {
                        timeString = hours_x+":"+minute_x+" "+"p.m.";
                        btn2.setText(timeString);
                     } else {
                        timeString = hours_x-12+ ":" + minute_x +" "+"p.m.";
                        btn2.setText(timeString);
                    }
                }
            };
            db5 = FirebaseDatabase.getInstance().getReference().child("user1");

            setting.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if(text.getText().toString().isEmpty())
                        Toast.makeText(getApplicationContext(),"Please write something",Toast.LENGTH_LONG).show();
                    else if(btn1.getText().toString().isEmpty() && btn2.getText().toString().isEmpty()) {
                        Toast.makeText(getApplicationContext(),"Please select date and time",Toast.LENGTH_LONG).show();
                    }
                    else if(btn1.getText().toString().isEmpty()){
                        Toast.makeText(getApplicationContext(),"Please select date",Toast.LENGTH_LONG).show();
                    }
                    else if(btn2.getText().toString().isEmpty()){
                        Toast.makeText(getApplicationContext(),"Please select time",Toast.LENGTH_LONG).show();
                    }
                    else{
                        final HashMap<String,String> adddata = new HashMap<String, String>();
                        adddata.put("Reminder",text.getText().toString());
                        adddata.put("Date",btn1.getText().toString());
                        adddata.put("Time",btn2.getText().toString());
                        db5.child("Users Own").setValue(adddata).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if(task.isSuccessful()){
                                    Toast.makeText(getApplicationContext(),
                                        "Reminder has been set successfully!!!",Toast.LENGTH_SHORT).show();
                                }else
                                {
                                    Toast.makeText(getApplicationContext(),
                                        "Problem in reminder setting !!",Toast.LENGTH_LONG).show();
                                }
                            }
                        });

                        retrive();
                        /*Intent intent = new Intent(Miscelleneous.this,History.class);
                        intent.putExtra(REM_KEY,validate1);
                        intent.putExtra(DATE_KEY,validate2);
                        intent.putExtra(TIME_KEY,validate3);
                        startActivity(intent);*/
                        //send();

                    }
                }
            });
        }
        /*private void send(){
            final ArrayList<String> arrayList = new ArrayList<>();
            arrayList.add(validate1);
            arrayList.add(validate2);
            arrayList.add(validate3);
            Intent i = new Intent(Miscelleneous.this,History.class);
            i.putExtra(REM_KEY,arrayList);
            startActivity(i);
        }*/
        private void retrive(){
        long current_date = System.currentTimeMillis();
        long current_time = System.currentTimeMillis();
       // String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm a");
        String System_Date = sdf.format(current_date);
        final String System_Time = sdf1.format(current_time);
        String usrdate = btn1.getText().toString().trim();
        final String usrtime = btn2.getText().toString().toLowerCase().trim();
       // Log.d("Miscelleneous",usrtime);
       // Log.d("Miscelleneous",usrdate);
        if( System_Date.equals(usrdate)){
            db5.child("Users Own").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    String tim="",date="",remind="";
                    for (DataSnapshot cdata:dataSnapshot.getChildren()) {
                        remind = cdata.getValue(String.class).toString();
                        date = cdata.getValue(String.class).toString();
                        tim = cdata.getValue(String.class).toString();
                    }
                    if(usrtime.equals(System_Time)){
                        Log.d("Miscelleneous","actual reminder");
                        Log.d("Miscelleneous","Date:"+remind);
                        Log.d("Miscelleneous","Reminder:"+date);
                        Log.d("Miscelleneous","Time:"+tim);

                        rem1.setText("Reminder : "+remind);
                        date1.setText("Date : "+date);
                        time1.setText("Time : "+tim);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
            //Toast.makeText(this,"User date matches with System date",Toast.LENGTH_SHORT).show();
        }
        else {

            //Toast.makeText(this,"User date doesn't matches with System date",Toast.LENGTH_SHORT).show();
        }
    }
}

请有人给我一个解决方案,

由于

2 个答案:

答案 0 :(得分:2)

使用广播接收器并设置您获得的时间。

答案 1 :(得分:1)

您可以使用 AlarmManager 在特定时间响铃或通知用户。

private AlarmManager alarmManager;
private static Intent alarmIntent;
private static PendingIntent pendingAlarmIntent;

public void setTimings(){

    private Calender alarmCalender = Calendar.getInstance();
    alarmCalender.setTimeInMillis(System.currentTimeMillis());
    alarmCalender.set(Calendar.HOUR_OF_DAY, "hour");       // hour=07
    alarmCalender.set(Calendar.MINUTE, "minute");          // minute=01
    alarmCalender.set(Calendar.SECOND, "second");          // second=0
    alarmCalender.set(Calendar.MILLISECOND, "millisecond");//millisecond=0

    setAlarm(AlarmManager.RTC_WAKEUP, alarmCalender, AlarmManager.INTERVAL_DAY);

}


public void setAlarm(int type, Calendar calendar, long timeInMillis){

   alarmIntent = new Intent(context, yourBroadcastReciever.class);
   pendingAlarmIntent = PendingIntent.getBroadcast(context, Constant.ALARM_REQUEST_CODE, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

   alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   alarmManager.setRepeating(type, calendar.getTimeInMillis(), timeInMillis, pendingAlarmIntent);
}

要在特定时间处理闹钟,请创建“接收器”

<强> yourBroadcastReciever.class

 @Override
    public void onReceive(Context context, Intent intent) {
       // here you handle the task when alarm ringing
    }

[注意:创建警报时必须使用Intent和Pending Intent]