Я видел похожие вопросы, но нет подходящего или правильного ответа, некоторые даже противоречивы.
Вопрос прост: не может ли AlarmManager работать долго (более нескольких часов)?
У меня есть приложение с массивом сообщений. При первом запуске каждое сообщение получает персональное время (Calendar obj), приложение устанавливает alarmManager для каждого и сохраняет все в sharedPrefference. Приведенный ниже код (я, конечно, скопировал только соответствующий) работает нормально, даже когда я перезагружаю устройство (благодаря sharedPref) в течение нескольких часов, а затем прекращает отправку уведомлений.
Если я установил все время сообщения в короткий срок (скажем, 10 мсг, 1 раз в 5 минут), он прекрасно работает, и все они отправлены. Но если я планирую его на каждый час, он будет работать только на первые 2-3 часа.
Я видел, что некоторые ответы говорят, что alarmManager не подходит для ломг, а другие говорят, что это отличный сервис для него :( может кто-нибудь дать мне профессиональный ответ?
Я также пробовал alarmManager.setAlarmClock () и setExactAndAllowWhileIdle (), но результаты те же.
*
msg.activity
// somewhere at the code:
createNotificationChannel ();
myMsg.msgAddTimes (); // adding Calendar for each msg
addAlerts (myMsg); // add alerts for each msg
private void addAlerts (MyMsg myMsg) {
MyReceiver rc = new MyReceiver ();
for (int i = 1; i < myMsg.totalMsgNum; i++)
rc.setSingleNotifications (this, myMsg.msg[i]);
}
private void createNotificationChannel () {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
CharSequence name = "myMessagesApp";
String description = "daily alert";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel (CHANNEL_ID, name, importance);
channel.setDescription (description);
NotificationManager notificationManager = getSystemService (NotificationManager.class);
notificationManager.createNotificationChannel (channel);
}
}
MyReciever. java
public class MyReceiver extends BroadcastReceiver {
final String CHANNEL_ID = "777";
SharedPreferences pref;
SharedPreferences.Editor editor;
@RequiresApi (api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onReceive (Context context, Intent intent)
{
// get the relevant content
pref = context.getSharedPreferences ("SAVED_FILE", Context.MODE_PRIVATE);
int atMsgNum = pref.getInt ("CURRENT", 1);
String json = pref.getString ("MSG_OBJ", "");
Gson gson = new Gson ();
MyMsg myMsg = gson.fromJson (json, MyMsg.class);
String titleStr = myMsg.msg [atMsgNum].title;
String contentStr = myMsg.msg [atMsgNum].msg;
atMsgNum++;
// update current msg num
editor = pref.edit ();
editor.putInt ("CURRENT", atMsgNum);
editor.commit ();
// intent for showing the msg activity
intent.setClass (context, OnPressTipNotificationActivity.class);
intent.putExtra ("ID", atMsgNum);
intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// notification
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntentWithParentStack(intent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(atMsgNum, 0);
NotificationCompat.Builder builder;
builder = new NotificationCompat.Builder (context, CHANNEL_ID)
.setSmallIcon (R.drawable.single_pics_logo)
.setContentTitle (titleStr)
.setContentText (contentStr)
.setStyle (new NotificationCompat.BigTextStyle ()
.bigText (contentStr))
.setPriority (NotificationCompat.PRIORITY_HIGH)
.setContentIntent (pendingIntent)
.setAutoCancel (true)
.setBadgeIconType (NotificationCompat.BADGE_ICON_SMALL)
.setVisibility (NotificationCompat.VISIBILITY_PUBLIC);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from (context);
notificationManager.notify (atMsgNum, builder.build ());
}
public void setSingleNotifications (Context context, Msg msg) {
Intent intent = new Intent (context, MyReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast (context, msg.num, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance ();
calendar.setTimeInMillis (System.currentTimeMillis ());
calendar.set (Calendar.YEAR, msg.calendar.get (Calendar.YEAR));
calendar.set (Calendar.MONTH, msg.calendar.get (Calendar.MONTH));
calendar.set (Calendar.DAY_OF_MONTH, msg.calendar.get (Calendar.DAY_OF_MONTH));
calendar.set (Calendar.HOUR_OF_DAY, msg.calendar.get (Calendar.HOUR_OF_DAY));
calendar.set (Calendar.MINUTE, msg.calendar.get (Calendar.MINUTE));
calendar.set (Calendar.SECOND, msg.calendar.get (Calendar.SECOND));
calendar.add (Calendar.SECOND, 1);
AlarmManager alarmManager = (AlarmManager) context.getSystemService (ALARM_SERVICE);
alarmManager.set (AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis (), alarmIntent);
}
}
манифест включает в себя:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
android:excludeFromRecents="true"
<receiver
android:name=".MyReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
<action android:name="android.media.action.DISPLAY_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>