2016-09-23 164 views
-5

我正在寫一個android應用程序,需要從服務器獲取數據。 如何在每次下載所有數據時知道數據是否發生變化?移動應用程序和服務器

你認爲依靠日期和時間會工作嗎?我的意思是: 如果服務器告訴應用程序更新的最後一次是在11.00 和當前時間是11.01,這意味着有更新{服務器還告訴我已經作出具體是什麼更新 } 否則沒有更新

回答

0

您可以使用一個待處理的意圖以及報警管理器和廣播接收器來實現此功能。

例如,你可以發送一個簡單的請求,比如說「請求A」來獲得服務器的響應。在服務器端,如果數據已更改,則響應將爲「true」,否則爲「false」。

現在,如果您將響應設爲false,則無需下載完整的數據。如果迴應是真的,應用程序應該開始下載數據,然後刷新內容。

你可以在說出「四小時」後設置你的等待意圖。因此,在四個小時後,請求將被髮送,您將收到回覆。其次,您必須設置鬧鐘管理器並重復設置,以便每四小時發送一次請求。

您還需要一個廣播接收器來接收廣播。在BroadcastReceiver的onReceive中,您需要檢查響應並根據它來刷新數據(如果它是真的)。

法火未決的意圖每隔四個小時:

public void scheduleAlarmForDataDownload() { 
     Long time = new GregorianCalendar().getTimeInMillis()+1000 * 60 * 60 * 4;// current time + 4 Hrs 
     Intent intent = new Intent(this, AlarmReceiver.class); 
     PendingIntent intentAlarm = PendingIntent.getBroadcast(this, 0, intent, 0); 
     AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 1000 * 60 * 60 * 4, intentAlarm);// 4 Hrs 
     //Toast.makeText(this, "Alarm Scheduled for 4 Hrs", Toast.LENGTH_LONG).show(); 
    } 

AlarmReceiver類

@Override 
    public void onReceive(Context context, Intent intent) { 
     // method to send a request(Request A) to server and check the response. 
     // If response is true again make a request to download and refresh the app data. 
     // If the response is false do nothing 

    } 
相關問題