我正在使用以下代码将我的 android 应用程序设置为在给定的时间使手机静音event.getStartTime()
public static void schedule(Context ctx, Event event) {
//schedule method is being called, but the alarm manager is not being set for some reason
Calendar start = event.getStartTime();
long end = event.getEndTime().getTimeInMillis();
String status = event.getStatus();
Intent intent = new Intent(ctx, AlarmReceiver.class);
intent.putExtra("time", end);
intent.putExtra("status", status);
PendingIntent sender = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, start.getTimeInMillis(), sender);
}
这是我onReceive
在AlarmReceiver
课堂上扩展的方法BroadcastReceiver
@Override
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context, "changing status", Toast.LENGTH_SHORT).show();
ContextWrapper c = new ContextWrapper(context);
AudioManager am = (AudioManager) c.getBaseContext().getSystemService(Context.AUDIO_SERVICE);
Calendar set_time = Calendar.getInstance();
int current_ringer_mode = am.getRingerMode();
String current_status = "";
switch (current_ringer_mode) {
case AudioManager.RINGER_MODE_VIBRATE: current_status = "vibrate";
break;
case AudioManager.RINGER_MODE_SILENT: current_status = "silence";
break;
case AudioManager.RINGER_MODE_NORMAL: current_status = "sound";
break;
default: current_status = "silence";
break;
}
try {
Bundle bundle = intent.getExtras();
String status = bundle.getString("status");
set_time.setTimeInMillis(bundle.getLong("time"));
if (status.equals("vibrate")) {
//turn phone on vibrate
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
if (bundle.getLong("time") != 0L) {
//set unscheduler
EventScheduler.unschedule(context.getApplicationContext(),
set_time,
current_status);
}
} else if (status.equals("silence")) {
//turn phone on silence
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
if (bundle.getLong("time") != 0L) {
//set unscheduler
EventScheduler.unschedule(context.getApplicationContext(),
set_time,
current_status);
}
} else if (status.equals("sound")) {
//turn on sound
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
} catch(Exception e) {
Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
然而,当这个事件应该发生的时候到了,什么都没有发生。我这样做正确吗?