Starting countdown timer in background on receiving push notification

谁说我不能喝 提交于 2019-12-13 04:42:29

问题


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

I can receive the notification successfully.

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.

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();
}

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

Thanks in advance.


回答1:


No need for countdown timer.

Just follow the steps.

1) Create AlarmManagerBroadcastReceiver.java

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

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

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


来源:https://stackoverflow.com/questions/26485024/starting-countdown-timer-in-background-on-receiving-push-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!