Android 按暂停按钮后计时器再次重置,但不在后台运行

Android 按暂停按钮后计时器再次重置,但不在后台运行,android,android-service,Android,Android Service,我已经创建了一个递增计数计数器,因为我正在运行后台服务,因此即使在应用程序被终止后,计数器也将在后台运行。但当应用程序被终止时,计数器从一开始就开始计数,当我按下暂停按钮并再次播放时,计数器从一开始就再次开始计数。以下是我的服务和活动代码。请帮帮我 package io.funswitch.gymmon.Services; import android.app.Service; import android.content.Intent; import android.os.Handler;

我已经创建了一个
递增计数计数器
,因为我正在运行后台服务,因此即使在应用程序被终止后,计数器也将在后台运行。但当应用程序被终止时,计数器从一开始就开始计数,当我按下暂停按钮并再次播放时,计数器从一开始就再次开始计数。以下是我的服务和活动代码。请帮帮我

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


}

我还尝试在SharedReferences中保存值,并在“播放”按钮单击时检索它,但它不起作用。请帮助我。

您需要将计数器保存在SharedReferences中,并在服务重新启动时还原计数器值

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


}
在您的
签出活动中

    @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);

    }

我对SharedPreferences和services很陌生,你能告诉我几行代码吗?这样我就可以继续了。在将初始时间值设置为sharedPref后,我应该在哪里检索这些值?我保存在onStop中的pref也应该在哪里检索?在
TimerService onCreate
中检查我的答案