Таймменеджер не сбрасывается при завершении или при уничтожении?JAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Таймменеджер не сбрасывается при завершении или при уничтожении?

Сообщение Anonymous »

УПРАВЛЕНИЕ ВРЕМЕНЕМ:

Код: Выделить всё

package com.example.datvexemphim.Activities;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.CountDownTimer;

public class TimerManager {
private static final String PREFS_NAME = "TimerPrefs";
private static final String KEY_TIME_LEFT = "timeLeft";
private static CountDownTimer countDownTimer;
private static long timeLeftInMillis;

public interface TimerCallback {
void onTick(long millisUntilFinished);
void onFinish();
}

public static void startTimer(final Context context, final TimerCallback callback) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
timeLeftInMillis = prefs.getLong(KEY_TIME_LEFT, 10 * 60 * 1000); // Default to 10 minutes

countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
@Override
public void onTick(long millisUntilFinished) {
callback.onTick(millisUntilFinished);
saveTimeLeft(context, millisUntilFinished);
timeLeftInMillis = millisUntilFinished;
}

@Override
public void onFinish() {
callback.onFinish();
clearTimeLeft(context);
}
}.start();
}

public static void stopTimer() {
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
}

public static void saveTimeLeft(Context context, long timeLeftInMillis) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putLong(KEY_TIME_LEFT, timeLeftInMillis);
editor.apply();
}

public static void clearTimeLeft(Context context) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove(KEY_TIME_LEFT);
editor.apply();
}

public static void loadTimeLeft(Context context) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
timeLeftInMillis = prefs.getLong(KEY_TIME_LEFT, 10 * 60 * 1000); // Default to 10 minutes
saveTimeLeft(context, timeLeftInMillis);
}

public static void setTimeLeft(Context context, long timeInMillis) {
timeLeftInMillis = timeInMillis;
saveTimeLeft(context, timeInMillis);
}
public static void resetTimer(Context context) {
saveTimeLeft(context, 10 * 60 * 1000);  // Reset to 10 minutes
}
}
ВНУТРЕННЯЯ ДЕЯТЕЛЬНОСТЬ:

Код: Выделить всё

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Thông báo");
builder.setMessage("Bạn có 10 phút để đặt vé và thanh toán, nếu trong khoảng thời gian đó bạn không thanh toán, ghế bạn chọn sẽ bị hủy.");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(insideActivity.this, SeatActivity.class);
Bundle bundle = new Bundle();
String[] time = timesccurrent.split("-");
String timestart = time[0].trim();
bundle.putInt("movieid", movieid);
bundle.putInt("roomcurrent", roomcurrent);
bundle.putString("datecurrent", datecurrent);
bundle.putString("citycurrent", citycurrent);
bundle.putString("theatercurrent", theatercurrent);
bundle.putString("timesccurrent", timesccurrent);
bundle.putString("timestart", timestart);
intent.putExtra("bundle2", bundle);
startActivity(intent);
// lay ngaygio hien tai , sinh mattmonan, mattve
LocalDateTime currentDateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
String formattedDateTime = currentDateTime.format(formatter);
MATTMONAN ="F"+String.valueOf(userid)+formattedDateTime;
MATTVE ="T"+String.valueOf(userid)+formattedDateTime;
dBhelper.insertHoadon(userid,MATTMONAN,MATTVE);
//TimerManager.setTimeLeft(insideActivity.this, 10 * 60 * 1000);
}
});
builder.setNegativeButton("Hủy", null);
builder.show();
}
СИДЕНЬЯ ДЕЯТЕЛЬНОСТЬ:

Код: Выделить всё

 protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seat);
