使用AlarmManager和BroadcastReceiver安排振铃模式

时间:2015-01-13 13:19:52

标签: android service broadcastreceiver alarmmanager android-audiomanager

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

这是我的代码示例:

@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);
}

这是我的接收器类,它将把振铃模式设置为PendingIntent中的spac。

@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>

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

1 个答案:

答案 0 :(得分:0)

以下是答案..

使用

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

而不是

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

问题解决。