Android:重复的HTTP请求

时间:2016-11-04 15:46:23

标签: android

重复HTTP请求的最简单方法是什么(即每45分钟一次)? 我不想使用任何推送通知 我已经尝试过AlarmManager,但它没有用。

Forground Service可能是一种很好的方式,但它可能会耗费太多电池。

1 个答案:

答案 0 :(得分:0)

从MainActivity中调用此metod:

private void setNotifyAlarm() {
        long _alarm;
        Calendar now = Calendar.getInstance();
        Calendar wakeupcall = Calendar.getInstance();
        wakeupcall.setTimeInMillis(System.currentTimeMillis());
        wakeupcall.set(Calendar.HOUR_OF_DAY, 15);
        wakeupcall.set(Calendar.MINUTE, 30);

        if (wakeupcall.getTimeInMillis() <= now.getTimeInMillis())
            _alarm=wakeupcall.getTimeInMillis() + (AlarmManager.INTERVAL_DAY+1);
        else
            _alarm=wakeupcall.getTimeInMillis();


        al = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        notif= new Intent(this,NotifyService.class);
        fintent = PendingIntent.getService(this,0,notif,0);
        al.setRepeating(AlarmManager.RTC_WAKEUP,_alarm,"45 minutes in Miliseconds", fintent);

为http requuest创建服务:NotifyService.java

public class NotifyService extends Service {


    private NotificationManager mNotificationManager;
    PowerManager powerManager;
    PowerManager.WakeLock wakeLock;

    @Override
    public void onCreate() {
        super.onCreate();
        powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NOTIFY");

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void handleSERVICE(Intent intent){
        new NotifyTASK().execute();
    }

    private class NotifyTASK extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {
            {
            DO your HTTP CALLS

            }
            stopSelf();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        wakeLock.acquire();
        handleSERVICE(intent);
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        wakeLock.release();
    }
}

现在在Manifest文件中添加:

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

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

此代码以指定的时间间隔启动服务。 希望这对您有所帮助,如果您需要更多代码,请告诉我。