Log.d(TAG,"onCreate");
// anh xa
dBhelper = new DBhelper(this);
txt_datemovie = findViewById(R.id.txt_datemovieseat);
txt_timemovie = findViewById(R.id.txt_timemovieseat);
txt_namemovieseat = findViewById(R.id.txt_namemovieseat);
txt_chair = findViewById(R.id.txt_chair);
txt_money = findViewById(R.id.txt_money);
txt_theaterroomseat = findViewById(R.id.txt_theaterroomseat);
// dong ho
countdownTimer = findViewById(R.id.countdownTimer);
//startTimer( 10 * 60 * 1000); // 10 minutes in milliseconds
// mo intent lay du lieu
Intent intent = getIntent();
bundle =  intent.getBundleExtra("bundle2");
// set du lieu cho cac truong
txt_datemovie.setText(bundle.getString("datecurrent"));
txt_timemovie.setText(bundle.getString("timesccurrent"));
txt_namemovieseat.setText(dBhelper.getMovieName(bundle.getInt("movieid")));
txt_theaterroomseat.setText(bundle.getString("theatercurrent")+ " Room "+ String.valueOf(bundle.getInt("roomcurrent")));
//
timesccurrent = bundle.getString("timesccurrent");
movieid = bundle.getInt("movieid");
roomcurrent = bundle.getInt("roomcurrent");
theatercurrent = bundle.getString("theatercurrent");
datecurrent = bundle.getString("datecurrent");
timestart = bundle.getString("timestart");
showid = dBhelper.getShowid(movieid,roomcurrent,theatercurrent,datecurrent,timestart);
// seat
mylist = new ArrayList();

List listghe= dBhelper.getGhe(showid,roomcurrent);
List listprice = dBhelper.getPrice(showid,roomcurrent);
for (int i = 0; i < listghe.size();  i++) {
mylist.add(new Seat(listghe.get(i), listprice.get(i)));
}
seatAdapter = new SeatAdapter((Activity) this,R.layout.seat, mylist,showid,roomcurrent,MATTVE);
gv = findViewById(R.id.gv);
gv.setAdapter(seatAdapter);
// btn_next
btn_finishPaymentButton1 = findViewById(R.id.btn_finishPaymentButton1);
btn_finishPaymentButton1.setEnabled(false); // Disable button initially
btn_finishPaymentButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(SeatActivity.this, FoodActivity.class );
Bundle bundle = new Bundle();
bundle.putInt("movieid", movieid);
bundle.putInt("roomcurrent", roomcurrent);
bundle.putString("datecurrent", datecurrent);
bundle.putString("theatercurrent", theatercurrent);
bundle.putString("timesccurrent", timesccurrent);
bundle.putString("timestart", timestart);
intent.putExtra("bundle3", bundle);
intent.putExtra("remainingTime",timeLeftInMillis);
startActivity(intent);

}
});
//btn_back
btn_back = findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dBhelper.deleteHoadon(MATTMONAN,MATTVE);
finish();
}
});
//TimerManager.resetTimer(this);
TimerManager.loadTimeLeft(this);
startCountdown();

}
private void startCountdown() {
TimerManager.startTimer(this, new TimerManager.TimerCallback() {
@Override
public void onTick(long millisUntilFinished) {
String timeLeftFormatted = String.format("%02d:%02d",
millisUntilFinished / 1000 / 60,
millisUntilFinished / 1000 % 60);
countdownTimer.setText(timeLeftFormatted);
}

@Override
public void onFinish() {
cancelBooking();
}
});
}
private void cancelBooking() {
// Hủy MATTVE và MATTMONAN, đặt tất cả ghế đã chọn về trống
dBhelper.deleteRecordsByMATTMONAN(MATTMONAN);
dBhelper.deleteRecordsByMATTVE(MATTVE);
dBhelper.deleteHoadon1(MATTMONAN);
dBhelper.UpdateGHECHUADAT(dBhelper.getTicketidfromMATTVE(MATTVE));
TimerManager.stopTimer();
// Xóa trạng thái thời gian còn lại
TimerManager.clearTimeLeft(this);
//TimerManager.resetTimer(this); // Reset timer to 10 minutes
// Điều hướng trở lại MainActivity
Intent intent = new Intent(SeatActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}

@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG,"onDestroy");
dBhelper.deleteRecordsByMATTMONAN(MATTMONAN);
dBhelper.deleteRecordsByMATTVE(MATTVE);
dBhelper.deleteHoadon1(MATTMONAN);
dBhelper.UpdateGHECHUADAT(dBhelper.getTicketidfromMATTVE(MATTVE));
TimerManager.stopTimer();
TimerManager.clearTimeLeft(this);
// Xóa trạng thái thời gian còn lại
//TimerManager.resetTimer(this); // Reset timer to 10 minutes

}
@Override
public void onBackPressed() {
super.onBackPressed();
dBhelper.deleteRecordsByMATTMONAN(MATTMONAN);
dBhelper.deleteRecordsByMATTVE(MATTVE);
dBhelper.deleteHoadon1(MATTMONAN);
dBhelper.updateTINHTRANGToTrong(dBhelper.getTicketidfromMATTVE(MATTVE));
//dBhelper.UpdateGHECHUADAT(dBhelper.getTicketidfromMATTVE(MATTVE));
TimerManager.stopTimer();
// Xóa trạng thái thời gian còn lại
TimerManager.clearTimeLeft(this);
//TimerManager.resetTimer(this);  // Reset timer to 10 minutes
finish();
}

