我创建了一个方法,通过按下主要活动下的保存按钮来调用它,如下所示:
public void scheduleAlarms(Context ctxt) {
String [] calvalue = (MessageDelay.getSelectedItem().toString()).split(" ", 3);
int H = Integer.parseInt(calvalue[1]);
Log.v("Timer","Timer"+H);
switch (H){
case 9:
H=9;
break;
case 12:
H=12;
break;
case 3:
H=15;
break;
case 5:
H=17;
break;
case 6:
H=18;
break;
case 8:
H=20;
break;
}
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, H);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
AlarmManager mgr=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(getApplicationContext(), AlarmReceiver.class);
PendingIntent pi=PendingIntent.getService(getApplicationContext(), 0, i, 0);
mgr.setRepeating(AlarmManager.RTC,cal.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pi);
Log.v("Timer","Timer");
}
然后我添加了一行显示如下:
<receiver android:process=":remote" android:name=".AlarmReceiver"></receiver>
然后创建一个接收器类如下:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
Toast.makeText(context, "broadcast received", Toast.LENGTH_SHORT).show();
// Set up new intent
Intent newIntent = new Intent(context, SendMessage.class);
// Start new intent
context.startService(newIntent);
} catch (Exception e) {
Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
但由于某些原因,当我在模拟器上测试它时,我无法接收任何广播:(
有人可以告诉我我做错了什么吗?
非常感谢提前
答案 0 :(得分:2)
您正在使用PendingIntent
进行服务,但希望收到广播。尝试使用PendingIntent.getBroadcast()
。