Android 报警接收器和广播接收器
我编写了一个扩展BroadcastReceiver的类:每天2个警报应该在引导完成后启动,但似乎没有运行。要检查好几个小时,但我不明白问题出在哪里。如果代码中有问题Android 报警接收器和广播接收器,android,Android,我编写了一个扩展BroadcastReceiver的类:每天2个警报应该在引导完成后启动,但似乎没有运行。要检查好几个小时,但我不明白问题出在哪里。如果代码中有问题 public class AlarmReceiver extends BroadcastReceiver { private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLET
public class AlarmReceiver extends BroadcastReceiver {
private final String BOOT_COMPLETED_ACTION =
"android.intent.action.BOOT_COMPLETED";
final String not1[] = new String[11];
int not1end = 10;
int x;
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BOOT_COMPLETED_ACTION)) {
Intent myIntent = new Intent(context, Notify.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, myIntent, 0);
not1[0] = "one";
not1[1] = "two";
not1[2] = "three";
// ...
rando();
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(ns);
int icon = R.drawable.ic_launcher2;
CharSequence tickerText = not1[x];
long when = System.currentTimeMillis();
Notification notification=new Notification(icon, tickerText, when);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
CharSequence contentTitle = "title";
CharSequence contentText = not1[x];
Intent notificationIntent = new Intent();
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.HOUR_OF_DAY, 05); // midday
cal1.set(Calendar.MINUTE, 45);
cal1.set(Calendar.SECOND, 00);
Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.HOUR_OF_DAY, 17);// 8pm for example
cal2.set(Calendar.MINUTE, 30);
cal2.set(Calendar.SECOND, 00);
}
}
private void rando() {
Random generator = new Random();
int random = generator.nextInt(not1end);
boolean flag = generator.nextBoolean();
x = random;
}
}
舱单:
<receiver
android:name=".AlarmReceiver"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
如果您想接收
启动\u完成
事件,您需要添加一个意向过滤器:
<receiver
android:name=".AlarmReceiver"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
不要忘记适当的许可证:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
您是否已将此收件人添加到您的清单中?请尝试删除android:exported=“false”
并报告。另外,intent.getAction().equals(启动\u完成\u操作)
是错误的。您必须BOOT\u COMPLETED\u ACTION.equals(intent.getAction())
,因为NPEs很快就会出现问题。。。我刚刚更新了代码(也看到logcat没有错误)。嗯,我看不到您在哪里启动通知或其他任何东西。添加这一行Log.v(“AlarmReceiver”,intent.getAction())
作为onReceive()
中的第一行,并在引导设备后检查日志。