Scheduling several alarms with WakefulIntentService

我的梦境 提交于 2019-12-12 02:06:49

问题


I am trying to schedule several alarms to publish posts to twitter. I am not sure of the usage, because i am getting a NullPointerException.

i have a list with posts and i would like to post them to twitter, so this is what i did. In the scheduleAlarms method of WakefulIntentService class i have a for loop iterating over the posts List and adding a post object to the putExtra method:

public static void scheduleAlarms(AlarmListener listener, Context ctxt,
        boolean force) {
    SharedPreferences prefs = ctxt.getSharedPreferences(NAME, 0);
    long lastAlarm = prefs.getLong(LAST_ALARM, 0);

    if (lastAlarm == 0
            || force
            || (System.currentTimeMillis() > lastAlarm && System
                    .currentTimeMillis() - lastAlarm > listener.getMaxAge())) {
        AlarmManager mgr = (AlarmManager) ctxt
                .getSystemService(Context.ALARM_SERVICE);
        for (Iterator<Post> iterator = AlarmActivity.posts.iterator(); iterator
                .hasNext();) {
            Post post = (Post) iterator.next();

            Intent i = new Intent(ctxt, AlarmReceiver.class);
            i.putExtra("post", post);
            PendingIntent pi = PendingIntent.getBroadcast(ctxt,
                    (int) post.getId(), i, 0);
            listener.scheduleAlarms(mgr, pi, ctxt);
        }

    }
}

Then in my AppService doWakefulWork method i get the Parcelable post object but i am getting a nullpointerexception:

@Override
protected void doWakefulWork(Intent intent) {
    Log.i("AppService", "I'm awake! I'm awake! (yawn)");
    Post post = intent.getParcelableExtra("post");
    System.out.println("- " + post.getPost());
}

Is this the right way of doing what i want to achieve?

Thanks in advance


回答1:


the NullPointerException states that intent.getParcelableExtra("post") is null.

My guess is that your BroadcastReceiver is not forwarding along your post extra to the service as part of its call to sendWakefulWork().

Is this the right way of doing what i want to achieve?

Probably not, as you will only send one post, ignoring all the rest, and you will not even do that correctly if the user powers off or reboots their device.

Use one scheduled alarm with one PendingIntent. Since your posts need to be in a persistent data store, have the WakefulIntentService load the posts to send from the data store. Eliminate all extras from the PendingIntent, as they are no longer needed and cannot readily be reconstituted in case of a power-off or reboot event.



来源:https://stackoverflow.com/questions/14704824/scheduling-several-alarms-with-wakefulintentservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!