Моя цель — реализовать уведомление, которое появляется в выбранное пользователем время дня. Я уже пробовал Service
, это работает, но проблема в том, что для этого требуется много фонового процесса (код ниже), а другой был AlarmManager
, но, похоже, он не работает должным образом, особенно на API 19+ . Я не смог найти актуальный хорошо закодированный учебник или полезный ответ на аналогичный вопрос здесь, в stackoverflow, поэтому я обращаюсь к вам.
Все вы знаете: если друг отправляет вам сообщение в WhatsApp, вы получаете уведомление, даже когда ваш телефон выключен или находится в спящем режиме (экран выключен). Я уверен, что некоторые из вас уже реализовали что-то подобное.
Задача точно: Мое приложение должно уведомлять пользователя каждый день один раз о его запланированных событиях в его календаре.
Например: Он выбрал 13:00 (я всегда использую 24-часовой формат), чтобы напомнить ему о своих событиях. На следующий день он запланировал 2 мероприятия: - Отвезти детей в школу - Сходить в спортзал
На следующий день в 13:00 приложение показывает уведомление: "У вас на сегодня два события!: 1)... 2)..."
Заполнение уведомления информацией не является проблемой. Это отлично работает, и я много раз проверял это. Мне не хватает только хорошо закодированного фонового потока, который следит за выбранным пользователем временем, чтобы показать уведомление.
Обратите внимание:
Интервал тиков TimerTask составляет 1000 мс (1 секунда). Я уверен, что это не очень хорошо закодировано, но оно работает. Но я ищу лучшее и более экономичное решение.
Кроме того, я добавил разрешение "android.permission.RECEIVE_BOOT_COMPLETED" и "android.permission.WAKE_LOCK".
Служба помечена как START_STICKY
Манифест.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<service android:name=".services.NotificationService" android:exported="false"/>
<receiver android:name=".services.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<activity
android:name=".activities.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
//Other Activities
</application>
</manifest>
Загрузочный приемник:
public class BootReceiver extends WakefulBroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, NotificationService.class));
}
}
Служба уведомлений:
public class NotificationService extends Service{
private Calendar currentCalendar, plannedCalendar;
public static final String FILENAME_SETTINGS = "MySettings";
private static final int MODE_PRIVATE = 0;
SharedPreferences data;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
private Timer timer;
private TimerTask timerTask = new TimerTask() {
@Override
public void run() {
data = getSharedPreferences(FILENAME_SETTINGS, MODE_PRIVATE);
int plannedHour = data.getInt("alarm_hour", 0);
int plannedMinute = data.getInt("alarm_minute", 0);
plannedCalendar = Calendar.getInstance(Locale.getDefault());
plannedCalendar.set(Calendar.MINUTE, plannedMinute);
plannedCalendar.set(Calendar.HOUR_OF_DAY, plannedHour);
plannedCalendar.set(Calendar.SECOND, 0);
plannedCalendar.set(Calendar.MILLISECOND, 0);
//Kalender aktualisieren
currentCalendar = Calendar.getInstance(Locale.getDefault());
currentCalendar.setTimeInMillis(System.currentTimeMillis());
//Check ob es 00:00:00 Uhr ist --> Notification wieder erwuenscht!!!
currentCalendar.set(Calendar.SECOND, 0);
currentCalendar.set(Calendar.MILLISECOND, 0);
if(currentCalendar.get(Calendar.SECOND) == 0 && currentCalendar.get(Calendar.MINUTE) == 0 && currentCalendar.get(Calendar.HOUR_OF_DAY) == 0){
SharedPreferences.Editor editor = data.edit();
editor.putBoolean("notification", false);
editor.apply();
}
//Nochmal aktualisieren weil durch den "Check" manipuliert wurde
currentCalendar = Calendar.getInstance(Locale.getDefault());
currentCalendar.setTimeInMillis(System.currentTimeMillis());
if((currentCalendar.getTimeInMillis() >= plannedCalendar.getTimeInMillis()) & !data.getBoolean("notification", false)) {
PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
notification();
SharedPreferences.Editor editor = data.edit();
editor.putBoolean("notification", true);
editor.apply();
wakeLock.release();
}
}
};
@Override
public void onCreate(){
super.onCreate();
timer = new Timer();
timer.schedule(timerTask, 0, 1000);
}
@Override
public void onDestroy() {
try{
timer.cancel();
timerTask.cancel();
}catch (Exception e){
e.printStackTrace();
}
Intent intent = new Intent("Intent");
intent.putExtra("VALUE", "blalal");
sendBroadcast(intent);
}
public void notification(){
Context context = getApplicationContext();
Intent intent = new Intent(context, LiveSelectActivity.class);
PendingIntent pen = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(getString(R.string.hineweisTrainingsGeplant))
.setContentText("Content")
.setContentIntent(pen)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_add_white_24dp);
Notification notification = builder.build();
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, notification);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
setAlarmClock()
надежен, хотя его элементы пользовательского интерфейса очень сильно связаны с метафорой будильника. Если друг отправляет вам сообщение в Whatsapp, вы получаете уведомление, даже когда ваш телефон выключен или находится в спящем режиме (экран выключен) — они используют Google Cloud Messaging, насколько мне известно. - person CommonsWare   schedule 30.03.2016ACTION_BOOT_COMPLETED
и переназначает будильник на этот момент. - person CommonsWare   schedule 30.03.2016