ПРОДАЖА:

Код: Выделить всё

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
Log.d(TAG,"onCreate");
dBhelper = new DBhelper(this);
// anh xa id cho cac thanh phan
txt_datetimefood = findViewById(R.id.txt_datetimefood);
txt_theaterroom = findViewById(R.id.txt_theaterroom);
txt_namemoviefood = findViewById(R.id.txt_namemoviefood);
txt_subtotal = findViewById(R.id.txt_subtotal);
countdownTimer = findViewById(R.id.countdownTimer);

//combo
Intent intent = getIntent();
bundle =  intent.getBundleExtra("bundle3");
txt_datetimefood.setText(bundle.getString("datecurrent")+" "+bundle.getString("timesccurrent"));
txt_theaterroom.setText(bundle.getString("theatercurrent")+"- Room"+bundle.getInt("roomcurrent"));
txt_namemoviefood.setText(dBhelper.getMovieName(bundle.getInt("movieid")));
// lay du lieu tu bundle
timesccurrent = bundle.getString("timesccurrent");
movieid = bundle.getInt("movieid");
roomcurrent = bundle.getInt("roomcurrent");
theatercurrent = bundle.getString("theatercurrent");
datecurrent = bundle.getString("datecurrent");

// gio
//timeLeftInMillis = getIntent().getLongExtra("remainingTime", 10 * 60 * 1000); // Mặc định 10 phút
//startTimer(timeLeftInMillis);

mylist = new ArrayList();
List listname = dBhelper.getNameFood();
List listprice = dBhelper.getPriceFood();
List listimage = dBhelper.getImageFood();
for (int i = 0; i < listimage.size();  i++) {
mylist.add(new Combo(listimage.get(i),listname.get(i),listprice.get(i)));
}
comboAdapter = new ComboAdapter(this , R.layout.combo, mylist,MATTMONAN);
comboAdapter.setOnQuantityChangeListener(new ComboAdapter.OnQuantityChangeListener() {
@Override
public void onQuantityChanged() {
updateSubtotal();
}
});
foodListView = findViewById(R.id.foodListView);
foodListView.setAdapter(comboAdapter);

