我的應用程序中有一些文件,但其中只有3個文件很重要。這是一個提醒應用程序與報警聲音和通知。 我有一個maincode.java文件,其中包含一個複選框及其偵聽器。如果用戶檢查chechbox,AlarmManager會將意圖發送到啓動MyService.java的AlarmReceiver.java。 MyService java包含有關播放聲音的代碼。代碼是部分的。 MyService.java:Android AlarmManager和服務問題
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的末尾調用它,其中複選框未選中?