Вопрос:
Как можно отправить уведомление программно, когда приложение полностью закрыто?
Пример. Пользователь закрыл приложение, также в Android Taskmanager, и ждет. Приложение должно отправить уведомление после X секунд или когда приложение проверяет наличие обновлений.
Я попытался работать с этими примерами кода, но:
- Нажатие уведомлений при закрытии приложения – слишком много действий/не работает
- Как получить мое приложение для отправки уведомления, когда оно закрыто? – много информации, но я не знаю, как с этим бороться
- Как отправить локальное уведомление и андроид при закрытии приложения? – много информации, но я не знаю, как с этим бороться
Если вы можете, попробуйте объяснить это на примере, потому что новички (как и я) могут легче изучить его таким образом.
Лучший ответ:
Вы можете использовать эту службу, все, что вам нужно сделать, это запустить эту службу onStop() в жизненном цикле вашей деятельности. С этим кодом: startService(new Intent(this, NotificationService.class)); затем вы можете создать новый класс Java и вставить в него этот код:
public class NotificationService extends Service { Timer timer; TimerTask timerTask; String TAG = «Timers»; int Your_X_SECS = 5; @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, «onStartCommand»); super.onStartCommand(intent, flags, startId); startTimer(); return START_STICKY; } @Override public void onCreate() { Log.e(TAG, «onCreate»); } @Override public void onDestroy() { Log.e(TAG, «onDestroy»); stoptimertask(); super.onDestroy(); } //we are going to use a handler to be able to run in our TimerTask final Handler handler = new Handler(); public void startTimer() { //set a new Timer timer = new Timer(); //initialize the TimerTask job initializeTimerTask(); //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms timer.schedule(timerTask, 5000, Your_X_SECS * 1000); // //timer.schedule(timerTask, 5000,1000); // } public void stoptimertask() { //stop the timer, if it not already null if (timer != null) { timer.cancel(); timer = null; } } public void initializeTimerTask() { timerTask = new TimerTask() { public void run() { //use a handler to run a toast that shows the current timestamp handler.post(new Runnable() { public void run() { //TODO CALL NOTIFICATION FUNC YOURNOTIFICATIONFUNCTION(); } }); } }; } }
После этого вам нужно только объединить сервис с manifest.xml:
<service android:name=».NotificationService» android:label=»@string/app_name»> <intent-filter> <action android:name=»your.app.domain.NotificationService» /> <category android:name=»android.intent.category.DEFAULT» /> </intent-filter> </service> Ответ №1
Для этого вы можете использовать диспетчер аварийных сигналов.
Выполните следующие шаги:
1) Используйте будильник, чтобы создать будильник через X секунд.
Intent intent = new Intent(this, AlarmReceiver.class); intent.putExtra(«NotificationText», «some text»); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, ledgerId, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, ‘X seconds in milliseconds’, pendingIntent);
2) Используйте приемник AlarmBroadCast в своем приложении.
Объявить в файле манифеста:
<receiver android:name=».utils.AlarmReceiver»> <intent-filter> <action android:name=»android.media.action.DISPLAY_NOTIFICATION» /> <category android:name=»android.intent.category.DEFAULT» /> </intent-filter> </receiver>
3) В приемнике широковещательной передачи при приеме вы можете создать уведомление.
public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // create notification here } } Ответ №2
Вы можете проверить активные приложения, используя сервис и отобразить уведомление, если активность не запущена.