简体   繁体   中英

CountdownTimer Service restarting when activity screen is re-opened

I'm trying to make a countdown timer screen on Android that will continue to count down if you back out of the app or go to different screens in the app or whatever. I'm running it as a Service but I'm still getting the problem of it starting over when I re-open the activity. Any help would be great. Here's my code.

Service Class

import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.annotation.Nullable; 
import android.support.v4.content.LocalBroadcastManager;




public class CountdownService extends Service{
public static final String
    ACTION_LOCATION_BROADCAST = CountdownService.class.getName() + "LocationBroadcast";

@Override
public void onCreate() {
super.onCreate();
new CountDownTimer(360000, 60000) {
    public void onTick(long millisUntilFinished) {
        int timeLeftInt = (int) Math.ceil((double) millisUntilFinished / 60000);    //Whole number of minutes left, ceiling
        sendBroadcastMessage(timeLeftInt);
        if(timeLeftInt == 5){
            Notify("Not Done");
        }

    }

    public void onFinish() {
        sendBroadcastMessage(0);
        Notify("done");

    }
}.start();

}

private void sendBroadcastMessage(int timeSent) {
    Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
    intent.putExtra("timeSent", timeSent);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

  }



@Override
public IBinder onBind(Intent intent) {
return null;
}
private void Notify(String doneness){

NotificationManager notificationManager = (NotificationManager)
        getSystemService(NOTIFICATION_SERVICE);

Intent intent = new Intent(this, Map.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
if(doneness.equals("done")) {
    Notification n = new Notification.Builder(this)
            .setContentTitle("Time to leave!")
            .setContentText("Your PrePark spot has expired, time to go home!")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pIntent)
            .setAutoCancel(true)
            .build();

    notificationManager.notify(0, n);
}

else{
    Notification n = new Notification.Builder(this)
            .setContentTitle("Ya got 5 minutes left in your PrePark spot!")
            .setContentText("Better get going soon here")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pIntent)
            .setAutoCancel(true)
            .build();

    notificationManager.notify(0, n);
}
}

Main Activity

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.os.Bundle;
import android.widget.TextView;

public class Countdown extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countdown);
LocalBroadcastManager.getInstance(this).registerReceiver(
        new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                TextView textView= findViewById(R.id.t1);
                int timeLeft = intent.getIntExtra("timeSent", 0);
                if(timeLeft>0) {
                    textView.setText("You have " + timeLeft + " minutes left");
                }
                else{
                    textView.setText("Y'all outta time, see ya again soon!");
                }
            }
        }, new IntentFilter(CountdownService.ACTION_LOCATION_BROADCAST)
);

}
@Override
protected void onResume() {
super.onResume();
startService(new Intent(this, CountdownService.class));
}

@Override
protected void onPause() {
super.onPause();
stopService(new Intent(this, CountdownService.class));
}
}

XML for main activity

<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center">

<TextView
android:id="@+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerInParent="true"
android:textSize="32sp"

/>


</RelativeLayout>

可能发生这种情况是因为您要在onResume()中启动倒计时服务,而在onPause()中停止该服务,并且还在服务的onCreate()方法中通过倒数计时器创建新实例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM