有人可以教我如何阻止闹钟响起我的代码。我是否有正确的方法来阻止其他活动的警报?因为,截至目前,即使我按下了解除按钮,警报仍然响起。
alertDialogBuilder.setTitle("Alarm");
alertDialogBuilder
.setMessage("Stop Alarm")
.setCancelable(false)
.setPositiveButton("Dismiss",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
eReceiver = new EAlarmReceiver();
Ringtone r = eReceiver.ringAlarm(context);
r.stop();
Toast.makeText(context.getApplicationContext(), "Alarm Stopped", Toast.LENGTH_LONG).show();
Intent openInterface = new Intent("proj.receiver.RECEIVERINTERFACE");
openInterface.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(openInterface);
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}// end oncreate()
这是我开始闹钟的地方
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
Object[] pdusObj = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdusObj.length];
for (int i = 0; i<pdusObj.length; i++)
{
messages[i] = SmsMessage.createFromPdu ((byte[])
pdusObj[i]);
sender = messages[i].getOriginatingAddress();
}
for (SmsMessage msg : messages) {
if (msg.getMessageBody().contains("firealert")) {
ringAlarm(context);
Intent openStopAlarm = new Intent("proj.receiver.STOPALARM");
openStopAlarm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(openStopAlarm);
}//end if
}//end for
}// end onreceive
public Ringtone ringAlarm(Context context)
{
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if(alert == null){
// alert is null, using backup
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(alert == null){ // I can't see this ever being null (as always have a default notification) but just incase
// alert backup is null, using 2nd backup
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
Ringtone r = RingtoneManager.getRingtone(context.getApplicationContext(), alert);
AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
int maxVolumeAlarm = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
//int maxVolumeRing = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, maxVolumeAlarm,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
//audioManager.setStreamVolume(AudioManager.STREAM_RING, maxVolumeRing,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
r.play();
Toast.makeText(context.getApplicationContext(), "alarm started", Toast.LENGTH_LONG).show();
return r;
}
//end ringAlarm()
答案 0 :(得分:2)
在BroadcastReceiver中声明的Ringtone r
值与您在Activity中定义的值不同,您必须执行使r变量在您的应用程序中具有更多范围的内容:
您可以将r变量定义为
static Ringtone;
在你的broadcastreceiver中,然后在onReceive()方法中为它赋值,然后从你的活动中调用该变量,只需声明新的r变量如下:
Ringtone r=yourpackge.Your_BroadcastReceiver_Class.r
然后致电
r.stop();