问题描述
我想在收到推送通知时启动倒数计时器。
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>
这篇关于在收到推送通知时在后台启动倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!