summaryrefslogtreecommitdiffstats
path: root/Android/06-Notifications/Notifications/src/course/labs/notificationslab/DownloaderTask.java
blob: 655d93a0230db79edaad7b1622d09179da00c4f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package course.labs.notificationslab;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.RemoteViews;

public class DownloaderTask extends AsyncTask<String, Void, String[]> {

    private static final int SIM_NETWORK_DELAY = 5000;
    private static final String TAG = "Lab-Notifications";
    private final int MY_NOTIFICATION_ID = 11151990;
    private String mFeeds[] = new String[3];
    private MainActivity mParentActivity;
    private Context mApplicationContext;

    // Change this variable to false if you do not have a stable network
    // connection
    private static final boolean HAS_NETWORK_CONNECTION = true;

    // Raw feed file IDs used if you do not have a stable connection
    public static final int txtFeeds[] = { R.raw.tswift, R.raw.rblack, R.raw.lgaga };

    // Constructor
    public DownloaderTask(MainActivity parentActivity) {
        super();
        mParentActivity = parentActivity;
        mApplicationContext = parentActivity.getApplicationContext();
    }

    @Override
    protected String[] doInBackground(String... urlParameters) {
        log("Entered doInBackground()");
        return download(urlParameters);
    }

    private String[] download(String urlParameters[]) {

        boolean downloadCompleted = false;

        try {

            for (int idx = 0; idx < urlParameters.length; idx++) {

                URL url = new URL(urlParameters[idx]);
                try {
                    Thread.sleep(SIM_NETWORK_DELAY);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                InputStream inputStream;
                BufferedReader in;

                // Alternative for students without
                // a network connection
                if (HAS_NETWORK_CONNECTION) {
                    inputStream = url.openStream();
                    in = new BufferedReader(new InputStreamReader(inputStream));
                } else {
                    inputStream = mApplicationContext.getResources().openRawResource(txtFeeds[idx]);
                    in = new BufferedReader(new InputStreamReader(inputStream));
                }

                String readLine;
                StringBuffer buf = new StringBuffer();

                while ((readLine = in.readLine()) != null) {
                    buf.append(readLine);
                }

                mFeeds[idx] = buf.toString();

                if (null != in) {
                    in.close();
                }
            }

            downloadCompleted = true;

        } catch (IOException e) {
            e.printStackTrace();
        }

        log("Tweet Download Completed:" + downloadCompleted);

        notify(downloadCompleted);

        return mFeeds;
    }

    // Call back to the MainActivity to update the feed display
    @Override
    protected void onPostExecute(String[] result) {
        super.onPostExecute(result);

        if (mParentActivity != null) {
            mParentActivity.setRefreshed(result);
        }

    }

    // If necessary, notifies the user that the tweet downloads are complete.
    // Sends an ordered broadcast back to the BroadcastReceiver in MainActivity
    // to determine whether the notification is necessary.
    private void notify(final boolean success) {
        log("Entered notify()");
        final Intent restartMainActivtyIntent = new Intent(mApplicationContext, MainActivity.class);
        restartMainActivtyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (success) {
            // Save tweets to a file
            saveTweetsToFile();
        }

        // Sends an ordered broadcast to determine whether MainActivity is
        // active and in the foreground. Creates a new BroadcastReceiver
        // to receive a result indicating the state of MainActivity

        // The Action for this broadcast Intent is MainActivity.DATA_REFRESHED_ACTION
        // The result Activity.RESULT_OK, indicates that MainActivity is active and
        // in the foreground.
        mApplicationContext.sendOrderedBroadcast(
                new Intent(MainActivity.DATA_REFRESHED_ACTION), null, new BroadcastReceiver() {

                    final String failMsg = "Download has failed. Please retry Later.";
                    final String successMsg = "Download completed successfully.";

                    @Override
                    public void onReceive(Context context, Intent intent) {

                        log("Entered result receiver's onReceive() method");

                        if (getResultCode() == Activity.RESULT_OK) {

                            final PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                            // Uses R.layout.custom_notification for the
                            // layout of the notification View. The xml
                            // file is in res/layout/custom_notification.xml
                            RemoteViews mContentView = new RemoteViews(
                                    mApplicationContext.getPackageName(),
                                    R.layout.custom_notification);

                            mContentView.setTextViewText(R.id.text, successMsg);

                            Notification.Builder notificationBuilder = new Notification.Builder(context);
                            notificationBuilder.setContentIntent(pendingIntent);
                            notificationBuilder.setContent(mContentView);
                            notificationBuilder.setSmallIcon(android.R.drawable.stat_sys_warning);
                            notificationBuilder.setAutoCancel(true);

                            log("Notification Area Notification sent");
                        }
                    }
                }, null, 0, null, null);
    }

    // Saves the tweets to a file
    private void saveTweetsToFile() {
        PrintWriter writer = null;
        try {
            FileOutputStream fos = mApplicationContext.openFileOutput(
                    MainActivity.TWEET_FILENAME, Context.MODE_PRIVATE);
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                            fos)));

            for (String s : mFeeds) {
                writer.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != writer) {
                writer.close();
            }
        }
    }

    // Simplified log output method
    private void log(String msg) {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.i(TAG, msg);
    }
}