Android Open Source - UTHPortal-Android-Gradle Data Sync Service






From Project

Back to project page UTHPortal-Android-Gradle.

License

The source code is released under:

MIT License

If you think the Android project UTHPortal-Android-Gradle listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.uth.uthportal.service;
/*w  ww  .j ava2  s .  c o m*/


import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.uth.uthportal.MainScreen;
import com.uth.uthportal.R;
import com.uth.uthportal.buffers.FileOperation;
import com.uth.uthportal.buffers.SettingsManager;
import com.uth.uthportal.collections.Settings;
import com.uth.uthportal.network.ApiLinks;
import com.uth.uthportal.network.JSONDownloader;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.util.Log;
/**
 * Background IntentService is used to download and parse
 * information, in scheduled intervals.
 * Also provides notifications when new Announcements
 * appear.
 * To communicate with our main thread we use Message
 * Broadcasting logic.
 * @author GeorgeT
 *
 */
public class DataSyncService extends IntentService {
  public DataSyncService() {
    super("UTHRefreshService");
  }
  //Parameters
  public static final String PARAM_RESULT = "wasSuccessful";
    public static final String PARAM_ITEM = "item";
    public static final String PARAM_ERROR = "errorMsg";
    public static final String PARAM_TYPE = "itemType";
    public static final String PARAM_NOTIFICATION_TYPE = "notifyType";
    public static final String ACTION_RESP =
            "com.uth.uthportal.intent.action.MESSAGE_PROCESSED"; //used to identificate our intent

    //Types
    public static final String TYPE_COURSES = "coursesList";
    public static final String TYPE_FOOD = "food";
    public static final String TYPE_DEPARTMENT = "depart";

    //Notifications
    //public static final int NOTIFY_INFO = 0;
    public static final int NOTIFY_GEN = 2;
    public static final int NOTIFY_COURSE = 1;
    public static final int NOTIFY_FOOD = 3;
    //public static final int NOTIFY_ERROR = 4;
    public static final String NOTIFY_INTENT =
            "com.uth.uthportal.intent.action.NOTIFICATION_CLICKED";
    //!-----------

    Settings settings;
  
  @Override
  protected void onHandleIntent(Intent intent) {
    settings = SettingsManager.loadSettings(this);//load settings or get default
    
    //find out if user wants us to auto-refresh
    if(settings.autoRefresh){
      ScheduleNextUpdate();
    }
    
    manageLocalCourses(downloadCourses());
    getFood();
    getGeneralAnn();

    stopSelf(); //stop this instance.
  }

  private void getGeneralAnn(){
        //Try to download
    String annDownloadedBuffer = JSONDownloader.getJSON(ApiLinks.getGeneralAnnLink());

    FileOperation fOperation = new FileOperation("GeneralAnn",this);
        String annLocalBuffer = fOperation.LoadFromPrivate(); // try to load from local


    if(annDownloadedBuffer != null && !annDownloadedBuffer .equals("")) {
            //we got download
            if (!annDownloadedBuffer.equals(annLocalBuffer)) {
                //If the downloaded buffer is different than the local buffer, we go new announcements
                //Save the new buffer
                fOperation.SaveToPrivate(annDownloadedBuffer);
                //Notify the user
                Notify("UTH Portal", getResources().getString(R.string.notify_new_ann), NOTIFY_GEN);
                // Send data to main screen
                broadCastSuccess(TYPE_DEPARTMENT, annDownloadedBuffer);

                return;
            }
        }

        //we got no download
    if ( !(annLocalBuffer  != null && !annLocalBuffer.equals("")) ) {
        // local was non-existent or empty
        Log.i("UTH Portal","General announcements archived data was empty!");
        return;
    }
        broadCastSuccess(TYPE_DEPARTMENT, annLocalBuffer); //Send local data to main screen
  }
  
