Home | History | Annotate | Download | only in scheduler
      1 package com.example.android.scheduler;
      2 
      3 import android.app.IntentService;
      4 import android.app.NotificationManager;
      5 import android.app.PendingIntent;
      6 import android.content.Context;
      7 import android.content.Intent;
      8 import android.support.v4.app.NotificationCompat;
      9 import android.util.Log;
     10 
     11 import java.io.BufferedReader;
     12 import java.io.IOException;
     13 import java.io.InputStream;
     14 import java.io.InputStreamReader;
     15 import java.net.HttpURLConnection;
     16 import java.net.URL;
     17 
     18 /**
     19  * This {@code IntentService} does the app's actual work.
     20  * {@code SampleAlarmReceiver} (a {@code WakefulBroadcastReceiver}) holds a
     21  * partial wake lock for this service while the service does its work. When the
     22  * service is finished, it calls {@code completeWakefulIntent()} to release the
     23  * wake lock.
     24  */
     25 public class SampleSchedulingService extends IntentService {
     26     public SampleSchedulingService() {
     27         super("SchedulingService");
     28     }
     29 
     30     public static final String TAG = "Scheduling Demo";
     31     // An ID used to post the notification.
     32     public static final int NOTIFICATION_ID = 1;
     33     // The string the app searches for in the Google home page content. If the app finds
     34     // the string, it indicates the presence of a doodle.
     35     public static final String SEARCH_STRING = "doodle";
     36     // The Google home page URL from which the app fetches content.
     37     // You can find a list of other Google domains with possible doodles here:
     38     // http://en.wikipedia.org/wiki/List_of_Google_domains
     39     public static final String URL = "http://www.google.com";
     40     private NotificationManager mNotificationManager;
     41     NotificationCompat.Builder builder;
     42 
     43     @Override
     44     protected void onHandleIntent(Intent intent) {
     45         // BEGIN_INCLUDE(service_onhandle)
     46         // The URL from which to fetch content.
     47         String urlString = URL;
     48 
     49         String result ="";
     50 
     51         // Try to connect to the Google homepage and download content.
     52         try {
     53             result = loadFromNetwork(urlString);
     54         } catch (IOException e) {
     55             Log.i(TAG, getString(R.string.connection_error));
     56         }
     57 
     58         // If the app finds the string "doodle" in the Google home page content, it
     59         // indicates the presence of a doodle. Post a "Doodle Alert" notification.
     60         if (result.indexOf(SEARCH_STRING) != -1) {
     61             sendNotification(getString(R.string.doodle_found));
     62             Log.i(TAG, "Found doodle!!");
     63         } else {
     64             sendNotification(getString(R.string.no_doodle));
     65             Log.i(TAG, "No doodle found. :-(");
     66         }
     67         // Release the wake lock provided by the BroadcastReceiver.
     68         SampleAlarmReceiver.completeWakefulIntent(intent);
     69         // END_INCLUDE(service_onhandle)
     70     }
     71 
     72     // Post a notification indicating whether a doodle was found.
     73     private void sendNotification(String msg) {
     74         mNotificationManager = (NotificationManager)
     75                this.getSystemService(Context.NOTIFICATION_SERVICE);
     76 
     77         PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
     78             new Intent(this, MainActivity.class), 0);
     79 
     80         NotificationCompat.Builder mBuilder =
     81                 new NotificationCompat.Builder(this)
     82         .setSmallIcon(R.drawable.ic_launcher)
     83         .setContentTitle(getString(R.string.doodle_alert))
     84         .setStyle(new NotificationCompat.BigTextStyle()
     85         .bigText(msg))
     86         .setContentText(msg);
     87 
     88         mBuilder.setContentIntent(contentIntent);
     89         mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
     90     }
     91 
     92 //
     93 // The methods below this line fetch content from the specified URL and return the
     94 // content as a string.
     95 //
     96     /** Given a URL string, initiate a fetch operation. */
     97     private String loadFromNetwork(String urlString) throws IOException {
     98         InputStream stream = null;
     99         String str ="";
    100 
    101         try {
    102             stream = downloadUrl(urlString);
    103             str = readIt(stream);
    104         } finally {
    105             if (stream != null) {
    106                 stream.close();
    107             }
    108         }
    109         return str;
    110     }
    111 
    112     /**
    113      * Given a string representation of a URL, sets up a connection and gets
    114      * an input stream.
    115      * @param urlString A string representation of a URL.
    116      * @return An InputStream retrieved from a successful HttpURLConnection.
    117      * @throws IOException
    118      */
    119     private InputStream downloadUrl(String urlString) throws IOException {
    120 
    121         URL url = new URL(urlString);
    122         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    123         conn.setReadTimeout(10000 /* milliseconds */);
    124         conn.setConnectTimeout(15000 /* milliseconds */);
    125         conn.setRequestMethod("GET");
    126         conn.setDoInput(true);
    127         // Start the query
    128         conn.connect();
    129         InputStream stream = conn.getInputStream();
    130         return stream;
    131     }
    132 
    133     /**
    134      * Reads an InputStream and converts it to a String.
    135      * @param stream InputStream containing HTML from www.google.com.
    136      * @return String version of InputStream.
    137      * @throws IOException
    138      */
    139     private String readIt(InputStream stream) throws IOException {
    140 
    141         StringBuilder builder = new StringBuilder();
    142         BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
    143         for(String line = reader.readLine(); line != null; line = reader.readLine())
    144             builder.append(line);
    145         reader.close();
    146         return builder.toString();
    147     }
    148 }
    149