我有一个应用程序,用户可以在其中选择一个或最多2个每日提醒,以在用户选择的时间触发。用户选择的时间存储在本地。用户可以在任何时间点编辑和/或删除提醒。但是,每日提醒不会发出通知,而且我不确定我哪里出错了。非常感谢您提供任何有关纠正方法的帮助,以便每天在用户选择的时间触发提醒。
MainActivity
public class Monitor1 extends Fragment implements View.OnClickListener {
ImageButton btnSetNotification;
private ListView listView;
public static TabbedDialog dialog;
ReminderAdapter adapter;
ArrayList<Reminder> list = new ArrayList<>();
public String isSelected;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_monitor1, container, false);
pref2 = getActivity().getSharedPreferences("MyPref2", Context.MODE_PRIVATE);
editor = pref2.edit();
editor.apply();
init(v);
return v;
}
private void init(View v) {
btnSetNotification = v.findViewById(R.id.btnSetNotification);
listView = v.findViewById(R.id.listView);
btnSetNotification.setOnClickListener(this);
btnSetNotification.setScaleType(ImageView.ScaleType.FIT_XY);
}
public void addList(Reminder r) throws Exception {
list.add(r);
adapter.notifyDataSetChanged();
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DbHelper dbHelper = new DbHelper(getActivity());
JSONArray jsonArray = dbHelper.getAllReminders();
adapter = new ReminderAdapter(getActivity(), list, this);
listView.setAdapter(adapter);
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject obj = jsonArray.getJSONObject(i);
String time = obj.getString("time");
Integer id = obj.getInt("id");
Reminder r = new Reminder();
r.setCode(id);
r.setTime(time);
addList(r);
} catch (Exception e) {
e.printStackTrace();
}
}
isSelected = pref2.getString("selectedTab", "");
}
public void handleSelection() {
isSelected = pref2.getString("selectedTab", "");
if (!isSelected.equals("")) {
if (list.size() == 0) {
editor.clear();
editor.apply();
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSetNotification:
dialogTabbed();
break;
}
}
private void dialogTabbed() {
FragmentManager manager = getChildFragmentManager();
dialog = new TabbedDialog();
dialog.show(manager, "tag");
}
public static class TabbedDialog extends DialogFragment {
public TabbedDialog() {
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dialog_tabbed, container, false);
TabLayout tabs = v.findViewById(R.id.tabLayout);
ViewPager viewpager = v.findViewById(R.id.viewpager);
viewpager.setAdapter(new MonitorPagerAdapter(getChildFragmentManager(), getActivity()));
tabs.setupWithViewPager(viewpager);
return v;
}
}
public static class ODFragment extends Fragment {
private Button btnOd;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_od, container, false);
initView(v);
return v;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && getActivity() != null && isAdded() && btnOd != null) {
changeViews();
}
}
void changeViews() {
((Monitor1) getParentFragment().getParentFragment()).isSelected = ((Monitor1) getParentFragment().getParentFragment()).pref2.getString("selectedTab", "");
if (((Monitor1) getParentFragment().getParentFragment()).isSelected.equals("od") && ((Monitor1) getParentFragment().getParentFragment()).list.size() > 0) {
btnOd.setEnabled(false);
} else if (((Monitor1) getParentFragment().getParentFragment()).isSelected.equals("bd") && ((Monitor1) getParentFragment().getParentFragment()).list.size() > 0) {
btnOd.setEnabled(false);
}
}
private void initView(View v) {
btnOd = v.findViewById(R.id.btnOd);
changeViews();
btnOd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(getActivity(), AlertDialog.THEME_HOLO_DARK, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String selectedTime = selectedHour + ":" + selectedMinute;
DbHelper dbHelper = new DbHelper(getActivity());
long code = dbHelper.saveReminder(selectedTime);
if (code != -1) {
Calendar calendar1 = Calendar.getInstance();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, selectedHour);
calendar.set(Calendar.MINUTE, selectedMinute);
calendar.set(Calendar.SECOND, 0);
Intent intent1 = new Intent(getActivity(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), (int) code, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
if (am != null) {
if (calendar.before(calendar1)) {
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + 86400000, AlarmManager.INTERVAL_DAY, pendingIntent);
} else {
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
Toast.makeText(getActivity(), "A daily reminder has been set for " + selectedTime, Toast.LENGTH_SHORT).show();
((Monitor1) getParentFragment().getParentFragment()).editor.putString("selectedTab", "od");
((Monitor1) getParentFragment().getParentFragment()).editor.apply();
Reminder r = new Reminder();
r.setCode((int) code);
r.setTime(selectedTime);
try {
TabbedDialog parentFrag = ((TabbedDialog) ODFragment.this.getParentFragment());
Monitor1 parentFrag1 = ((Monitor1) parentFrag.getParentFragment());
parentFrag1.addList(r);
((Monitor1) getParentFragment().getParentFragment()).handleSelection();
} catch (Exception e) {
e.printStackTrace();
}
}
dialog.dismiss();
}
}
}, hour, minute, true);
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
});
}
}
public static class BDFragment extends Fragment {
Button btnOdR1, btnOdR2;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_bd, container, false);
initView(v);
return v;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && getActivity() != null && isAdded() && btnOdR1 != null) {
changeViews();
}
}
private void changeViews() {
((Monitor1) getParentFragment().getParentFragment()).isSelected = ((Monitor1) getParentFragment().getParentFragment()).pref2.getString("selectedTab", "");
if (((Monitor1) getParentFragment().getParentFragment()).isSelected.equals("bd") && ((Monitor1) getParentFragment().getParentFragment()).list.size() > 0) {
if (((Monitor1) getParentFragment().getParentFragment()).list.size() == 1) {
btnOdR1.setEnabled(false);
btnOdR2.setEnabled(true);
} else if (((Monitor1) getParentFragment().getParentFragment()).list.size() == 2) {
btnOdR1.setEnabled(false);
btnOdR2.setEnabled(false);
}
} else if (((Monitor1) getParentFragment().getParentFragment()).isSelected.equals("od") && ((Monitor1) getParentFragment().getParentFragment()).list.size() > 0) {
btnOdR1.setEnabled(false);
btnOdR2.setEnabled(false);
}
}
private void initView(View v) {
btnOdR1 = v.findViewById(R.id.btnOdR1);
btnOdR2 = v.findViewById(R.id.btnOdR2);
changeViews();
btnOdR1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setReminder(btnOdR1);
}
});
btnOdR2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setReminder(btnOdR2);
}
});
}
int bdCount = 0;
private void setReminder(final Button btn) {
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(getActivity(),AlertDialog.THEME_HOLO_DARK, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String selectedTime = selectedHour + ":" + selectedMinute;
DbHelper dbHelper = new DbHelper(getActivity());
long code = dbHelper.saveReminder(selectedTime);
if (code != -1) {
Calendar calendar1 = Calendar.getInstance();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, selectedHour);
calendar.set(Calendar.MINUTE, selectedMinute);
calendar.set(Calendar.SECOND, 0);
Intent intent1 = new Intent(getActivity(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), (int) code, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
if (am != null) {
if (calendar.before(calendar1)) {
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + 86400000, AlarmManager.INTERVAL_DAY, pendingIntent);
} else {
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
Toast.makeText(getActivity(), "A daily reminder has been set for " + selectedTime, Toast.LENGTH_SHORT).show();
Reminder r = new Reminder();
r.setCode((int) code);
r.setTime(selectedTime);
((Monitor1) getParentFragment().getParentFragment()).editor.putString("selectedTab", "bd");
((Monitor1) getParentFragment().getParentFragment()).editor.apply();
try {
TabbedDialog parentFrag = ((TabbedDialog) BDFragment.this.getParentFragment());
Monitor1 parentFrag1 = ((Monitor1) parentFrag.getParentFragment());
parentFrag1.addList(r);
((Monitor1) getParentFragment().getParentFragment()).handleSelection();
} catch (Exception e) {
e.printStackTrace();
}
if (btn.getId() == btnOdR1.getId()) {
btnOdR1.setEnabled(false);
} else if (btn.getId() == btnOdR2.getId()) {
btnOdR2.setEnabled(false);
}
}
}
if (!btnOdR1.isEnabled() && !btnOdR2.isEnabled()) {
dialog.dismiss();
}
}
}, hour, minute, true);
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
}
SharedPreferences pref2;
SharedPreferences.Editor editor;
}
AlarmReceiver
public class AlarmReceiver extends BroadcastReceiver {
int MID = 1;
@RequiresApi(api = Build.VERSION_CODES.KITKAT_WATCH)
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.e("got>", "got");
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
String textTitle = "Times UP";
String textContent = "TT";
if (intent.getAction() != null && intent.getAction().equals("com.notification")) {
textTitle = "Times up";
textContent = "TT";
int id = Integer.parseInt(intent.getStringExtra("a"));
DbHelper dbHelper = new DbHelper(context);
dbHelper.delete(id, "table_notification");
}
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context, "12")
.setBadgeIconType(R.mipmap.ic_launcher_square_launch_round)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher_square_launch_round))
.setColor(Color.BLACK)
.setSmallIcon(R.mipmap.ic_launcher_square_launch_round)
.setContentTitle(textTitle)
.setContentText(textContent).setSound(alarmSound)
.setAutoCancel(true).setWhen(when)
.setVibrate(new long[]{100, 1000, 1000, 1000, 100})
.setLights(Color.RED, 100, 100);
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (!pm.isInteractive()) {
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MH24_ScreenLock");
wl.acquire(10000);
PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MH24_ScreenLock");
wl_cpu.acquire(10000);
if (intent.getAction() != null && intent.getAction().equals("com.notification")) {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), i,
PendingIntent.FLAG_ONE_SHOT);
mNotifyBuilder.setContentIntent(pendingIntent);
}
if (notificationManager != null) {
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("12",
"Questionnaire Notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(MID, mNotifyBuilder.build());
}
}
}}
BootReceiver
public class BootCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
DbHelper dbHelper = new DbHelper(context);
ArrayList<Notification> listNotifications = dbHelper.getAllNotifications();
for (int i = 0; i < listNotifications.size(); i++) {
Notification n = listNotifications.get(i);
Integer mYear = Integer.valueOf(n.getDate().split("/")[2]);
Integer mMonth = Integer.valueOf(n.getDate().split("/")[1]);
Integer mDay = Integer.valueOf(n.getDate().split("/")[0]);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.clear();
calendar.set(mYear, mMonth, mDay);
Log.e("got", "" + mDay);
Intent intent1 = new Intent(context, AlarmReceiver.class);
intent1.setAction("com.notification");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, Integer.parseInt("99".concat(String.valueOf(n.getId()))), intent1, PendingIntent.FLAG_ONE_SHOT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
if (am != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
} else {
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
}
JSONArray jsonArray = dbHelper.getAllReminders();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = null;
try {
obj = jsonArray.getJSONObject(i);
String time = obj.getString("time");
Integer id = obj.getInt("id");
Log.e("time>", time);
Calendar calendar1 = Calendar.getInstance();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time.split(":")[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(time.split(":")[1]));
calendar.set(Calendar.SECOND, 0);
Intent intent1 = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, id, intent1, PendingIntent.FLAG_ONE_SHOT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
if (am != null) {
if (calendar.before(calendar1)) {
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + 86400000, AlarmManager.RTC_WAKEUP, pendingIntent);
} else {
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.RTC_WAKEUP, pendingIntent);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
适配器
public class ReminderAdapter extends ArrayAdapter<Reminder> {
ArrayList<Reminder> list;
Context c;
Monitor1 monitor1;
public ReminderAdapter(Context context, ArrayList<Reminder> list, Monitor1 monitor1) {
super(context, R.layout.item_reminder);
this.list = list;
this.c = context;
this.monitor1 = monitor1;
}
@Override
public int getCount() {
return list.size();
}
@Nullable
@Override
public Reminder getItem(int position) {
return list.get(position);
}
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
final Reminder reminder = getItem(position);
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_reminder, parent, false);
TextView tvName = convertView.findViewById(R.id.tvTime);
if (Integer.valueOf(reminder.time.split(":")[0]) > 12) {
tvName.setText(Integer.valueOf(reminder.getTime().split(":")[0]) - 12 + ":" + reminder.getTime().split(":")[1] + " PM");
} else {
if (Integer.valueOf(reminder.getTime().split(":")[1]) > 0 && Integer.valueOf(reminder.getTime().split(":")[0]) == 12) {
tvName.setText(reminder.getTime() + " PM");
} else {
tvName.setText(reminder.getTime() + " AM");
}
}
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteEvent(reminder, position);
}
});
return convertView;
}
private void deleteEvent(final Reminder reminder, final int position) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
final View v = LayoutInflater.from(c).inflate(R.layout.dialog_edit, null, false);
builder.setView(v);
final AlertDialog dialog = builder.create();
Button btnEdit = v.findViewById(R.id.btnEdit);
Button btnDel = v.findViewById(R.id.btnDel);
dialog.setCanceledOnTouchOutside(false);
btnEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
setReminder(Integer.valueOf(reminder.getTime().split(":")[0]), Integer.valueOf(reminder.getTime().split(":")[1]), position, reminder.getCode());
}
});
btnDel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
dialogToDelete(reminder.getCode(), position);
}
});
dialog.show();
}
private void setReminder(int hour, int minute, final int pos, final int code) {
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(c, android.app.AlertDialog.THEME_HOLO_DARK, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String selectedTime = selectedHour + ":" + selectedMinute;
Calendar calendar1 = Calendar.getInstance();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, selectedHour);
calendar.set(Calendar.MINUTE, selectedMinute);
calendar.set(Calendar.SECOND, 0);
Intent intent1 = new Intent(c, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(c, code, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) c.getSystemService(ALARM_SERVICE);
if (am != null) {
if (calendar.before(calendar1)) {
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + 86400000, AlarmManager.INTERVAL_DAY, pendingIntent);
} else {
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
Toast.makeText(c, "Reminder updated", Toast.LENGTH_SHORT).show();
Reminder r = new Reminder();
r.setCode(code);
r.setTime(selectedTime);
try {
DbHelper dbHelper = new DbHelper(c);
dbHelper.upadteCount(r);
list.set(pos, r);
notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, hour, minute, true);
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
public void dialogToDelete(final int id, final int position) {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(c);
builder.setMessage("Delete Daily Reminder?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
dialoginterface.dismiss();
DbHelper dbHelper = new DbHelper(c);
dbHelper.delete(id, DbHelper.TABLE_REMINDER);
list.remove(position);
notifyDataSetChanged();
monitor1.handleSelection();
Intent intent1 = new Intent(c, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(c, id, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) c.getSystemService(ALARM_SERVICE);
am.cancel(pendingIntent);
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
dialoginterface.dismiss();
}
});
final android.app.AlertDialog alertDialog = builder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface arg0) {
alertDialog.getButton(android.app.AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(c, R.color.orange));
alertDialog.getButton(android.app.AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(c, R.color.orange));
}
});
alertDialog.show();
}
}