我的应用程序有一个带有数字选择器的重复闹钟,所以如果我选择每隔一分钟重复一次声音就会消失,但如果用户接到电话,则闹钟不会停止。我怎么解决这个问题?我应该在接收器活动中实施什么才能检测到电话?
接收器:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
public class MainReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MediaPlayer m=MediaPlayer.create(context, R.raw.sound2);
m.start();
}
}
答案 0 :(得分:1)
刚刚更新了我的上述答案:根据AlarmManager.setRepeating(int type,long triggerAtMillis,long intervalMillis,PendingIntent操作)的Android文档,它将继续出现,直到使用cancel(PendingIntent)显式删除。如果你正在使用这个API,那么要么你必须在通话中取消它,要么在接收器中你必须添加通话条件而只是在没有做任何事情的情况下返回。
答案 1 :(得分:0)
尝试代码:
final MediaPlayer m = MediaPlayer.create(context, R.raw.sound2); m.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { m.start(); } }); AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); am.requestAudioFocus(new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { Log.i("FOCUS",focusChange + ""); if (focusChange > 0) m.start(); else m.pause(); } }, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
或者让您的BroadcastReceiver接收器电话进入状态:
public class MainReceiver extends BroadcastReceiver {
private static final String PLAYAUDIO = "PLAYAUDIO";
private static final String PHONE_STATE = "android.intent.action.PHONE_STATE";
private static MediaPlayer m;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(PLAYAUDIO)) {
m= MediaPlayer.create(context, R.raw.sound2);
m.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
m.start();
}
});
m.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
m = null;
}
});
} else
if (intent.getAction().equals(PHONE_STATE)) {// NEW CALL STATE
String extra = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (extra.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)
&& m != null)
m.start();
else if (m != null)
m.pause();
}
}
}
像这样的AndroidManifest.xml:
<receiver android:name="YourPackage.MainReceiver">
<intent-filter>
<action android:name="PLAYAUDIO"/>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
//Add permistion
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
答案 2 :(得分:0)
伙计们,我终于明白了,我看到了几个电话管理员的例子,我写了一个并且工作得很好。
public class MainReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
MediaPlayer m=MediaPlayer.create(context, R.raw.sound2);
TelephonyManager tm =
(TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
switch (tm.getCallState()) {
case TelephonyManager.CALL_STATE_RINGING:
m.stop();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
m.stop();
break;
case TelephonyManager.CALL_STATE_IDLE:
m.start();
break;
}
}
}