为什么预定通知每20分钟显示一次,而不是Android中的预定时间以及如何修复?

时间:2017-06-21 03:45:58

标签: android notifications alarmmanager

我有一个通知,在显示时会显示不同的活动以鼓励用户参与。通知显示但是在关注Android开发人员文档之后,我将其编程为每天下午2点展示一次。不幸的是,它显示每20分钟一次。我不知道我做错了什么。我按照教程每隔2小时显示一次自定义通知,以获得基本的理解,但不希望用户看到很多通知。然后,我在SO上查看了各种问题/答案,发现使用报警管理器将是最佳选择。我根据谷歌警报管理器的例子修改了代码,但它没有按预期工作。这是我的代码以及到目前为止我尝试过的内容:

清单

<service
    android:name=".EngagementNotification"
    android:enabled="true"
    android:exported="false" />

<receiver android:name=".EngagementNotificationInitReceiver" />
<receiver android:name=".EngagementNotificationInit">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.TIMEZONE_CHANGED" />
        <action android:name="android.intent.action.TIME_SET" />
    </intent-filter>
</receiver>

EngagementNotification

public class EngagementNotification extends IntentService {

    private static final int NOTIFICATION_ID = 1;
    private static final String ACTION_START = "ACTION_START";
    private static final String ACTION_DELETE = "ACTION_DELETE";

    public EngagementNotification() {
        super(EngagementNotification.class.getSimpleName());
    }

    public static Intent createIntentStartNotificationService(Context context) {
        Intent intent = new Intent(context, EngagementNotification.class);
        intent.setAction(ACTION_START);
        return intent;
    }

    public static Intent createIntentDeleteNotification(Context context) {
        Intent intent = new Intent(context, EngagementNotification.class);
        intent.setAction(ACTION_DELETE);
        return intent;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(getClass().getSimpleName(), "onHandleIntent, started handling a notification event");
        try {
            String action = intent.getAction();
            if (ACTION_START.equals(action)) {
                processStartNotification();
            }
        } finally {
            WakefulBroadcastReceiver.completeWakefulIntent(intent);
        }
    }

    private void processDeleteNotification(Intent intent) {
        // Log something?
    }

    private void processStartNotification() {
        // Do something. For example, fetch fresh data from backend to create a rich notification?
        HashMap<String, String> mActivities = new HashMap<String, String>();
        mActivities.put("ActivityOne", "com.example.testapp.ActivityOne");
        mActivities.put("ActivityTwo", "com.example.testapp.ActivityTwo");
        mActivities.put("ActivityThree", "com.example.testapp.ActivityThree");
        mActivities.put("ActivityFour", "com.example.testapp.ActivityFour");
        mActivities.put("ActivityFive", "com.example.testapp.ActivityFive");
        mActivities.put("ActivitySix", "com.example.testapp.ActivitySix");
        mActivities.put("ActivitySeven", "com.example.testapp.ActivitySeven");
        mActivities.put("ActivityEight", "com.example.testapp.ActivityEight");

        // Get a random entry from the HashMap.
        Object[] crunchifyKeys = mActivities.keySet().toArray();
        Object key = crunchifyKeys[new Random().nextInt(crunchifyKeys.length)];

        Class<?> c = null;
        if(mActivities.get(key) != null) {
            try {
                c = Class.forName(mActivities.get(key));
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        String mActivity = key.toString();
        String strActivityFormat = getResources().getString(R.string.activity_message);
        String strActivityMsg = String.format(strActivityFormat, mActivity);

        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        long[] v = {500,1000};

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle(getResources().getString(R.string.bb_notif_title))
                .setAutoCancel(true)
                .setColor(getResources().getColor(R.color.colorAccent))
                .setContentText(strActivityMsg)
                .setSound(uri)
                .setVibrate(v)
                .setSmallIcon(R.mipmap.ic_launcher);

        Intent mainIntent = new Intent(this, c);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                NOTIFICATION_ID,
                mainIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        builder.setDeleteIntent(EngagementNotificationInitReceiver.getDeleteIntent(this));

        final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, builder.build());
    }
}

EngagementNotificationInitReceiver

public class EngagementNotificationInitReceiver extends WakefulBroadcastReceiver {
    private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
    private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";

    public static void setupAlarm(Context context) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent alarmIntent = getStartPendingIntent(context);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 14);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY , alarmIntent);
    }

    public static void cancelAlarm(Context context) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent alarmIntent = getStartPendingIntent(context);
        alarmManager.cancel(alarmIntent);
    }

    private static long getTriggerAt(Date now) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        //calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
        return calendar.getTimeInMillis();
    }

    private static PendingIntent getStartPendingIntent(Context context) {
        Intent intent = new Intent(context, EngagementNotificationInitReceiver.class);
        intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
        return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    public static PendingIntent getDeleteIntent(Context context) {
        Intent intent = new Intent(context, EngagementNotificationInitReceiver.class);
        intent.setAction(ACTION_DELETE_NOTIFICATION);
        return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Intent serviceIntent = null;
        if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
            Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
            serviceIntent = EngagementNotification.createIntentStartNotificationService(context);
        } else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
            Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
            serviceIntent = EngagementNotification.createIntentDeleteNotification(context);
        }

        if (serviceIntent != null) {
            // Start the service, keeping the device awake while it is launching.
            startWakefulService(context, serviceIntent);
        }
    }
}

EngagementNotificationInit

public class EngagementNotificationInit extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        EngagementNotificationInitReceiver.setupAlarm(context);
    }
}

EngagementNotificationInitReceiver.setupAlarm方法应该确保通知在指定时间每天显示一次。

0 个答案:

没有答案