我的应用程序中有一些文件,但现在只有 3 个文件很重要。这是一个带有警报声音和通知的提醒应用程序。我有一个包含复选框及其侦听器的 maincode.java 文件。如果用户在 chechbox 中签入,AlarmManager 会向 AlarmReceiver.java 发送一个意图,后者会启动 MyService.java。MyService java 包含有关播放声音的代码。代码是部分的。我的服务.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();
}
警报接收器.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 末尾调用它?