btn_finishPaymentButton2 = findViewById(R.id.btn_finishPaymentButton2);
btn_finishPaymentButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//countDownTimer.cancel();
Intent intent = new Intent(FoodActivity.this, Waitforpay.class );
Bundle bundle = new Bundle();
bundle.putInt("movieid", movieid);
bundle.putInt("roomcurrent", roomcurrent);
bundle.putString("datecurrent", datecurrent);
bundle.putString("theatercurrent", theatercurrent);
bundle.putString("timesccurrent", timesccurrent);
intent.putExtra("remainingTime",timeLeftInMillis);
intent.putExtra("bundle4",bundle);
startActivity(intent);
//finish();

}
});
//TimerManager.resetTimer(this);
TimerManager.loadTimeLeft(this);
startCountdown();
}
private void startCountdown() {
TimerManager.startTimer(this, new TimerManager.TimerCallback() {
@Override
public void onTick(long millisUntilFinished) {
String timeLeftFormatted = String.format("%02d:%02d",
millisUntilFinished / 1000 / 60,
millisUntilFinished / 1000 % 60);
countdownTimer.setText(timeLeftFormatted);
}

@Override
public void onFinish() {
cancelBooking();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG,"onDestroy");
dBhelper.deleteRecordsByMATTMONAN(MATTMONAN);
dBhelper.deleteRecordsByMATTVE(MATTVE);
dBhelper.deleteHoadon1(MATTMONAN);
dBhelper.UpdateGHECHUADAT(dBhelper.getTicketidfromMATTVE(MATTVE));
TimerManager.stopTimer();
// Xóa trạng thái thời gian còn lại
TimerManager.clearTimeLeft(this);
//TimerManager.resetTimer(this); // Reset timer to 10 minutes
}
@Override
public void onBackPressed() {
super.onBackPressed();
TimerManager.loadTimeLeft(this);
startCountdown();
}

private void updateSubtotal() {
subtotal = 0;
for (Combo combo : mylist) {
subtotal += combo.getComboprice() * combo.getQuantity();
}
txt_subtotal.setText(subtotal + "đ");
}
private void cancelBooking() {
// Hủy MATTVE và MATTMONAN, đặt tất cả ghế đã chọn về trống
dBhelper.deleteRecordsByMATTMONAN(MATTMONAN);
dBhelper.deleteRecordsByMATTVE(MATTVE);
dBhelper.deleteHoadon1(MATTMONAN);
TimerManager.stopTimer();
TimerManager.clearTimeLeft(this);
// Xóa trạng thái thời gian còn lại
//TimerManager.resetTimer(this);  // Reset timer to 10 minutes
// Điều hướng trở lại MainActivity
Intent intent = new Intent(FoodActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
Действие ожидания оплаты:

Код: Выделить всё

`@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_waitforpay);
//anh xa cac thanh phan
txt_namemovieend = findViewById(R.id.txt_namemovieend);
txt_theaterroompayment = findViewById(R.id.txt_theaterroompayment);
txt_datetimepayment = findViewById(R.id.txt_datetimepayment);
txt_ticket = findViewById(R.id.txt_ticket);
txt_totalprice = findViewById(R.id.txt_totalprice);
txt_totalpriceticket = findViewById(R.id.txt_totalpriceticket);
lv_fooditemwfp = findViewById(R.id.lv_fooditemwfp);
// xu li cum thanh phan thong tin rap va suat chieu
dBhelper = new DBhelper(this);
Intent intent = getIntent();
bundle = intent.getBundleExtra("bundle4");
txt_namemovieend.setText(dBhelper.getMovieName(bundle.getInt("movieid")));
txt_theaterroompayment.setText(bundle.getString("theatercurrent") + "- Room" + bundle.getInt("roomcurrent"));
txt_datetimepayment.setText(bundle.getString("datecurrent") + " " + bundle.getString("timesccurrent"));
roomcurrent = bundle.getInt("roomcurrent");
List listgheid = dBhelper.getGheidfromTTve(MATTVE);
txt_ticket.setText(String.valueOf(slghe) + " x " + "Seat : " + seats);
//int price = dBhelper.getTongtien(MATTVE);
int ticketprice = totalPrice;
txt_totalpriceticket.setText(String.valueOf(ticketprice) + "đ");
int foodprice = subtotal;
finaltongtien = subtotal + totalPrice;
txt_totalprice.setText(String.valueOf(finaltongtien) + "đ");
// xu li listview
mylist = new ArrayList();
List listfoodid = dBhelper.getFoodidfrom(MATTMONAN);
List listsl = dBhelper.getSLfromTTMONAN(MATTMONAN);
List listfoodname = dBhelper.getNamefromMONAN(listfoodid);
List listprice = dBhelper.getPricefromMONAN(listfoodid);
for (int i = 0; i < listfoodname.size();  i++) {
mylist.add(new Foodpay(listfoodname.get(i), listprice.get(i), listsl.get(i)));
}
// set kt thay doi listview boi sl item
ViewGroup.LayoutParams params = lv_fooditemwfp.getLayoutParams();
params.height = (int) (listfoodname.size() * 62 *((lv_fooditemwfp.getResources().getDisplayMetrics().density)));
lv_fooditemwfp.setLayoutParams(params);
foodAdapter = new FoodAdapter(Waitforpay.this, R.layout.list_item_food_waitforpay, mylist);
lv_fooditemwfp.setAdapter(foodAdapter);

countdownTimer = findViewById(R.id.countdownTimer);
btn_finishPaymentButton3 = findViewById(R.id.btn_finishPaymentButton3);
btn_finishPaymentButton3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showPaymentDialog();
}
});
TimerManager.loadTimeLeft(this);
startCountdown();
}
private void startCountdown() {
TimerManager.startTimer(this, new TimerManager.TimerCallback() {
@Override
public void onTick(long millisUntilFinished) {
String timeLeftFormatted = String.format("%02d:%02d",
millisUntilFinished / 1000 / 60,
millisUntilFinished / 1000 % 60);
countdownTimer.setText(timeLeftFormatted);
}

@Override
public void onFinish() {
cancelBooking();
}
});
}
private void showPaymentDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Thông báo");
builder.setMessage("Bạn đã đặt vé thành công");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// cap nhat lai trang thai hoa don
dBhelper.UpdateHoadon(MATTMONAN, finaltongtien);
// cap nhat trang thai thanh toan mon an va thanh toan ve
dBhelper.UpdateTTVE(MATTVE);
dBhelper.UpdateTTMONAN(MATTMONAN);
dBhelper.UpdateGHE(dBhelper.getTicketidfromMATTVE(MATTVE));
completePayment();
}
});
builder.setCancelable(false);
builder.show();
}

private void completePayment() {
TimerManager.stopTimer();
TimerManager.clearTimeLeft(this);
//TimerManager.resetTimer(this);
Intent intent = new Intent(Waitforpay.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
}

private void cancelBooking() {
// Hủy MATTVE và MATTMONAN, đặt tất cả ghế đã chọn về trống
dBhelper.deleteRecordsByMATTMONAN(MATTMONAN);
dBhelper.deleteRecordsByMATTVE(MATTVE);
dBhelper.deleteHoadon1(MATTMONAN);
dBhelper.UpdateGHECHUADAT(dBhelper.getTicketidfromMATTVE(MATTVE));
TimerManager.stopTimer();
TimerManager.clearTimeLeft(this);
//TimerManager.resetTimer(this);
// Điều hướng trở lại MainActivity
Intent intent = new Intent(Waitforpay.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}

@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG,"onDestroy");
dBhelper.deleteRecordsByMATTMONAN(MATTMONAN);
dBhelper.deleteRecordsByMATTVE(MATTVE);
dBhelper.deleteHoadon1(MATTMONAN);
dBhelper.UpdateGHECHUADAT(dBhelper.getTicketidfromMATTVE(MATTVE));
TimerManager.stopTimer();
TimerManager.clearTimeLeft(this);
// Xóa trạng thái thời gian còn lại
//TimerManager.resetTimer(this);
}
@Override
public void onBackPressed() {
super.onBackPressed();
TimerManager.loadTimeLeft(this);
startCountdown();
`
MAIN,INSIDE,SEAT,FOOD,WAIT
Я пробовал много разных способов, но когда я нажимаю кнопку завершения в действии ожидания, время не отображается. перезагрузить. Я хочу, чтобы часы в режимах «Место», «Еда», «Ожидание» работали как те же часы, когда возвращаемся или продолжаем, часы по-прежнему работают правильно. При нажатии кнопки «Готово» или при возвращении из места в салон часы необходимо сбросить. Например, если пользователь выйдет из приложения во время бронирования билета, время будет стерто и вернется к 10 минутам.

Подробнее здесь: https://stackoverflow.com/questions/787 ... -ondestroy
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»