Я работаю над приложением, которое будет напоминать пользователю о конкретном событии в определенное время и дату. Я правильно установил уведомления, но иногда они работают, а иногда нет.Уведомления не отображаются в определенное время и дату
Я использую дополнительный блок и получаю дополнительную информацию о том, чтобы отправить кликовую позицию в мой класс приемника (отправка позиции из класса BuddhaEvent классу Myreceiver). Поэтому, если пользователь нажимает на позицию 1, то из класса сообщений следует инициировать уведомление 1. Я помещаю записи журнала в каждую позицию, пожалуйста, проверьте ее.
Выход журнала заявления, как это:
POSITION0 : 0 POSITION0 : 0 POSITION1: 1 POSITION0 : 0 POSITION2 : 2
И это утверждение журнала, когда 4 уведомления показаны
POSITION0 : 0
POSITION0 : 0 POSITION1: 1 POSITION0 : 0 POSITION2 : 2 POSITION0 : 0 POSITION3 : 3
Существует закономерность здесь 0 всегда вызывается перед уведомлением !!!
Я не знаю, что происходит. Первое уведомление работает нормально, но после этого уведомления являются случайными. В большинстве случаев уведомления 2 и 3 поступают одновременно, а иногда 2 ждут 3. Еще одна проблема, которую я заметил, заключается в том, что когда я спускаюсь для уведомлений, все уведомления имеют одинаковое время доставки. Я установил разные идентификаторы для каждого уведомления.
То, что я думаю, это то, что лишние и лишние вещи выполняются неправильно. Я был бы очень признателен, если кто-то поможет мне разобраться в проблеме.
ОБНОВЛЕНИЕ: ТАК, КОГДА Я НАЖМИТЕ ПЕРВЫЙ ПУНКТ НА СПИСОК, УВЕДОМЛЕНИЕ 1 ПОКАЗАЕТ. ЕСЛИ Я ЩЕЛКНУТЬ НА ПУНКТ 2, ТОГДА УВЕДОМЛЕНИЕ 1 И 2 ПОКАЗАЕТСЯ В ОДНОМ ВРЕМЕНИ. КОГДА Я ЩЕЛКНУТЬ НА ПУНКТЕ 3 УВЕДОМЛЕНИЕ 3 И 1 ПОКАЗАТЬ. Заранее спасибо
UPDATE2: ПРОГРАММА звала 0 КАЖДЫЙ РАЗ, я решил изменить PUT POSITION0 что-то другое и теперь только одно уведомление показывает во время (ЭТО ТОЛЬКО РАБОТАЕТ КОГДА ВРЕМЯ ПРОШЛО) НО КОГДА Я TRY К РАСПИСАНИЮ СООБЩЕНИЙ УВЕДОМЛЕНИЯ СОБЫТИЯ ОДИНАКОВЫВАЮТСЯ ПРОБЛЕМЫ (КАК ПОКАЗАТЬ ДВА УВЕДОМЛЕНИЯ В ОДИН ВРЕМЯ).
Это мой Основной класс `общественный класс BuddhaEvent расширяет AppCompatActivity реализует View.OnClickListener { Список MyList общественности = новый ArrayList(); android.support.v4.app.NotificationCompat.Builder уведомление;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_buddhism_event);
fill_eventsList();
fill_ListView();
clickResponse();
Button buddah_button_event = (Button) findViewById(R.id.button_event_back_buddhism);
buddah_button_event.setOnClickListener(this);
}
private void fill_eventsList() {
myList.add(new list("Jan-24", R.drawable.chris, "Mahayana countries the new year starts on the first full moon day in January.", "Mahayana New Year"));
myList.add(new list("Feb-2", R.drawable.chris, "Chinese festival celebrated at the turn of the traditional lunisolar Chinese calendar.", "Chinese New Year"));
myList.add(new list("Feb-15", R.drawable.chris, "Celebrates the day when the Buddha is said to have achieved Parinirvana, or complete Nirvana", "Nirvana Day"));
myList.add(new list("Mar-23", R.drawable.chris, "Celebration in honour of the Sangha, or the Buddhist community", "Magha Puja Day"));
myList.add(new list("Apr-22", R.drawable.chris, "Buddhist New Year", "Theravada New Year"));
myList.add(new list("May-15", R.drawable.chris, "Celebrates the Buddha's birthday", "Wesak - Buddha Day"));
myList.add(new list("Jul-11", R.drawable.chris, "Honor the spirits of one's ancestors.", "Obon"));
myList.add(new list("Jul-19", R.drawable.chris, "Celebrates Buddha's teachings of peace and enlightenment", "Asala - Dharma Day"));
myList.add(new list("Dec-8", R.drawable.chris, "The day that the historical Buddha, Siddhartha Gautama (Shakyamuni), experienced enlightenment", "Bodhi Day"));
}
private void fill_ListView() {
ArrayAdapter<list> listArrayAdapter = new myListAdapter();
ListView list = (ListView) findViewById(R.id.list_eventsView);
list.setAdapter(listArrayAdapter);
}
public void clickResponse() {
ListView l = (ListView) findViewById(R.id.list_eventsView);
if (l != null) {
l.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View viewClicked,
final int position, long id) {
AlertDialog.Builder alert = new AlertDialog.Builder(
BuddhaEvent.this);
alert.setTitle("Reminder!!");
alert.setMessage("Do you want to be reminded of this event in future?");
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("OUTSIDE", "CHECKING WHICH IS CLICKED : " + which);
if (position == 0) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 6);
calendar.set(Calendar.DAY_OF_MONTH, 20);
calendar.set(Calendar.HOUR_OF_DAY, 21);
calendar.set(Calendar.MINUTE, 2);
calendar.set(Calendar.SECOND, 0);
Intent intent = new Intent(getApplicationContext(), MyReceiver.class);
intent.putExtra("position0", position);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
if (position == 1) {
Calendar calendar2 = Calendar.getInstance();
calendar2.set(Calendar.MONTH, 6);
calendar2.set(Calendar.DAY_OF_MONTH, 20);
calendar2.set(Calendar.HOUR_OF_DAY, 21);
calendar2.set(Calendar.MINUTE, 3);
calendar2.set(Calendar.SECOND, 0);
Intent intent2 = new Intent(getApplicationContext(), MyReceiver.class);
intent2.putExtra("position1",position);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(getApplicationContext(), 101, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager2 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager2.set(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(), pendingIntent2);
}
if (position == 2) {
Calendar calendar3 = Calendar.getInstance();
calendar3.set(Calendar.MONTH, 6);
calendar3.set(Calendar.DAY_OF_MONTH, 20);
calendar3.set(Calendar.HOUR_OF_DAY, 21);
calendar3.set(Calendar.MINUTE, 4);
calendar3.set(Calendar.SECOND, 0);
Intent intent3 = new Intent(getApplicationContext(), MyReceiver.class);
intent3.putExtra("position2", position);
PendingIntent pendingIntent3 = PendingIntent.getBroadcast(getApplicationContext(), 105, intent3, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar3.getTimeInMillis(), pendingIntent3);
}
if (position == 3) {
Calendar calendar4 = Calendar.getInstance();
calendar4.set(Calendar.MONTH, 6);
calendar4.set(Calendar.DAY_OF_MONTH, 20);
calendar4.set(Calendar.HOUR_OF_DAY, 21);
calendar4.set(Calendar.MINUTE, 5);
calendar4.set(Calendar.SECOND, 0);
Intent intent4 = new Intent(getApplicationContext(), MyReceiver.class);
intent4.putExtra("position3", position);
PendingIntent pendingIntent4 = PendingIntent.getBroadcast(getApplicationContext(), 102, intent4, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager4 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager4.set(AlarmManager.RTC, calendar4.getTimeInMillis(), pendingIntent4);
}
dialog.dismiss();
}
});
alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
});
}
}
private class myListAdapter extends ArrayAdapter<list> {
public myListAdapter() {
super(BuddhaEvent.this, R.layout.custom_events_layout, myList);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.custom_events_layout, parent, false);
}
list current_list = myList.get(position);
ImageView imageView = (ImageView) itemView.findViewById(R.id.id_image);
imageView.setImageResource(current_list.getIconId());
TextView titleTxt = (TextView) itemView.findViewById(R.id.id_event);
titleTxt.setText(current_list.getName());
EditText text = (EditText) itemView.findViewById(R.id.id_desp);
text.setText(current_list.getDetails());
TextView date = (TextView) itemView.findViewById(R.id.id_date);
date.setText(current_list.getDate());
return itemView;
}
}
public void onClick(View v) {
startActivity(new Intent(BuddhaEvent.this, BuddhaScreen.class));
}
} ` Это MyReceiver класс, который расширяет радиовещательный приемник
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(bundle==null){
return;
}else{
if(bundle.getInt("position0")==0){
Log.d("INSIDE", "POSITION0 : " + bundle.getInt("position0"));
Utils utils = new Utils();
utils.generateNotification(context);
}
if(bundle.getInt("position1")==1){
Log.d("INSIDE", "POSITION1: " + bundle.getInt("position1"));
Utils utils = new Utils();
utils.generateNotification2(context);
}
if(bundle.getInt("position2")==2){
Log.d("INSIDE", "POSITION2 : " + bundle.getInt("position2"));
Utils utils = new Utils();
utils.generateNotification3(context);
}
if(bundle.getInt("position3")==3){
Log.d("INSIDE", "POSITION3 : " + bundle.getInt("position3"));
Utils utils = new Utils();
utils.generateNotification4(context);
}
}
}
}
Это мой Utils класс, который следит за уведомлениями
public class Utils {
public void generateNotification(Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context, BuddhaNow.class);
// replace the old activity if there is a case that it is already opened
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, repeating_intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setWhen(System.currentTimeMillis())
.setContentTitle("Notification Title1")
.setContentText("Notification Text1")
.setAutoCancel(true);
notificationManager.notify(100, builder.build());
}
public void generateNotification2(Context context) {
NotificationManager notificationManager2 = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent repeating_intent2 = new Intent(context, BuddhaNow.class);
// replace the old activity if there is a case that it is already opened
repeating_intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent2 = PendingIntent.getActivity(context, 101, repeating_intent2, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder2 = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent2)
.setSmallIcon(R.drawable.ic_launcher)
.setWhen(System.currentTimeMillis())
.setContentTitle("Notification Title2")
.setContentText("Notification Text2")
.setAutoCancel(true);
notificationManager2.notify(101, builder2.build());
}
public void generateNotification3(Context context) {
NotificationManager notificationManager3 = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent repeating_intent3 = new Intent(context, BuddhaNow.class);
// replace the old activity if there is a case that it is already opened
repeating_intent3.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent3 = PendingIntent.getActivity(context, 102, repeating_intent3, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder3 = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent3)
.setSmallIcon(R.drawable.ic_launcher)
.setWhen(System.currentTimeMillis())
.setContentTitle("Notification Title3")
.setContentText("Notification Text3")
.setAutoCancel(true);
notificationManager3.notify(102, builder3.build());
}
public void generateNotification4(Context context) {
NotificationManager notificationManager4 = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent repeating_intent4 = new Intent(context, BuddhaNow.class);
// replace the old activity if there is a case that it is already opened
repeating_intent4.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent4 = PendingIntent.getActivity(context, 105, repeating_intent4, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder4 = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent4)
.setSmallIcon(R.drawable.ic_launcher)
.setWhen(System.currentTimeMillis())
.setContentTitle("Notification Title4")
.setContentText("Notification Text4")
.setAutoCancel(true);
notificationManager4.notify(105, builder4.build());
}
}
Из-за позиции 2 и 3 типов сигнализации являются RTC , Попробуйте изменить их на RTC_WAKEUP. причина в том, что RTC_WAKEUP разбудит устройство и отправит ожидающее намерения. С другой стороны, RTC доставляет намерение только тогда, когда устройство просыпается. –
@VenkateshGoud спасибо за повторную игру Я уже заменил их RTC_WAKEUP, но все равно не работает – timmy24565
Пожалуйста, расширьте WakefulBroadcastReceiver вместо BroadcastReceiver. –