Search code examples
androidservicebroadcastreceiveralarmmanagerandroid-audiomanager

Schedule ringer mode using AlarmManager and BroadcastReceiver


I want to schedule ringer mode at user define time but it's not working. The problem here is the ringer mode should change according to given time schedule, but it's switching one case to another and device continuing vibrate to normal mode and vice-versa.

Here is my code sample:

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

and this is my receiver class that will set ringer mode as spacify in PendingIntent.

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

and I'm using this receiver.

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

Hoping a good answer. Thanks.


Solution

  • Here is the answer..

    Use of

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

    instead of

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

    And problem solve.