Java tutorial
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.online.fullsail; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Environment; import android.support.v4.app.NotificationCompat; import android.util.DisplayMetrics; import android.view.WindowManager; import android.widget.ProgressBar; import android.widget.RemoteViews; @SuppressLint("Instantiatable") public class SaveWebMedia extends AsyncTask<String, Integer, File> { private File externalData; private NotificationManager mNM; Notification notification; ProgressBar progressBar; SharedPreferences mPrefs; int totalSize; Context context; int timestamp = (int) System.currentTimeMillis(); SaveWebMedia(Context context) { this.context = context; mNM = (NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { externalData = context.getExternalFilesDir(null); } else { externalData = new File(Environment.getExternalStorageDirectory(), "/FullSailMobile"); if (!externalData.mkdirs()) { externalData.mkdirs(); } } } // Use a resourceId as an unique identifier // This class definition states that DownloadImageTask will take String // parameters, publish Integer progress updates, and return a Bitmap @Override protected File doInBackground(String... paths) { String exportfile = paths[0].substring(paths[0].lastIndexOf('/') + 1, paths[0].length()); String vDownload = externalData + "/" + exportfile; File downFile = null; try { // set the download URL of the file to be downloaded URL url = new URL(paths[0]); // create the new connection HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestMethod("GET"); urlConnection.setRequestProperty("Connection", "Keep-Alive"); // and connect! urlConnection.connect(); // set the path where we want to save the file File SDCardRoot = Environment.getExternalStorageDirectory(); // create a new file, with specified path and name downFile = new File(SDCardRoot, vDownload); // this will be used to write the downloaded data // into the file // we created FileOutputStream fileOutput = new FileOutputStream(downFile); // this will be used in reading the data from the // internet InputStream inputStream = urlConnection.getInputStream(); // this is the total size of the file int totalSize = urlConnection.getContentLength(); // variable to store total downloaded bytes int downloadedSize = 0; // create a buffer... byte[] buffer = new byte[1024]; int bufferLength = 0; // used to store a temporary buffer then // read through the input buffer and write // to the specified output file int priorProgress = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { downloadedSize += bufferLength; int currentSize = (int) (downloadedSize * 100 / totalSize); if (currentSize > priorProgress) { priorProgress = (int) (downloadedSize * 100 / totalSize); publishProgress(currentSize); } fileOutput.write(buffer, 0, bufferLength); } // close the output stream when done fileOutput.close(); inputStream.close(); // catch some possible errors... } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return downFile; // When finished, return the resulting file } @Override protected void onProgressUpdate(Integer... progress) { notification.contentView.setProgressBar(R.id.status_progress, 100, progress[0], false); mNM.notify(timestamp, notification); } @Override protected void onPreExecute() { Intent intent = new Intent(); final PendingIntent pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0); notification = new Notification(R.drawable.icon_notification, "Downloading...", System.currentTimeMillis()); notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT; notification.flags |= Notification.FLAG_NO_CLEAR; notification.contentView = new RemoteViews(this.context.getPackageName(), R.layout.download_notify); notification.contentIntent = pendingIntent; notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon); notification.contentView.setTextViewText(R.id.status_text, "Downloading Content..."); notification.contentView.setProgressBar(R.id.status_progress, 100, 0, false); mNM.notify(timestamp, notification); } @Override protected void onPostExecute(File download) { String fileString = download.toString(); mNM.cancel(timestamp); System.gc(); String fileName = fileString.substring(fileString.lastIndexOf('/') + 1, fileString.length()); String fileExt = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length()); File downFile = new File(externalData, fileName); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(downFile), "application/" + fileExt); List<ResolveInfo> intents = this.context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (intents == null || intents.size() == 0) { intent.setDataAndType(Uri.fromFile(downFile), "video/" + fileExt); intents = this.context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (intents == null || intents.size() == 0) { intent.setDataAndType(Uri.fromFile(downFile), "image/" + fileExt); intents = this.context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (intents == null || intents.size() == 0) { intent = new Intent(Intent.ACTION_SEARCH); if (Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.ECLAIR) { intent.setPackage("com.android.vending"); } intent.putExtra("query", fileExt); } } } intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent contentIntent = PendingIntent.getActivity(this.context, 0, intent, PendingIntent.FLAG_ONE_SHOT); Notification notification = null; Resources resources = this.context.getResources(); String[] mediaTypes = resources.getStringArray(R.array.media); boolean acceptedType = false; for (int i = 0; i < mediaTypes.length; i++) { if (fileExt.toLowerCase().equals(mediaTypes[i])) { acceptedType = true; } } if (acceptedType) { Bitmap preview = null; String[] videoTypes = resources.getStringArray(R.array.movFiles); for (int i = 0; i < videoTypes.length; i++) { if (fileExt.toLowerCase().equals(videoTypes[i])) { preview = getVideoFrame(fileString); } } String[] imageTypes = resources.getStringArray(R.array.movFiles); for (int i = 0; i < imageTypes.length; i++) { if (fileExt.toLowerCase().equals(imageTypes[i])) { preview = decodeBitmapFile(fileString); } } NotificationCompat.Builder builder = new NotificationCompat.Builder(this.context); builder.setTicker(this.context.getString(R.string.notify_download_complete)) .setWhen(System.currentTimeMillis()) .setContentTitle(this.context.getString(R.string.Document_complete)) .setContentText(this.context.getString(R.string.Pdf_completed, fileName)) .setSmallIcon(R.drawable.icon).setAutoCancel(true).setPriority(Notification.PRIORITY_HIGH) .setContentIntent(contentIntent); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { notification = new NotificationCompat.BigPictureStyle(builder).bigPicture(preview).build(); } else { notification = builder.build(); } } else { NotificationCompat.Builder builder = new NotificationCompat.Builder(this.context); builder.setContentTitle(this.context.getString(R.string.Document_complete)) .setContentText(this.context.getString(R.string.Pdf_completed, fileName)) .setSmallIcon(R.drawable.icon).setAutoCancel(true).setPriority(Notification.PRIORITY_HIGH) .setContentIntent(contentIntent); notification = builder.build(); } notification.flags |= Notification.FLAG_AUTO_CANCEL; mNM.notify(timestamp, notification); } public Bitmap decodeBitmapFile(String filename) { System.gc(); WindowManager wManager = (WindowManager) this.context.getApplicationContext() .getSystemService(Context.WINDOW_SERVICE); DisplayMetrics metrics = new DisplayMetrics(); wManager.getDefaultDisplay().getMetrics(metrics); final float scale = this.context.getResources().getDisplayMetrics().density; int reqWidth = (int) (metrics.widthPixels * scale + 0.5f); int reqHeight = (int) (metrics.heightPixels * scale + 0.5f); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeFile(filename, options); int heightRatio = (int) Math.ceil(options.outHeight / (float) reqHeight); int widthRatio = (int) Math.ceil(options.outWidth / (float) reqWidth); if (heightRatio > 1 || widthRatio > 1) { if (heightRatio > widthRatio) { options.inSampleSize = heightRatio; } else { options.inSampleSize = widthRatio; } } options.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeFile(filename, options); return bitmap; } private Bitmap getVideoFrame(String uri) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { if (Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.GINGERBREAD) { retriever.setDataSource(uri); return retriever.getFrameAtTime(); } else { retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY); retriever.setDataSource(uri); return retriever.captureFrame(); // These items were handled by the custom android media class // Despite being marked errors, they compile without an issue } } catch (IllegalArgumentException ex) { ex.printStackTrace(); } catch (RuntimeException ex) { ex.printStackTrace(); } finally { try { retriever.release(); } catch (RuntimeException ex) { } } return null; } }