В настоящее время я пытаюсь запустить исследование, в котором участникам предлагается сообщать информацию шесть раз в день в течение пяти дней с помощью своего устройства Android. Чтобы добиться этого, я планирую 30 будильников при первом запуске приложения. Мой код отлично работает на моем устройстве (Nexus 6p под управлением Android 8.1) и, по-видимому, отлично работает примерно от 60 до 70% моих участников. Однако для остальных 30-40% эти участники никогда не получают сигнал тревоги (наиболее типичный), или сигналы перестают появляться через день или два в исследовании.
Сначала, при необходимости, я создаю канал для своих предупреждений
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "my_channel_01";
String description = "my_channel_01";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("my_channel_01", name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
Затем я добавляю все 30 дат, которые я хочу, чтобы мои тревоги отключались, в список alarmDates, затем перебираю список и устанавливаю будильник для каждой даты.
public void startAlert(){
for (int i = 0; i < alarmDates.size(); i++){
int request_code = 234324243;
request_code += i;
String string = alarmDates.get(i);
DateFormat format = new SimpleDateFormat("MMMM d, yyyy HH:mm:ss");
Date date = new Date();
try {
date = format.parse(string);
} catch (ParseException e) {
e.printStackTrace();
}
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), request_code, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= 23) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
date.getTime(), pendingIntent);
} else if (Build.VERSION.SDK_INT >= 19) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
}
}
Мой приемник вещания выглядит так:
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Create the notification to be shown
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context, "my_channel_01")
//.setSmallIcon(R.drawable.icon)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle("How are things going?")
.setContentText("Tap here to tell us how you're feeling")
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setAutoCancel(true)
.setPriority(2);
Intent resultIntent = new Intent(context, MainActivity2.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
context,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
Random rand = new Random();
int n = rand.nextInt(5000) + 1;
// Sets an ID for the notification
int mNotificationId = n;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// Make sure any previously launched alarms are removed
mNotifyMgr.cancelAll();
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
В настоящее время я работаю с тремя участниками, чтобы разобраться с этой проблемой. Они используют Samsung Galaxy J7, LG Tribute Dynasty и Galaxy s9 +. Никто из них не сообщает, что видел какие-либо уведомления из моего приложения.
Любая помощь очень ценится.