Android AlarmManager и сервисный вопрос - PullRequest
1 голос
/ 27 января 2011

В моем приложении есть несколько файлов, но сейчас важны только 3 из них.Это приложение-напоминание со звуком будильника и уведомлениями.У меня есть файл maincode.java, содержащий флажок и его слушатель.Если пользователь устанавливает флажок в чекбоксе, AlarmManager отправляет намерение в AlarmReceiver.java, который запускает MyService.java.MyService Java содержит код о воспроизведении звука.Код является частичным.MyService.java:

public void onCreate() {
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

    player = MediaPlayer.create(this, R.raw.sound);
    player.setLooping(false); // Set looping
}

@Override
public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");
    player.stop();
}

@Override
public void onStart(Intent intent, int startid) {
    Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onStart");
    player.start();
}

AlarmReceiver.java:

public void onCreate() {
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

    player = MediaPlayer.create(this, R.raw.sound);
    player.setLooping(false); // Set looping

Важная часть maincode.java:

    cb1 = (CheckBox) findViewById(R.id.CheckBox01);
    cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
        {           
            if (cb1.isChecked()) 
                {
                 if (GlobalVars.getHourOfDay() >= 0) 
                 {
                     Toast.makeText(maincode.this, "ok", Toast.LENGTH_SHORT).show();
                     rem1.setText(GlobalVars.getReminder1name());
                        Intent intent = new Intent(maincode.this, AlarmReceiver.class);
                        PendingIntent pendingIntent = PendingIntent.getBroadcast(bInsulinReminder.this, 0,
                          intent, PendingIntent.FLAG_UPDATE_CURRENT);
                        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                        Calendar cal = Calendar.getInstance();
                        cal.set(Calendar.HOUR_OF_DAY, GlobalVars.getHourOfDay());
                        cal.set(Calendar.MINUTE, GlobalVars.getMinute());
                        cal.set(Calendar.SECOND, 0);
                        cal.set(Calendar.MILLISECOND, 0);
                        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+ 3000, 6000, pendingIntent);

                 }
                 Toast.makeText(maincode.this, "Checked", Toast.LENGTH_SHORT).show();
                } else {
                    rem1.setText("No reminder set");
                    Toast.makeText(maincode.this, "Not checked", Toast.LENGTH_SHORT).show();
                }
        }

        });

(rem1 - кнопка напоминания, текст которойзависит от имени того, что хочет пользователь)

Проблема с кодом заключается в том, что если я включу сигнализацию, я не смогу ее остановить.Я знаю, что в MyService.java есть команда player.stop (), но как я могу вызвать ее с конца maincode.java, где флажок снят?

1 Ответ

3 голосов
/ 27 января 2011

Нет, вы не можете сделать это напрямую от слушателя. Вы можете отключить будильник следующим образом:

Intent intent = new Intent(maincode.this, AlarmReceiver.class);
PendingIntent pendingIntent =  PendingIntent.getBroadcast(bInsulinReminder.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
pendingItem.cancel();
alarmManager.cancel(pendingItem);

Или, если (я полагаю) AlarmReceiver является реализацией BroadcastReceiver, и из метода onReceive вы запускаете MyService, который является реализацией класса Service.

Итак, если вы хотите отключить эту тревогу из вашего слушателя maincode.java, вы можете просто остановить MyService, воссоздав PendingIntent, который вы использовали в AlarmReceiver, и выполнив метод stopService.

Надеюсь, это поможет.

...