每天使用AlarmManger android进行火灾通知

时间:2016-12-09 08:53:20

标签: android broadcastreceiver alarmmanager

我正在尝试在早上7点设置闹钟并每天点火。  但我面临的问题是我在一天内多次收到通知 请帮帮我

这是我的代码:

  public void startAlert() {
        Intent myIntent = new Intent(ReminderActivity.this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(ReminderActivity.this, 0, myIntent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        Calendar firingCal = Calendar.getInstance();
        Calendar currentCal = Calendar.getInstance();


        if (Prefs.getInt("HOURS", 0) == 0) {
            firingCal.set(Calendar.HOUR_OF_DAY, 07);
            firingCal.set(Calendar.MINUTE, 00);
            firingCal.set(Calendar.SECOND, 0);
            firingCal.set(Calendar.AM_PM, Calendar.AM);
        } else {
            firingCal.set(Calendar.HOUR_OF_DAY, Prefs.getInt("HOURS", 0));
            firingCal.set(Calendar.MINUTE, Prefs.getInt("MINUTES", 0));
            firingCal.set(Calendar.SECOND, 0);
            if (hour < 12) {
                firingCal.set(Calendar.AM_PM, Calendar.AM);
            } else {
                firingCal.set(Calendar.AM_PM, Calendar.PM);
            }
        }


        long intendedTime = firingCal.getTimeInMillis();
        long currentTime = currentCal.getTimeInMillis();

        if (intendedTime >= currentTime) {
            // you can add buffer time too here to ignore some small differences in milliseconds
            // set from today
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
        } else {
            // set from next day
            // you might consider using calendar.add() for adding one day to the current day
            firingCal.add(Calendar.DAY_OF_MONTH, 1);
            intendedTime = firingCal.getTimeInMillis();

            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
        }
    }

BroadcastReceiver类

public class AlarmReceiver extends BroadcastReceiver {
    int MID = 0;
    String notificationDesc = "";

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        if (Prefs.getString("LOCAL_NOTI", "").equalsIgnoreCase("0")) {
            return;
        }
        long when = System.currentTimeMillis();
        if (!Prefs.getBoolean("TODAY_NOTI", false)) {
            return;
        }
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notificationIntent = new Intent(context, HomeScreen.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
                context).setSmallIcon(getNotificationIcon())
                .setContentTitle("Yoga App")
                .setContentText("Did you do yoga today ?").setSound(alarmSound)
                .setAutoCancel(true).setWhen(when)
                .setContentIntent(pendingIntent).setColor(ContextCompat.getColor(context, R.color.colorPrimary))
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_notification_icon)).setStyle(new NotificationCompat.BigTextStyle().bigText(notificationDesc))
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
        notificationManager.notify(MID, mNotifyBuilder.build());
        MID++;

    }

这里是清单文件:

<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>

 <receiver android:name="Class name"  android:enabled="true" android:exported="false" android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
            <intent-filter>
               <action android:name="android.intent.action.REBOOT"/>
                <action android:name="android.intent.action.TIME_SET" />
               <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
               <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>
        </receiver>

1 个答案:

答案 0 :(得分:0)

public class AlarmReciever extends WakefulBroadcastReceiver {

    // An ID used to post the notification.
    public static final int NOTIFICATION_ID = 1;
    //public static int id = 0;
    NotificationCompat.Builder builder;
    Context context;
    // The app's AlarmManager, which provides access to the system alarm services.
    private AlarmManager alarmMgr;

    private NotificationManager mNotificationManager;

    @Override
    public void onReceive(Context context, Intent intent) {


        Logger.get().e(this, "Alarm trigger");
        this.context = context;
        String activityname = intent.getExtras().getString("activityname");
        String alarmid = intent.getExtras().getString("alarmid");
        sendNotification("" + activityname);
        cancelAlarm(context, alarmid, intent);

    }


    // BEGIN_INCLUDE(set_alarm)

