我的应用中有一些文件,但现在只有3个很重要。这是一个提醒应用程序,具有警报声和通知。 我有一个maincode.java文件,其中包含一个复选框及其监听器。如果用户在chechbox中检查,则AlarmManager会向AlarmReceiver.java发送一个intent,它启动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的末尾调用它来取消选中复选框?
答案 0 :(得分:3)
不,你不能直接从听众那里做到这一点。您可以通过以下方式禁用警报:
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侦听器内部停止此警报,可以通过重新创建在AlarmReceiver中使用的PendingIntent并执行stopService方法来停止MyService。
希望有所帮助。