在收到推送通知时在后台启动倒数计时器

编程入门 行业动态 更新时间:2024-10-07 08:23:35
本文介绍了在收到推送通知时在后台启动倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在收到推送通知时启动倒数计时器。

I want to start a countdown timer when a push notification is received.

我可以成功接收通知。

现在我想问一下,是否可以启动倒数计时器当接收到通知并且我的应用程序处于后台还是前台时,在BroadcastReceiver的onReceive中?

Now I want to ask, is it possible to start countdown timer in onReceive of BroadcastReceiver when a notification is received and my application is in background or foreground?

我应该说,无论应用程序是否在前台,计时器都应启动。 当计时器结束时,它应该向服务器发送一些数据。 而且我需要在倒计时期间应用程序进入前台时在文本视图中显示剩余时间。

Simply, I should say that the timer should start whether the app is in foreground or not. And when the timer is finished it should send some data to server. And I need to show the remaining time in a text view as soon as app comes to foreground during the countdown.

我要添加一些代码,请帮帮我。

I am adding some code, please help me out.

这是启动计时器的代码,此函数在onReceive中调用。

This is code to start the timer and this function is called in onReceive.

void startOrderCountDown() { CountDownTimer orderCountDown = new CountDownTimer(40000, 1000) { public void onTick(long millisUntilFinished) { Constant.remainingTimeOfOrder = millisUntilFinished / 1000; Log.v("Timer", "Time left: " + millisUntilFinished / 1000); } public void onFinish() { new Thread(new Runnable() { @Override public void run() { String dr_id = myPreferences.getDRIVERID(); String res = new ServerConnection() .updateOrderMissedRejected( Constant.UPDATE_MISSED_REJECTED_ORDER, dr_id, "", "0"); Log.e("Timer", "finished..." + res); } }).start(); } }; orderCountDown.start(); }

但是,当通知到达时,它仅在屏幕上显示剩余时间:39 logcat。

But When the notification arrives, it just prints "Time left: 39" in logcat.

提前感谢。

推荐答案

无需倒数计时计时器。

只需执行以下步骤。

1)创建AlarmManagerBroadcastReceiver.java

1) Create AlarmManagerBroadcastReceiver.java

public class AlarmManagerBroadcastReceiver extends BroadcastReceiver implements IjoomerSharedPreferences { @Override public void onReceive(Context context, Intent intent) { // Call your sever task. } }

2)设置从收到警报的当前时间开始

2) set alarm from current time when you receive push notification.

long INTERVAL = 40000; AlarmManager am=(AlarmManager)getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(this, AlarmManagerBroadcastReceiver.class); PendingIntent pi = PendingIntent.getBroadcast(this, 1010, intent, 0); try{ am.cancel(pi); }catch (Exception e){ } am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + INTERVAL, pi);

2)Manifest.xml

2) Manifest.xml

<receiver android:process=":remote" android:name="com.XXX.ZZZZ.AlarmManagerBroadcastReceiver"></receiver>

更多推荐

在收到推送通知时在后台启动倒数计时器

本文发布于:2023-11-05 10:24:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560577.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计时器   倒数   后台   通知

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!