    /**
     * Sets a repeating alarm that runs once a day at approximately 8:30 a.m. When the
     * alarm fires, the app broadcasts an Intent to this WakefulBroadcastReceiver.
     *
     * @param context
     */
    public void setAlarm(Context context, Calendar calendar, int hour, int min, String message, String alarmid) {
        String cancelid;

        alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, AlarmReciever.class);
        // The pending intent that is triggered when the alarm fires.
        // id = id + 1;
        intent.putExtra("activityname", message);
        intent.putExtra("alarmid", "" + alarmid);

        Logger.get().d(this, "alarm" + CommonUtil.safeLongToInt(calendar.getTimeInMillis()));
        PendingIntent alarmIntent = PendingIntent.getBroadcast(context, Integer.valueOf(alarmid), intent, PendingIntent.FLAG_UPDATE_CURRENT);


        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        /*
         * If you don't have precise time requirements, use an inexact repeating alarm
         * to minimize the drain on the device battery.
         *
         * The call below specifies the alarm type, the trigger time, the interval at
         * which the alarm is fired, and the alarm's associated PendingIntent.
         * It uses the alarm type RTC_WAKEUP ("Real Time Clock" wake up), which wakes up
         * the device and triggers the alarm according to the time of the device's clock.
         *
         * Alternatively, you can use the alarm type ELAPSED_REALTIME_WAKEUP to trigger
         * an alarm based on how much time has elapsed since the device was booted. This
         * is the preferred choice if your alarm is based on elapsed time--for example, if
         * you simply want your alarm to fire every 60 minutes. You only need to use
         * RTC_WAKEUP if you want your alarm to fire at a particular date/time. Remember
         * that clock-based time may not translate well to other locales, and that your
         * app's behavior could be affected by the user changing the device's time setting.
         *
         * Here are some examples of ELAPSED_REALTIME_WAKEUP:
         *
         * // Wake up the device to fire a one-time alarm in one minute.
         * alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
         *         SystemClock.elapsedRealtime() +
         *         60*1000, alarmIntent);
         *
         * // Wake up the device to fire the alarm in 30 minutes, and every 30 minutes
         * // after that.
         * alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
         *         AlarmManager.INTERVAL_HALF_HOUR,
         *         AlarmManager.INTERVAL_HALF_HOUR, alarmIntent);
         */
        // Set the alarm to fire at approximately 8:30 a.m., according to the device's
        // clock, and to repeat once a day.


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmMgr.setExact(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(), alarmIntent);
        } else {
            alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
        }


        // Enable {@code SampleBootReceiver} to automatically restart the alarm when the
        // device is rebooted.
        ComponentName receiver = new ComponentName(context, AlarmReciever.class);
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

    }
    // END_INCLUDE(set_alarm)


    /**
     * Cancels the alarm.
     *
     * @param context
     */
    // BEGIN_INCLUDE(cancel_alarm)
    public void cancelAlarm(Context context, String alarmid, Intent intent) {
        // If the alarm has been set, cancel it.
        alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmMgr.cancel(PendingIntent.getBroadcast(context, Integer.valueOf(alarmid), intent, PendingIntent.FLAG_CANCEL_CURRENT));

//        PackageManager pm = context.getPackageManager();
//        pm.setComponentEnabledSetting(receiver,
//                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
//                PackageManager.DONT_KILL_APP);
    }



    // Post a notification indicating whether a doodle was found.
    private void sendNotification(String activityname) {
        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mNotificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Uri sound = null;
        try {
            sound = Uri.parse(sound);
        }
        catch(Exception e){

        }
            PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                    new Intent(context, SomeActivity.class), 0);
            Bitmap largeIcon = BitmapFactory.decodeResource(icon);
            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(context).setAutoCancel(true)
                            .setSmallIcon(smallicon)
                            .setLargeIcon(largeIcon)
                            .setContentTitle("title")
                            .setStyle(new NotificationCompat.BigTextStyle()
                                    .bigText(activityname)).setSound(sound).setVibrate(new long[]{1000, 1000})
                            .setContentText(activityname);
            mBuilder.setContentIntent(contentIntent);
            mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());




    }








    public String getCurrentTime(){
        //DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
        //get current date time with Date()
        Date date = new Date();
        return String.valueOf(dateFormat.format(date));

    }


}