Моя деятельность открывается снова и снова автоматически - PullRequest
0 голосов
/ 05 июля 2019

я реализую часы обратного отсчета, но в активности произошла ошибка, активность снова и снова открывается автоматически снова и снова, я хочу сделать, когда обратный отсчет становится 00 00 00, тогда установлен alaram, который должен быть вызван

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtDay = (TextView) findViewById(R.id.txtDay);
    txtHour = (TextView) findViewById(R.id.txtHour);
    txtMinute = (TextView) findViewById(R.id.txtMinute);
    txtSecond = (TextView) findViewById(R.id.txtSecond);
    tvEventStart = (TextView) findViewById(R.id.tveventStart);
    backgroundLayout = (RelativeLayout) findViewById(R.id.activity_main);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    timer = new Timer();

    try {
        checkEventisGone();
    } catch (ParseException e) {
        e.printStackTrace();
    }

    if (!check) {
        countDownStart();
        makeAlarm(eventDateforAlram);
    } else {

        startCelebration();
        textViewGone();
    }

    doBindService();

    changeAlphaofImg();


}

private void checkEventisGone() throws ParseException {
    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyyMMddHHmmss");
    // Please here set your event date//YYYY-MM-DD
    Date futureDate = dateFormat.parse(eventDate);
    Date currentDate = new Date();
    if (currentDate.after(futureDate)) {
        check = true;
    } else {
        check = false;
    }
}

private void changebgImageAutomitacally() {
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {

            runOnUiThread(new Runnable() // run on ui thread
            {
                public void run() {

                    if (series) {
                        if (counter < images.length) {
                            counter++;
                            changingBackgoundimage(images[counter]);
                        } else if (counter == images.length) {
                            series = false;
                        } else {
                            counter = 0;
                        }
                    } else {
                        if (counter < images.length) {
                            counter = new Random().nextInt(images.length);
                            changingBackgoundimage(images[counter]);
                        } else {
                            counter = 0;
                        }
                    }

                }
            });
        }
    }, 3000, 3000);
}

private void changeAlphaofImg() {
    backgroundLayout.setAlpha(backgroundLayout.getAlpha() - 0.1f);
}

private void changingBackgoundimage(int id) {
    backgroundLayout.setBackgroundResource(id);

}

private void startCelebration() {
    Intent music = new Intent();
    music.setClass(getApplicationContext(), MusicService.class);
    startService(music);
    changebgImageAutomitacally();
}


private void makeAlarm(String eventDate) {
    AlarmManager objAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Calendar objCalendar = Calendar.getInstance();
    String[] arr = eventDate.split("/");
    objCalendar.set(Calendar.YEAR, 2019);
    objCalendar.set(Calendar.MONTH, 6);
    objCalendar.set(Calendar.DAY_OF_MONTH, 5);
    objCalendar.set(Calendar.HOUR_OF_DAY, 10);
    objCalendar.set(Calendar.MINUTE, 0);
    objCalendar.set(Calendar.SECOND, 0);
    objCalendar.set(Calendar.MILLISECOND, 0);
    objCalendar.set(Calendar.AM_PM, Calendar.AM);

    Intent alamShowIntent = new Intent(this, MainActivity.class);
    PendingIntent alarmPendingIntent = PendingIntent.getActivity(this, 0, alamShowIntent, 0);

    objAlarmManager.set(AlarmManager.RTC_WAKEUP, objCalendar.getTimeInMillis(), alarmPendingIntent);

}


public void countDownStart() {
    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, 1000);
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat(
                        "yyyyMMddHHmmss");
                // Please here set your event date//YYYY-MM-DD
                Date futureDate = dateFormat.parse(eventDate);
                Date currentDate = new Date();
                if (!check) {
                    if (!currentDate.after(futureDate)) {
                        long diff = futureDate.getTime()
                                - currentDate.getTime();
                        long days = diff / (24 * 60 * 60 * 1000);
                        diff -= days * (24 * 60 * 60 * 1000);
                        long hours = diff / (60 * 60 * 1000);
                        diff -= hours * (60 * 60 * 1000);
                        long minutes = diff / (60 * 1000);
                        diff -= minutes * (60 * 1000);
                        long seconds = diff / 1000;
                        txtDay.setText("" + String.format("%02d", days));
                        txtHour.setText("" + String.format("%02d", hours));
                        txtMinute.setText(""
                                + String.format("%02d", minutes));
                        txtSecond.setText(""
                                + String.format("%02d", seconds));
                    } else {
                        tvEventStart.setVisibility(View.GONE);
                        tvEventStart.setText("The event started!");
                        textViewGone();
                        check = true;
                        startCelebration();

                    }
                } else {
                    //
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    handler.postDelayed(runnable, 1 * 1000);

}

public void textViewGone() {
    findViewById(R.id.LinearLayout1).setVisibility(View.GONE);
    findViewById(R.id.LinearLayout2).setVisibility(View.GONE);
    findViewById(R.id.LinearLayout3).setVisibility(View.GONE);
    findViewById(R.id.LinearLayout4).setVisibility(View.GONE);
    findViewById(R.id.textViewheader1).setVisibility(View.GONE);
    findViewById(R.id.textViewheader2).setVisibility(View.GONE);
}

private ServiceConnection Scon = new ServiceConnection() {

    public void onServiceConnected(ComponentName name, IBinder
            binder) {
        mServ = ((MusicService.ServiceBinder) binder).getService();
    }

    public void onServiceDisconnected(ComponentName name) {
        mServ = null;
        doUnbindService();
    }
};

void doBindService() {
    bindService(new Intent(this, MusicService.class),
            Scon, Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

void doUnbindService() {
    if (mIsBound) {
        unbindService(Scon);
        mIsBound = false;
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    doUnbindService();
}

, пожалуйста, предложите мне что-нибудь, чтобы мне было легче от этого. Я использую сервис, который воспроизводит музыку в фоновом режиме

1 Ответ

0 голосов
/ 05 июля 2019

Привет, ваша проблема startCelebration(); вызов внутри работоспособного

public void countDownStart() {
    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, 1000);
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat(
                        "yyyyMMddHHmmss");
                // Please here set your event date//YYYY-MM-DD
                Date futureDate = dateFormat.parse(eventDate);
                Date currentDate = new Date();
                if (!check) {
                    if (!currentDate.after(futureDate)) {
                        long diff = futureDate.getTime()
                                - currentDate.getTime();
                        long days = diff / (24 * 60 * 60 * 1000);
                        diff -= days * (24 * 60 * 60 * 1000);
                        long hours = diff / (60 * 60 * 1000);
                        diff -= hours * (60 * 60 * 1000);
                        long minutes = diff / (60 * 1000);
                        diff -= minutes * (60 * 1000);
                        long seconds = diff / 1000;
                        txtDay.setText("" + String.format("%02d", days));
                        txtHour.setText("" + String.format("%02d", hours));
                        txtMinute.setText(""
                                + String.format("%02d", minutes));
                        txtSecond.setText(""
                                + String.format("%02d", seconds));
                    } else {
                        tvEventStart.setVisibility(View.GONE);
                        tvEventStart.setText("The event started!");
                        textViewGone();
                        check = true;
                        startCelebration();<*********** check logic passing this

                    }
                } else {
                    //
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    handler.postDelayed(runnable, 1 * 1000);

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...