在android中定期获取/更新和比较数据?

时间:2014-07-27 14:15:30

标签: android

我正在创建一个Android应用程序,它从天气api获取当地天气预报以及北极光的推特更新并将两者相关联。我想知道,即使用户没有在他们的设备上打开应用程序,对我来说,不断更新数据并进行比较的最佳方式是什么?所以基本上我希望我的应用程序在后台运行。任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

您想要定期重复的任务可以在IntentService中实现。

public class MyService extends IntentService {

    public MyService () {
        super("MyService ");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        new MyTask().execute();
        Log.d("MyService", "About to execute MyTask");
    }

    private class MyTask extends AsyncTask<String, Void, Boolean> {
        @Override
        protected Boolean doInBackground(String... strings) {
            Log.d("MyService", "Calling doInBackground within MyTask");
            return false;
        }
    }
}

您需要通过AlarmManager设置定期警报,以便您决定何时使用PendingIntent启动IntentService;例如,在活动中:

...
int interval =10*1000;//every 10 seconds
AlarmManager alarm = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);

Intent alarmIntent = new Intent(this, MyAlarmReceiver.class);
PendingIntent pendingIntent =PendingIntent.getBroadcast(this, 0, alarmIntent, 0);

alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 
                          interval, pendingIntent);
...

PendingIntent将被发送到收听警报的BroadcastReceiver:

public class MyAlarmReceiver extends BroadcastReceiver {
    public MyAlarmReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent serviceIntent = new Intent(context, MyService.class);
        context.startService(serviceIntent);
        Log.d("MyAlarmReceiver", "Called context.startService");
    }
}

每次关闭手机时,您设置的闹钟会自动取消,因此您需要BroadcastReceiver监听boot_completed e再次设置闹钟:

public class MyBootReceiver extends BroadcastReceiver {

    public MyBootReceiver() {
    }

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

        Log.d("MyBootReceiver ", "Boot completed");
        int interval =10*1000;//every 10 second
        AlarmManager alarm = 
           (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

        Intent alarmIntent = new Intent(context, MyAlarmReceiver.class);
        PendingIntent pendingIntent = 
            PendingIntent.getBroadcast(context, 0, alarmIntent, 0);

        alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, 
                                  System.currentTimeMillis(), 
                                  interval, pendingIntent);
    }
}

在AndroidManifest.xml中,您需要为BroadcastReceiver添加RECEIVE_BOOT_COMPLETED权限和BOOT_COMPLETED intent-filter:

<application ...>
    ...
    <receiver
    android:name=".services.MyBootReceiver"
    android:enabled="true"
    android:exported="true" >
    <intent-filter android:priority="500" >
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
    </receiver>
    ...
</application>
...
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

更多细节here