使用 AlarmManager 和 BroadcastReceiver 安排铃声模式

Schedule ringer mode using AlarmManager and BroadcastReceiver

我想在用户定义的时间安排振铃模式,但它不起作用。这里的问题是铃声模式应该根据给定的时间表改变,但它会将一种情况切换到另一种情况,并且设备会继续振动到正常模式,反之亦然。

这是我的代码示例:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
Calendar calendar1 = Calendar.getInstance();


calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.AM_PM,Calendar.AM);

Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, (int)System.currentTimeMillis(), myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

calendar1.set(Calendar.HOUR_OF_DAY, 12);
calendar1.set(Calendar.MINUTE, 30);
calendar1.set(Calendar.AM_PM,Calendar.PM);

Intent myIntent1 = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, (int)System.currentTimeMillis(), myIntent1,PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), pendingIntent);
}

这是我的接收器 class,它将在 PendingIntent 中将铃声模式设置为 spacify。

@Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
AudioManager audio = (AudioManager)arg0.getSystemService(Context.AUDIO_SERVICE);

switch(audio.getRingerMode()){
case AudioManager.RINGER_MODE_NORMAL :
    audio.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
    Log.d("MODE", "is vibrate");
    break;

case AudioManager.RINGER_MODE_VIBRATE :
    audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
    Log.d("MODE", "is normal");
    break;
}}

我正在使用这个接收器。

<receiver android:name=".MyReceiver">  
    <intent-filter>  
        <action android:name="android.media.RINGER_MODE_CHANGED" /> 
    </intent-filter>  
</receiver>

希望得到一个好的答案。谢谢

答案在这里..

使用

<receiver android:name=".MyReceiver"> </receiver>

而不是

<receiver android:name=".MyReceiver">  
<intent-filter>  
    <action android:name="android.media.RINGER_MODE_CHANGED" /> 
</intent-filter>  

并解决问题。