1+ package course .labs .notificationslab ;
2+
3+ import java .io .BufferedReader ;
4+ import java .io .BufferedWriter ;
5+ import java .io .FileOutputStream ;
6+ import java .io .IOException ;
7+ import java .io .InputStream ;
8+ import java .io .InputStreamReader ;
9+ import java .io .OutputStreamWriter ;
10+ import java .io .PrintWriter ;
11+ import java .net .URL ;
12+
13+ import android .app .Activity ;
14+ import android .app .Notification ;
15+ import android .app .NotificationManager ;
16+ import android .app .PendingIntent ;
17+ import android .content .BroadcastReceiver ;
18+ import android .content .Context ;
19+ import android .content .Intent ;
20+ import android .os .AsyncTask ;
21+ import android .util .Log ;
22+ import android .widget .RemoteViews ;
23+
24+ public class DownloaderTask extends AsyncTask <String , Void , String []> {
25+
26+ private static final int SIM_NETWORK_DELAY = 5000 ;
27+ private static final String TAG = "Lab-Notifications" ;
28+ private final int MY_NOTIFICATION_ID = 11151990 ;
29+ private String mFeeds [] = new String [3 ];
30+ private MainActivity mParentActivity ;
31+ private Context mApplicationContext ;
32+
33+ // Change this variable to false if you do not have a stable network
34+ // connection
35+ private static final boolean HAS_NETWORK_CONNECTION = true ;
36+
37+ // Raw feed file IDs used if you do not have a stable connection
38+ public static final int txtFeeds [] = { R .raw .tswift , R .raw .rblack ,
39+ R .raw .lgaga };
40+
41+ // Constructor
42+ public DownloaderTask (MainActivity parentActivity ) {
43+ super ();
44+
45+ mParentActivity = parentActivity ;
46+ mApplicationContext = parentActivity .getApplicationContext ();
47+
48+ }
49+
50+ @ Override
51+ protected String [] doInBackground (String ... urlParameters ) {
52+ log ("Entered doInBackground()" );
53+
54+ return download (urlParameters );
55+
56+ }
57+
58+ private String [] download (String urlParameters []) {
59+
60+ boolean downloadCompleted = false ;
61+
62+ try {
63+
64+ for (int idx = 0 ; idx < urlParameters .length ; idx ++) {
65+
66+ URL url = new URL (urlParameters [idx ]);
67+ try {
68+ Thread .sleep (SIM_NETWORK_DELAY );
69+ } catch (InterruptedException e ) {
70+ e .printStackTrace ();
71+ }
72+
73+ InputStream inputStream ;
74+ BufferedReader in ;
75+
76+ // Alternative for students without
77+ // a network connection
78+ if (HAS_NETWORK_CONNECTION ) {
79+ inputStream = url .openStream ();
80+ in = new BufferedReader (new InputStreamReader (inputStream ));
81+ } else {
82+ inputStream = mApplicationContext .getResources ()
83+ .openRawResource (txtFeeds [idx ]);
84+ in = new BufferedReader (new InputStreamReader (inputStream ));
85+ }
86+
87+ String readLine ;
88+ StringBuffer buf = new StringBuffer ();
89+
90+ while ((readLine = in .readLine ()) != null ) {
91+ buf .append (readLine );
92+ }
93+
94+ mFeeds [idx ] = buf .toString ();
95+
96+ if (null != in ) {
97+ in .close ();
98+ }
99+ }
100+
101+ downloadCompleted = true ;
102+
103+ } catch (IOException e ) {
104+ e .printStackTrace ();
105+ }
106+
107+ log ("Tweet Download Completed:" + downloadCompleted );
108+
109+ notify (downloadCompleted );
110+
111+ return mFeeds ;
112+
113+ }
114+
115+ // Call back to the MainActivity to update the feed display
116+
117+ @ Override
118+ protected void onPostExecute (String [] result ) {
119+ super .onPostExecute (result );
120+
121+ if (mParentActivity != null ) {
122+ mParentActivity .setRefreshed (result );
123+ }
124+
125+ }
126+
127+ // If necessary, notifies the user that the tweet downloads are complete.
128+ // Sends an ordered broadcast back to the BroadcastReceiver in MainActivity
129+ // to determine whether the notification is necessary.
130+
131+ private void notify (final boolean success ) {
132+ log ("Entered notify()" );
133+
134+ final Intent restartMainActivtyIntent = new Intent (mApplicationContext ,
135+ MainActivity .class );
136+ restartMainActivtyIntent .setFlags (Intent .FLAG_ACTIVITY_NEW_TASK );
137+
138+ if (success ) {
139+
140+ // Save tweets to a file
141+ saveTweetsToFile ();
142+
143+ }
144+
145+ // Sends an ordered broadcast to determine whether MainActivity is
146+ // active and in the foreground. Creates a new BroadcastReceiver
147+ // to receive a result indicating the state of MainActivity
148+
149+ // The Action for this broadcast Intent is MainActivity.DATA_REFRESHED_ACTION
150+ // The result Activity.RESULT_OK, indicates that MainActivity is active and
151+ // in the foreground.
152+
153+ mApplicationContext .sendOrderedBroadcast (
154+ new Intent (MainActivity .DATA_REFRESHED_ACTION ),
155+ null ,
156+ new BroadcastReceiver () {
157+
158+ final String failMsg = "Download has failed. Please retry Later." ;
159+ final String successMsg = "Download completed successfully." ;
160+
161+ @ Override
162+ public void onReceive (Context context , Intent intent ) {
163+
164+ log ("Entered result receiver's onReceive() method" );
165+
166+ // TODO: Check whether the result code is RESULT_OK
167+
168+ if (/*change this*/ true ) {
169+
170+ // TODO: If so, create a PendingIntent using the
171+ // restartMainActivityIntent and set its flags
172+ // to FLAG_UPDATE_CURRENT
173+
174+ final PendingIntent pendingIntent = null ;
175+
176+
177+
178+ // Uses R.layout.custom_notification for the
179+ // layout of the notification View. The xml
180+ // file is in res/layout/custom_notification.xml
181+
182+ RemoteViews mContentView = new RemoteViews (
183+ mApplicationContext .getPackageName (),
184+ R .layout .custom_notification );
185+
186+ // TODO: Set the notification View's text to
187+ // reflect whether or the download completed
188+ // successfully
189+
190+
191+
192+ // TODO: Use the Notification.Builder class to
193+ // create the Notification. You will have to set
194+ // several pieces of information. You can use
195+ // android.R.drawable.stat_sys_warning
196+ // for the small icon. You should also setAutoCancel(true).
197+
198+ Notification .Builder notificationBuilder = null ;
199+
200+ // TODO: Send the notification
201+
202+
203+
204+ log ("Notification Area Notification sent" );
205+ }
206+ }
207+ },
208+ null ,
209+ 0 ,
210+ null ,
211+ null );
212+ }
213+
214+ // Saves the tweets to a file
215+ private void saveTweetsToFile () {
216+ PrintWriter writer = null ;
217+ try {
218+ FileOutputStream fos = mApplicationContext .openFileOutput (
219+ MainActivity .TWEET_FILENAME , Context .MODE_PRIVATE );
220+ writer = new PrintWriter (new BufferedWriter (new OutputStreamWriter (
221+ fos )));
222+
223+ for (String s : mFeeds ) {
224+ writer .println (s );
225+ }
226+ } catch (IOException e ) {
227+ e .printStackTrace ();
228+ } finally {
229+ if (null != writer ) {
230+ writer .close ();
231+ }
232+ }
233+ }
234+
235+ // Simplified log output method
236+ private void log (String msg ) {
237+ try {
238+ Thread .sleep (500 );
239+ } catch (InterruptedException e ) {
240+ e .printStackTrace ();
241+ }
242+ Log .i (TAG , msg );
243+ }
244+
245+ }
0 commit comments