  private void getFood(){
        //Try to download
        String foodDownloadedBuffer = JSONDownloader.getJSON(ApiLinks.getFoodLink());

        FileOperation fOperation = new FileOperation("Food",this);
        String foodLocalBuffer = fOperation.LoadFromPrivate(); // try to load from local


        if(foodDownloadedBuffer != null && !foodDownloadedBuffer.equals("")) {
            //we got download
            if (!foodDownloadedBuffer.equals(foodLocalBuffer)) {
                //If the downloaded buffer is different than the local buffer, we go new announcements
                //Save the new buffer
                fOperation.SaveToPrivate(foodDownloadedBuffer);
                //Notify the user
                Notify("UTH Portal", getResources().getString(R.string.notify_new_menu), NOTIFY_FOOD);
                // Send data to main screen
                broadCastSuccess(TYPE_FOOD, foodDownloadedBuffer);

                return;
            }
        }

        //we got no download
        if ( !(foodLocalBuffer != null && !foodLocalBuffer.equals("")) ) {
            // local was non-existent or empty
            Log.i("UTH Portal","Food archived data was empty!");
            return;
        }
        broadCastSuccess(TYPE_FOOD, foodLocalBuffer); //Send local data to main screen
  }

  private void manageLocalCourses(HashMap<String,String> downloadMap){
    List<String> coursesBuffersList = new ArrayList<String>();
        String newCourses = "";
    
    for (String course : settings.courses) {
      //attempt to load file
      FileOperation fop = new FileOperation(course,this);
      String downloadedContent = downloadMap.get(course);
      String localContent =  fop.LoadFromPrivate();//get local content for course

      if(downloadedContent != null && !downloadedContent.equals("") ) {
                Log.d("Course downloaded", course);
                //we got download
                if (!downloadedContent.equals(localContent)) {
                    // We got new course announcements
                    fop.SaveToPrivate(downloadedContent); //save our download
                    //Notify the user
                    newCourses += course + ", ";
                    //Add to buffers list
                    coursesBuffersList.add(downloadedContent);
                    // Check next course
                    continue;
                }
            }

            //we got no download
            if( !(localContent != null && !localContent.equals("")) ) {
                // local was non-existent or empty
                Log.i("UTH Portal","No archived data for course: " + course);
                continue;
            }
            coursesBuffersList.add(localContent); //try to replace with local content
    }
    
    Log.d("Courses Count", String.valueOf(coursesBuffersList.size()));

    if(coursesBuffersList.size()>0 && coursesBuffersList.get(0).length()>1){
            if ( !newCourses.equals("") ) {
                newCourses = newCourses.substring(0,newCourses.length() - 2); // remove last comma/space
                Notify("UTHPortal",getResources().getString(R.string.notify_new_course) +" "+ newCourses, NOTIFY_COURSE);
            }
      broadCastSuccess(TYPE_COURSES, (Serializable)coursesBuffersList);
    } else {
            Log.i("UTHPortal","Courses archived data was empty!");
    }
  }
  private HashMap<String,String> downloadCourses(){
    HashMap<String,String> linksMap = ApiLinks.getCoursesLinks(settings.courses); //get links
    HashMap<String,String> downloadMap = new HashMap<String,String>();
    String link;
    String json;

    for(String course : settings.courses){
      link = linksMap.get(course);
      json = JSONDownloader.getJSON(link);
      if(json != null){
        downloadMap.put(course,json); //operation successful
      }else {
        downloadMap.put(course,""); // operation failed.
      }
    }
    return downloadMap;
  }

    /*
  private void broadCastFail(String errorMsg){
    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction(ACTION_RESP);
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra(PARAM_RESULT,false); //default to error
    broadcastIntent.putExtra(PARAM_ERROR, errorMsg);//the error
    sendBroadcast(broadcastIntent);
  }
  */

