如何管理服务中的计时器以在后台运行

时间:2018-03-14 06:02:35

标签: android android-studio service timer

我正在尝试实现一项服务,当我选择一个时间时,计时器启动并在后台运行。事情很好。但是当我选择另一个时间时,计时器会相互重叠。我希望我的应用程序以不同的服务运行不同时间的方式工作。此外,当我杀死应用程序并重新打开它时,我会在所有服务中获得剩余时间。

但是我的数据来自Web服务,此Web服务包含一个包含时间的字段。当我点击时间时,应该开始上述概念。

我已将我的代码实现为,

BroadCastService.java

public class BroadCastService extends Service {

private long totalTimeCountInMilliseconds;
private long timeBlinkInMilliseconds;
private CountDownTimer countDownTimer;
private boolean blink;
String getTime;

public static final String COUNTDOWN_BR = "project.uop.assignment8";
Intent bi = new Intent(COUNTDOWN_BR);

public BroadCastService() {
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //return super.onStartCommand(intent, flags, startId);
    getTime = intent.getStringExtra("time");
    setTimer();
    startTimer();
    Log.i("madhura","madhura");
    return START_STICKY;
}

@Override
public void onCreate() {
    super.onCreate();

}

private void setTimer() {
    int time = 0;
   //if (getTime.equals("")) {
        time = Integer.parseInt(getTime);
  //  } else
       /* Toast.makeText(BroadCastService.this, "Please Enter Minutes...",
                Toast.LENGTH_LONG).show();*/

    totalTimeCountInMilliseconds = 60 * time * 1000;

    timeBlinkInMilliseconds = 30 * 1000;
}



private void startTimer() {
    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);
            bi.putExtra("countdown", a);
            sendBroadcast(bi);

        }

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

    }.start();
}

}

和我的TimerActivity.class

public class TimerActivity extends AppCompatActivity {

TextView mTextField;
TextView hotel;
private long totalTimeCountInMilliseconds;
private long timeBlinkInMilliseconds;
private CountDownTimer countDownTimer;
private boolean blink;
String getTime;
SessionManager sessionManager;
Toolbar toolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_timer);
    InitializeToolbar();
    Intent in = getIntent();
    getTime = in.getStringExtra("time");
    Intent intent = new Intent(this,BroadCastService.class);
    intent.putExtra("time",getTime);
    this.startService(intent);
    sessionManager = new SessionManager(this);
    hotel = findViewById(R.id.textView);
    hotel.setText(sessionManager.getUserName());
    Log.i("started", "Started service");
    mTextField = findViewById(R.id.timer);
}

public void InitializeToolbar(){
    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setTitle("Order Notification");
}



private BroadcastReceiver br = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        updateGUI(intent); // or whatever method used to update your GUI fields
    }
};

@Override
public void onResume() {
    super.onResume();
    registerReceiver(br, new IntentFilter(BroadCastService.COUNTDOWN_BR));
    Log.i("efgh", "Registered broacast receiver");
}

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(br);
    Log.i("abcd", "Unregistered broadcast receiver");
}

@Override
public void onStop() {
    try {
        unregisterReceiver(br);
    } catch (Exception e) {
        // Receiver was probably already stopped in onPause()
    }
    super.onStop();
}
@Override
public void onDestroy() {
    stopService(new Intent(this, BroadCastService.class));
    Log.i("Stopped", "Stopped service");
    super.onDestroy();
}

private void updateGUI(Intent intent) {
    if (intent.getExtras() != null) {
        String millisUntilFinished = intent.getStringExtra("countdown");
        mTextField.setText(millisUntilFinished);
    }
}

}

提前感谢。

1 个答案:

答案 0 :(得分:0)

使用Handler@Overide方法Handler#handleMessage(Message msg)

请参阅:https://gist.github.com/mjohnsullivan/403149218ecb480e7759