计时器运行按钮单击但不在OnCreate()上运行

时间:2018-03-20 06:14:45

标签: android service timer

我正在尝试在activity的onCreate()方法上运行一个计时器,但它没有以这种方式运行。只需单击按钮即可运行计时器。我试图在onCreate()中调用runButtonClick()方法,但它没有运行。在我通过另一个活动的意图传递价值。

这是我的代码:

public class TimerActivity extends AppCompatActivity {



private static final String TAG = TimerActivity.class.getSimpleName();
private TimerService timerService;
private boolean serviceBound;
private Button timerButton;
String GetTime;
private TextView timerTextView;
String replaceString;

// Handler to update the UI every second when the timer is running
private final Handler mUpdateTimeHandler = new UIUpdateHandler(this);

// Message type for the handler
private final static int MSG_UPDATE_TIME = 0;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_timer);
    Intent in  = getIntent();
    GetTime = in.getStringExtra("order_name");
    replaceString = GetTime.replaceAll(" Minutes","");
    timerButton = findViewById(R.id.delivered_to_driver);
    timerTextView = findViewById(R.id.timer);
    timerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           // runButtonClick();
        }
    });
}



@Override
protected void onStart() {
    super.onStart();
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "Starting and binding service");
    }
    Intent i = new Intent(this, TimerService.class);
    i.putExtra("order_time",replaceString);
    startService(i);
    bindService(i, mConnection, 0);
}


@Override
protected void onStop() {
    super.onStop();
    updateUIStopRun();
    if (serviceBound) {
        // If a timer is active, foreground the service, otherwise kill the service
        if (timerService.isTimerRunning()) {
            timerService.foreground();
        }
        else {
            stopService(new Intent(this, TimerService.class));
        }
        // Unbind the service
        unbindService(mConnection);
        serviceBound = false;
    }
}


public void runButtonClick() {
    if (serviceBound && !timerService.isTimerRunning()) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "Starting timer");
        }
        timerService.startTimer();
        updateUIStartRun();
    }
    else if (serviceBound && timerService.isTimerRunning()) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "Stopping timer");
        }
        timerService.stopTimer();
        updateUIStopRun();
    }
}



/**

 * Updates the UI when a run starts

 */

private void updateUIStartRun() {

    mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME);

    //timerButton.setText(R.string.timer_stop_button);

}



/**

 * Updates the UI when a run stops

 */

private void updateUIStopRun() {

    mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);

    //timerButton.setText(R.string.timer_start_button);

}



/**

 * Updates the timer readout in the UI; the service must be bound

 */

private void updateUITimer() {

    if (serviceBound) {

        timerTextView.setText(timerService.elapsedTime());

    }

}



/**

 * Callback for service binding, passed to bindService()

 */

private ServiceConnection mConnection = new ServiceConnection() {



    @Override

    public void onServiceConnected(ComponentName className, IBinder service) {

        if (Log.isLoggable(TAG, Log.VERBOSE)) {

            Log.v(TAG, "Service bound");

        }

        TimerService.RunServiceBinder binder = (TimerService.RunServiceBinder) service;

        timerService = binder.getService();

        serviceBound = true;

        // Ensure the service is not in the foreground when bound

        timerService.background();

        // Update the UI if the service is already running the timer

        if (timerService.isTimerRunning()) {

            updateUIStartRun();

        }

    }



    @Override

    public void onServiceDisconnected(ComponentName name) {

        if (Log.isLoggable(TAG, Log.VERBOSE)) {

            Log.v(TAG, "Service disconnect");

        }

        serviceBound = false;

    }

};



/**

 * When the timer is running, use this handler to update

 * the UI every second to show timer progress

 */

static class UIUpdateHandler extends Handler {



    private final static int UPDATE_RATE_MS = 1000;

    private final WeakReference<TimerActivity> activity;



    UIUpdateHandler(TimerActivity activity) {

        this.activity = new WeakReference<>(activity);

    }



    @Override

    public void handleMessage(Message message) {

        if (MSG_UPDATE_TIME == message.what) {

            if (Log.isLoggable(TAG, Log.VERBOSE)) {

                Log.v(TAG, "updating time");

            }

            activity.get().updateUITimer();

            sendEmptyMessageDelayed(MSG_UPDATE_TIME, UPDATE_RATE_MS);

        }

    }

}



/**

 * Timer service tracks the start and end time of timer; service can be placed into the

 * foreground to prevent it being killed when the activity goes away

 */

public static class TimerService extends Service {



    private long totalTimeCountInMilliseconds;
    private long timeBlinkInMilliseconds;
    private CountDownTimer countDownTimer;
    private boolean blink;
    int time;