  private void broadCastSuccess(String itemType, Serializable item){
    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction(ACTION_RESP);
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra(PARAM_RESULT, true); //default success
    broadcastIntent.putExtra(PARAM_TYPE, itemType);//the item's type
    broadcastIntent.putExtra(PARAM_ITEM, item); //send the actual item
    sendBroadcast(broadcastIntent);
  }
  private void ScheduleNextUpdate()
    {
      Intent intent = new Intent(this, this.getClass());
      PendingIntent pendingIntent =
          PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

      long currentTimeMs = System.currentTimeMillis();
      long nextUpdateTimeMs = currentTimeMs + settings.refreshInterval * DateUtils.MINUTE_IN_MILLIS; //add interval
      
      Time nextUpdateTime = new Time();
      nextUpdateTime.set(nextUpdateTimeMs);
      
      AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
      alarmManager.set(AlarmManager.RTC, nextUpdateTimeMs, pendingIntent); //schedule next
    }
  private void Notify(String title, String text, int notifyType){
        //User has notifications disabled
        if (!settings.notify)
            return;

    //Notification logic.
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(title)
            .setContentText(text);

        //mBuilder.setAutoCancel(true);

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(this, MainScreen.class);
        resultIntent.setAction(NOTIFY_INTENT);
        resultIntent.putExtra(PARAM_NOTIFICATION_TYPE, notifyType);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(MainScreen.class);

    // Adds the Intent that starts the Activity to the top of the stack
        // We have to generate a unique id for our request
        // For some reason FLAG_UPDATE_CURRENT won't work.
    stackBuilder.addNextIntent(resultIntent);
        int iUniqueId = (int) (System.currentTimeMillis() & 0xfffffff);
        PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(iUniqueId, 0);
    mBuilder.setContentIntent(resultPendingIntent);

    NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(notifyType, mBuilder.build());
  }

    /*
  private boolean isNetworkAvailable() {
    //used to determine if we are connected to the internet.
    //TODO: Check if we are on Mobile data or WIFI
      ConnectivityManager connectivityManager 
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
      return activeNetworkInfo != null && activeNetworkInfo.isConnected();
  }*/
}




Java Source Code List

com.uth.uthportal.AboutScreen.java
com.uth.uthportal.CoursesFragment.java
com.uth.uthportal.DepartmentFragment.java
com.uth.uthportal.FoodFragment.java
com.uth.uthportal.MainScreen.java
com.uth.uthportal.SettingsScreen.java
com.uth.uthportal.adapter.AdapterManager.java
com.uth.uthportal.adapter.AdapterProvider.java
com.uth.uthportal.adapter.ExpandableListAdapter.java
com.uth.uthportal.adapter.SettingsAdapter.java
com.uth.uthportal.adapter.TabsPagerAdapter.java
com.uth.uthportal.buffers.AvailableCoursesParser.java
com.uth.uthportal.buffers.CoursesParser.java
com.uth.uthportal.buffers.FileOperation.java
com.uth.uthportal.buffers.FoodParser.java
com.uth.uthportal.buffers.GeneralAnnParser.java
com.uth.uthportal.buffers.SettingsManager.java
com.uth.uthportal.collections.AnnItem.java
com.uth.uthportal.collections.Announcements.java
com.uth.uthportal.collections.AvailableCourse.java
com.uth.uthportal.collections.CourseInfo.java
com.uth.uthportal.collections.Course.java
com.uth.uthportal.collections.DayMenu.java
com.uth.uthportal.collections.DefaultIntervals.java
com.uth.uthportal.collections.Dish.java
com.uth.uthportal.collections.Food.java
com.uth.uthportal.collections.GeneralAnnouncement.java
com.uth.uthportal.collections.Settings.java
com.uth.uthportal.network.ApiLinks.java
com.uth.uthportal.network.AppRater.java
com.uth.uthportal.network.AsyncJSONDownloader.java
com.uth.uthportal.network.JSONDownloader.java
com.uth.uthportal.service.DataSyncService.java
com.uth.uthportal.util.SystemUiHiderBase.java
com.uth.uthportal.util.SystemUiHiderHoneycomb.java
com.uth.uthportal.util.SystemUiHider.java