AlarmReceiver和BroadcastReceiver

时间:2012-12-17 18:47:45

标签: android

我写了一个扩展BroadcastReceiver的类:每天应该在启动完成后启动2个警报,但似乎没有运行。需要很多时间检查,但我不明白问题出在哪里。如果代码中有问题?

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>

1 个答案:

答案 0 :(得分:1)

如果您想接收BOOT_COMPLETE个事件,则需要添加一个Intent-Filter:

<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" />