我使用以下代码将我的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();
}
}
然而,当这个事件发生时间到来时,没有任何反应。我这样做了吗?
答案 0 :(得分:1)
愚蠢的怀疑,但你注册了BroadcastReceiver和所需的IntentFilter吗?
修改强> 在清单文件中,您应该在应用程序节点
中包含以下行<receiver android:name="your_receiver_name" >
<intent-filter>
<action android:name="your_action_name" >
</action>
</intent-filter>
</receiver>
动态的另一种方法是,调用registerReceiver (BroadcastReceiver receiver, IntentFilter filter)
有关如何使用广播过滤器的精彩教程,您可以访问此Vogella Tutorial
希望这会清除您的疑问并解决问题。