    private static final String TAG = TimerService.class.getSimpleName();
    String thisTime;


    // Start and end times in milliseconds

    private String startTime, endTime;



    // Is the service tracking time?

    private boolean isTimerRunning;



    // Foreground notification id

    private static final int NOTIFICATION_ID = 1;



    // Service binder

    private final IBinder serviceBinder = new RunServiceBinder();



    public class RunServiceBinder extends Binder {

        TimerService getService() {

            return TimerService.this;

        }

    }



    @Override

    public void onCreate() {

        if (Log.isLoggable(TAG, Log.VERBOSE)) {

            Log.v(TAG, "Creating service");

        }

        startTime = "0";

        endTime = "0";

        isTimerRunning = false;

    }



    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {

        if (Log.isLoggable(TAG, Log.VERBOSE)) {

            Log.v(TAG, "Starting service");

        }
        thisTime = intent.getStringExtra("order_time");

        return Service.START_STICKY;

    }



    @Override

    public IBinder onBind(Intent intent) {

        if (Log.isLoggable(TAG, Log.VERBOSE)) {

            Log.v(TAG, "Binding service");

        }

        return serviceBinder;

    }



    @Override

    public void onDestroy() {

        super.onDestroy();

        if (Log.isLoggable(TAG, Log.VERBOSE)) {

            Log.v(TAG, "Destroying service");

        }

    }



    /**

     * Starts the timer

     */

    public void startTimer() {

        if (!isTimerRunning) {


             if (thisTime != null) {
             time = Integer.parseInt(thisTime);
            } else
            Toast.makeText(TimerService.this, "",
                    Toast.LENGTH_LONG).show();

            totalTimeCountInMilliseconds = 60 * time * 1000;

            timeBlinkInMilliseconds = 30 * 1000;

            // startTime = System.currentTimeMillis();
             isTimerRunning = true;

             countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {

                @Override
                public void onTick(long leftTimeInMilliseconds) {
                    long seconds = leftTimeInMilliseconds / 1000;

                    if (leftTimeInMilliseconds < timeBlinkInMilliseconds) {
                        if (blink) {
                            // mTextField.setVisibility(View.VISIBLE);
                            // if blink is true, textview will be visible
                        } else {
                            //   mTextField.setVisibility(View.INVISIBLE);
                        }

                        blink = !blink;
                    }

                    String a = String.format("%02d", seconds / 60) + ":" + String.format("%02d", seconds % 60);
                    startTime = a;
                    isTimerRunning = true;

                }

                @Override
                public void onFinish() {
                    Toast.makeText(TimerService.this, "Finished", Toast.LENGTH_SHORT).show();
                }

            }.start();

        }

        else {

            Log.e(TAG, "startTimer request for an already running timer");

        }

    }



    /**

     * Stops the timer

     */

    public void stopTimer() {

        if (isTimerRunning) {

            endTime = String.valueOf(System.currentTimeMillis());

            isTimerRunning = false;

        }

        else {

            Log.e(TAG, "stopTimer request for a timer that isn't running");

        }

    }



    /**

     * @return whether the timer is running

     */

    public boolean isTimerRunning() {

        return isTimerRunning;

    }



    /**

     * Returns the  elapsed time

     *

     * @return the elapsed time in seconds

     */

    public String elapsedTime() {

        // If the timer is running, the end time will be zero

        return startTime;
    }

     /*Integer.parseInt(endTime) > Integer.parseInt(startTime) ?

                (Integer.parseInt(endTime) - Integer.parseInt(startTime)) / 1000 :

                (System.currentTimeMillis() - Integer.parseInt(startTime)) / 1000;*//*

    }



    /**

     * Place the service into the foreground

     */

    public void foreground() {

        startForeground(NOTIFICATION_ID, createNotification());

    }



    /**

     * Return the service to the background

     */

    public void background() {

        stopForeground(true);

    }



    /**

     * Creates a notification for placing the service into the foreground

     *

     * @return a notification for interacting with the service when in the foreground

     */

    private Notification createNotification() {

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)

                .setContentTitle("Timer Active")

                .setContentText("Tap to return to the timer")

                .setSmallIcon(R.mipmap.ic_launcher);



        Intent resultIntent = new Intent(this, TimerActivity.class);

        PendingIntent resultPendingIntent =

                PendingIntent.getActivity(this, 0, resultIntent,

                        PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentIntent(resultPendingIntent);



        return builder.build();

    }

}



}

我不明白我的问题是什么......你的帮助将不胜感激。谢谢你...

1 个答案:

答案 0 :(得分:0)

在onStart()方法中调用startService(),启动服务后serviceBound将为true。所以在oncreate()方法中,如果runButtonClick中的条件不会执行。