按下暂停按钮并且不在后台运行时,计时器再次重置

时间:2018-07-21 06:11:49

标签: android android-service

我为此创建了一个up count counter,因为我正在运行一个后台服务,因此即使该应用被杀死,计数器也将在后台运行。但是当应用被终止时,计数器从头开始计数,当我按下暂停按钮并再次播放时,计数器又从头开始像以前一样开始计数。以下是我的服务和活动的代码。请帮帮我。

package io.funswitch.gymmon.Services;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;

import java.util.Locale;

import static io.funswitch.gymmon.Fragments.CheckOutFragment.running;

    public class TimerService  extends Service {
    private Intent intent;
    public static final String BROADCAST_ACTION = "com.javacodegeeks.android.androidtimerexample.MainActivity";

    private Handler handler = new Handler();
    private long initial_time;
    long timeInMilliseconds = 0L;

    @Override
    public void onCreate() {
        super.onCreate();
        initial_time = SystemClock.uptimeMillis();
        intent = new Intent(BROADCAST_ACTION);
        handler.removeCallbacks(sendUpdatesToUI);
        handler.postDelayed(sendUpdatesToUI, 1000); // 1 second

    }

    private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            DisplayLoggingInfo();
            handler.postDelayed(this, 1000); // 1 seconds
        }
    };

    private void DisplayLoggingInfo() {

        timeInMilliseconds = SystemClock.uptimeMillis() - initial_time;

        int timer = (int) timeInMilliseconds / 1000;
        intent.putExtra("time", timer);
        sendBroadcast(intent);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(sendUpdatesToUI);

    }



    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }


}

CheckoutActivity.java

 package io.funswitch.gymmon.activities;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Locale;

import io.funswitch.gymmon.Fragments.CheckOutFragment;
import io.funswitch.gymmon.R;
import io.funswitch.gymmon.Services.TimerService;

public class CheckOutActivity extends AppCompatActivity implements View.OnClickListener {
    private Boolean exit = false;
    ImageView play_pause, play;
    private int milliseconds;
    public boolean running;
    TextView timer;
    int time;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_out);
        play_pause = findViewById(R.id.pause_play);
        timer = findViewById(R.id.timer);
        play = findViewById(R.id.play);
        play_pause.setOnClickListener(this);
        play.setOnClickListener(this);
        time = getIntent().getIntExtra("time", 0);

//        if (savedInstanceState == null) {
//            FragmentManager fragmentManager = getSupportFragmentManager();
//            CheckOutFragment stepsDetailActivityFragment = new CheckOutFragment();
//            fragmentManager.beginTransaction()
//                    .add(R.id.check_out_frame, stepsDetailActivityFragment)
//                    .commit();
//
//        }
//        int time = getIntent().getIntExtra("time", 0);
//        Bundle bundle = new Bundle();
//        bundle.putInt("time", time);
//// set Fragmentclass Arguments
//        CheckOutFragment fragobj = new CheckOutFragment();
//        fragobj.setArguments(bundle);

    }

    @Override
    public void onClick(View v) {
        if (v == play_pause) {
            if (running) {
//                SharedPreferences sharedPreferences = getSharedPreferences("myPref", 0);
//                sharedPreferences.getInt("tim", 0);
                stopService(new Intent(CheckOutActivity.this, TimerService.class));
                running = false;
                play_pause.setImageResource(R.drawable.ic_play_button);
            } else {
                SharedPreferences sharedPreferences = getSharedPreferences("myPref", 0);
                sharedPreferences.getInt("timee", 0);
                running = true;
                play_pause.setImageResource(R.drawable.ic_pause);
                registerReceiver(broadcastReceiver, new IntentFilter(TimerService.BROADCAST_ACTION));
                startService(new Intent(CheckOutActivity.this, TimerService.class));

            }
        }
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            runTimer(intent);
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        running = true;
        Intent intent = new Intent(CheckOutActivity.this, TimerService.class);
        startService(intent);
        registerReceiver(broadcastReceiver, new IntentFilter(TimerService.BROADCAST_ACTION));
//        running = false;
//        stopService(new Intent(CheckOutActivity.this, TimerService.class));
//        unregisterReceiver(broadcastReceiver);


    }


    public void runTimer(Intent intent) {
        time = intent.getIntExtra("time", 0);
        int hour = time / 3600;
        int mins = time / 60;
        int secs = time % 60;
        String timerTask = String.format(Locale.US, "%02d:%02d:%02d", hour, mins, secs);
        timer.setText(timerTask);
        SharedPreferences sharedPreferences = getSharedPreferences("myPref", 0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("tim", time);
        editor.apply();
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (exit) {
            finish(); // finish activity
        } else {
            Toast.makeText(this, "Press Back again to Exit.",
                    Toast.LENGTH_SHORT).show();
            exit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit = false;
                }
            }, 2 * 1000);

        }
    }


    @Override
    protected void onResume() {
        super.onResume();

//        Intent intent = new Intent(CheckOutActivity.this, TimerService.class);
//        startService(intent);
//        registerReceiver(broadcastReceiver, new IntentFilter(TimerService.BROADCAST_ACTION));
    }


}

我还试图将值保存在sharedPreferences中,并在单击播放按钮时检索到它,但是它不起作用。请帮帮我。

1 个答案:

答案 0 :(得分:0)

您需要将计数器保存在共享偏好中,并在服务重启时恢复计数器值

在您的CheckOutActivity

    @Override
            protected void onStop() {
        // save counter(time) value to sharedprefrences 
        running = false;
        stopService(intent)
        unregisterReceiver(broadcastReceiver);
        }

        int time;

 public void runTimer(Intent intent){
        time = intent.getIntExtra("time", 0);
        int hour = time/3600;
        int mins = time / 60;
        int secs = time % 60;
        timer.setText(String.format(Locale.US,"%02d:%02d:%02d", hour, mins, secs));
    }

TimerService

int counter;
     @Override
        public void onCreate() {
            super.onCreate();
        //set counter to value from sharedprefrences 
    }

private void DisplayLoggingInfo() {

        timeInMilliseconds = SystemClock.uptimeMillis() - initial_time;

        int timer = (int) timeInMilliseconds / 1000;
        intent.putExtra("time", timer+counter);
        sendBroadcast(intent);

    }