Anda di halaman 1dari 5

package course.labs.

notificationslab; import import import import import import import import import import import import import import import import import import import java.io.BufferedReader; java.io.BufferedWriter; java.io.FileOutputStream; java.io.IOException; java.io.InputStream; java.io.InputStreamReader; java.io.OutputStreamWriter; java.io.PrintWriter; java.net.URL; android.app.Activity; android.app.Notification; android.app.NotificationManager; android.app.PendingIntent; android.content.BroadcastReceiver; android.content.Context; android.content.Intent; android.os.AsyncTask; android.util.Log; android.widget.RemoteViews;

public class DownloaderTask extends AsyncTask<String, Void, String[]> { private private private private private private static final int SIM_NETWORK_DELAY = 5000; static final String TAG = "Lab-Notifications"; final int MY_NOTIFICATION_ID = 11151990; String mFeeds[] = new String[3]; MainActivity mParentActivity; Context mApplicationContext;

// Change this variable to false if you do not have a stable network // connection private static final boolean HAS_NETWORK_CONNECTION = false; // 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 InputStreamR eader(inputStream)); } else { inputStream = mApplicationContext.getRes ources() .openRawResource(txtFeed s[idx]); in = new BufferedReader(new InputStreamR eader(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 MainActiv ity // to determine whether the notification is necessary. private void notify(final boolean success) { log("Entered notify()"); final Intent restartMainActivtyIntent = new Intent(mApplicationC ontext, 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_REF RESHED_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 fai led. Please retry Later."; final String successMsg = "Download comp leted successfully."; @Override public void onReceive(Context context, I ntent intent) { log("Entered result receiver's o nReceive() method");

// TODO: Check whether the resul t code is RESULT_OK if (/*change this*/ true) { // TODO: If so, create a PendingIntent using the // restartMainActivityIn tent and set its flags // to FLAG_UPDATE_CURREN T final PendingIntent pend ingIntent = null;

// Uses R.layout.custom_ notification for the // layout of the notific ation View. The xml // file is in res/layout /custom_notification.xml RemoteViews mContentView = new RemoteViews( mApplica tionContext.getPackageName(), R.layout .custom_notification); // TODO: Set the notific ation View's text to // reflect whether or th e download completed // successfully

// TODO: Use the Notific ation.Builder class to // create the Notificati on. You will have to set // several pieces of inf ormation. You can use // android.R.drawable.st at_sys_warning // for the small icon. Y ou should also setAutoCancel(true). Notification.Builder not ificationBuilder = null; // TODO: Send the notifi cation

log("Notification Area N otification sent");

} } }, null, 0, null, null); } // Saves the tweets to a file private void saveTweetsToFile() { PrintWriter writer = null; try { FileOutputStream fos = mApplicationContext.openFileOutpu t( MainActivity.TWEET_FILENAME, Context.MOD E_PRIVATE); writer = new PrintWriter(new BufferedWriter(new OutputSt reamWriter( 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); } }

Anda mungkin juga menyukai