我正在尝试构建一个警报应用程序。当闹钟打开时,用户必须在关闭之前扫描匹配的二维码。我查看了此链接以播放声音:如何在 Android 中播放铃声/闹钟声音,我正在使用 zxing 库中的 ScanningViaIntent 进行 QR 码扫描仪:https ://code.google.com/ p/zxing/。
所以我在 onStart() 活动中启动声音:
@Override
public void onStart(){
super.onStart();
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
}
然后用户通过按下按钮启动扫描仪:
private class HandleClick implements OnClickListener{
public void onClick(View arg0) {
IntentIntegrator integrator = new IntentIntegrator(AlarmRequirementsActivity.this);
integrator.initiateScan();
}
}
扫描仪的结果在这里返回:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
System.out.println("scanREsult" + scanResult);
System.out.println("requestCode: " + requestCode);
TextView result =(TextView)findViewById(R.id.scanResult);
if (resultCode == RESULT_OK) {
String scanResultString = intent.getStringExtra("SCAN_RESULT");
if(scanResultString .equals(matchString))
{
result.setText("You found it!");
r.stop();
}
else
{
result.setText("\"" + scanResultString + "\""+ " did not match");
}
System.out.println(intent.getStringExtra("SCAN_RESULT"));
} else if (resultCode == RESULT_CANCELED) {
}
}
// else continue with any other code you need in the method
}
如您所见,我在成功匹配后调用 r.stop() 。然而,这些是我的问题:
- 从扫描仪返回后,活动将重新启动。比赛是否成功并不重要。
- 这导致现在播放两个警报音
我试过把它放在 onCreate() 方法中,但也无济于事。
更新:
我试过了:
@Override
public void onStart(){
super.onStart();
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
r = RingtoneManager.getRingtone(getApplicationContext(), notification);
if(!r.isPlaying())
{
r.play();
}
}
这在下面。两者都有相同的问题
if(scanResultString .equals(matchString))
{
result.setText("You found it!");
if(r.isPlaying())
{
r.stop();
}
}