From 30d164851ac3d4e7397e010baa24a8e5cb0dc090 Mon Sep 17 00:00:00 2001 From: Joe Robinson Date: Tue, 15 Dec 2015 20:43:45 +0000 Subject: Migrate to IntelliJ format, also contains some minor logging changes and moved libraries --- .../com/lc8n/blauploader/FileArrayAdapter.java | 165 +++++++ .../java/com/lc8n/blauploader/FileBrowser.java | 289 ++++++++++++ .../main/java/com/lc8n/blauploader/FileShare.java | 513 +++++++++++++++++++++ .../main/java/com/lc8n/blauploader/FileUpload.java | 214 +++++++++ .../main/java/com/lc8n/blauploader/HomeScreen.java | 57 +++ .../com/lc8n/blauploader/ProgressInputStream.java | 97 ++++ .../java/com/lc8n/blauploader/SoundRecorder.java | 162 +++++++ .../java/com/lc8n/blauploader/UploadLocation.java | 129 ++++++ app/src/main/java/com/lc8n/util/FileUploader.java | 105 +++++ .../com/lc8n/util/ProgressMultipartEntity.java | 72 +++ 10 files changed, 1803 insertions(+) create mode 100644 app/src/main/java/com/lc8n/blauploader/FileArrayAdapter.java create mode 100644 app/src/main/java/com/lc8n/blauploader/FileBrowser.java create mode 100644 app/src/main/java/com/lc8n/blauploader/FileShare.java create mode 100644 app/src/main/java/com/lc8n/blauploader/FileUpload.java create mode 100644 app/src/main/java/com/lc8n/blauploader/HomeScreen.java create mode 100644 app/src/main/java/com/lc8n/blauploader/ProgressInputStream.java create mode 100644 app/src/main/java/com/lc8n/blauploader/SoundRecorder.java create mode 100644 app/src/main/java/com/lc8n/blauploader/UploadLocation.java create mode 100644 app/src/main/java/com/lc8n/util/FileUploader.java create mode 100644 app/src/main/java/com/lc8n/util/ProgressMultipartEntity.java (limited to 'app/src/main/java/com') diff --git a/app/src/main/java/com/lc8n/blauploader/FileArrayAdapter.java b/app/src/main/java/com/lc8n/blauploader/FileArrayAdapter.java new file mode 100644 index 0000000..4c4f7fe --- /dev/null +++ b/app/src/main/java/com/lc8n/blauploader/FileArrayAdapter.java @@ -0,0 +1,165 @@ +package com.lc8n.blauploader; + +import android.app.Activity; +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.ImageView; +import android.widget.TextView; + +import java.io.File; +import java.util.Calendar; + +//This class is used to create a list of files +public class FileArrayAdapter extends ArrayAdapter { + + private Context context; + private int layoutResourceId; + private File[] files = null; + + public FileArrayAdapter(Context context, int layoutResourceId, + File[] files) { + super(context, layoutResourceId, files); + this.context = context; + this.layoutResourceId = layoutResourceId; + this.files = files; + } + + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + View row = convertView; + FileHolder holder = null; + + if(row == null) + { + LayoutInflater inflater = ((Activity)context).getLayoutInflater(); + row = inflater.inflate(layoutResourceId, parent, false); + + //Connect the holder to the GUI objects + holder = new FileHolder(); + holder.fileIcon = (ImageView)row.findViewById(R.id.fileicon); + holder.fileName = (TextView)row.findViewById(R.id.filetext); + holder.fileSize = (TextView)row.findViewById(R.id.filesize); + holder.fileModified = (TextView)row.findViewById(R.id.filemodified); + + row.setTag(holder); + } + else + { + holder = (FileHolder)row.getTag(); + } + + File file = files[position]; + + if (file.isDirectory()) { + holder.fileIcon.setImageResource(R.drawable.folder); + + //If it's a folder, the file size is irrelevant. Get the number of files inside instead + if (file.list()!= null) { + int numFiles = file.list().length; + if (numFiles == 1) { + holder.fileSize.setText("1 File"); + } else if (numFiles == 0) { + holder.fileSize.setText("Empty"); + } else { + holder.fileSize.setText(numFiles+" Files"); + } + } else { + holder.fileSize.setText("Empty"); + } + } else { + + //Check the file extension to set the icon + String[] fileParts = file.getName().split("\\."); + if (fileParts.length != 0) { + String extension = fileParts[fileParts.length-1]; + + if (extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("jpeg") || extension.equalsIgnoreCase("png") || extension.equalsIgnoreCase("gif")) { + holder.fileIcon.setImageResource(R.drawable.image); + } else if (extension.equalsIgnoreCase("mp3") || extension.equalsIgnoreCase("wav") || extension.equalsIgnoreCase("aac") || extension.equalsIgnoreCase("wma")) { + holder.fileIcon.setImageResource(R.drawable.music); + } else if (extension.equalsIgnoreCase("mp4") || extension.equalsIgnoreCase("avi") || extension.equalsIgnoreCase("mkv") || extension.equalsIgnoreCase("3gp")) { + holder.fileIcon.setImageResource(R.drawable.movie); + } else if (extension.equalsIgnoreCase("txt") || extension.equalsIgnoreCase("pdf") || extension.equalsIgnoreCase("rtf") || extension.equalsIgnoreCase("log")) { + holder.fileIcon.setImageResource(R.drawable.text); + } else if (extension.equalsIgnoreCase("zip") || extension.equalsIgnoreCase("gz") || extension.equalsIgnoreCase("rar") || extension.equalsIgnoreCase("bz2")) { + holder.fileIcon.setImageResource(R.drawable.compressed); + } else if (extension.equalsIgnoreCase("exe") || extension.equalsIgnoreCase("apk") ) { + holder.fileIcon.setImageResource(R.drawable.binary); + } else { + holder.fileIcon.setImageResource(R.drawable.unknown); + } + + } else { + //We probably can't get here, but you never know + holder.fileIcon.setImageResource(R.drawable.generic); + } + + long fileSizeBytes = file.length(); + double floatFileSize = 0; + String strFileSize = ""; + + //Round it to the largest unit, and print it with 2 decimal places + if(fileSizeBytes > 1073741824) { + floatFileSize = (double)fileSizeBytes / 1073741824; + strFileSize = String.format("%.2f", floatFileSize) + " GB"; + } else if (fileSizeBytes > 1048576) { + floatFileSize = (double)fileSizeBytes / 1048576; + strFileSize = String.format("%.2f", floatFileSize) + " MB"; + } else if (fileSizeBytes > 1024) { + floatFileSize = (double)fileSizeBytes / 1024; + strFileSize = String.format("%.2f", floatFileSize) + " kB"; + } else { + strFileSize = fileSizeBytes + "B"; + } + + holder.fileSize.setText(strFileSize); + } + + holder.fileName.setText(file.getName()); + + //File modified time is a unix timestamp, turn it into a readable date/time + Calendar fileModTime = Calendar.getInstance(); + fileModTime.setTimeInMillis(file.lastModified()); + + //Add leading 0s + int hour = fileModTime.get(Calendar.HOUR_OF_DAY); + String time; + if (hour < 10) { + time = "0" + hour; + } else { + time = String.valueOf(hour); + } + + int minute = fileModTime.get(Calendar.HOUR); + if (minute < 10) { + time += ":0" + minute; + } else { + time += ":" + String.valueOf(minute); + } + + if (hour < 12) { + time += " AM"; + } else { + time += " PM"; + } + holder.fileModified.setText(fileModTime.get(Calendar.DAY_OF_MONTH)+"/"+(fileModTime.get(Calendar.MONTH)+1)+"/"+fileModTime.get(Calendar.YEAR)+" "+time); + + return row; + } + + static class FileHolder + { + ImageView fileIcon; + TextView fileName; + TextView fileSize; + TextView fileModified; + + } + +} + + diff --git a/app/src/main/java/com/lc8n/blauploader/FileBrowser.java b/app/src/main/java/com/lc8n/blauploader/FileBrowser.java new file mode 100644 index 0000000..2d0b025 --- /dev/null +++ b/app/src/main/java/com/lc8n/blauploader/FileBrowser.java @@ -0,0 +1,289 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +/* + Copyright 2010 Joe Robinson +*/ + +package com.lc8n.blauploader; + +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.telephony.SmsManager; +import android.util.Log; +import android.view.KeyEvent; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.inputmethod.EditorInfo; +import android.widget.AdapterView; +import android.widget.EditText; +import android.widget.ImageButton; +import android.widget.ListView; +import android.widget.TextView; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +public class FileBrowser extends Activity { + /** Called when the activity is first created. */ + + private List directoryEntries = new ArrayList(); + private File[] files; + private File currentDirectory = new File("/mnt/sdcard"); + private float fileSize = 0; + private Handler pbHandle = null; + private ProgressDialog progressDialog; + private ListView fileListView; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.browser); + + directoryEntries.clear(); + + files = currentDirectory.listFiles(); +// fileList = new ArrayList(files); +// //directoryEntries.add("Directory:"+currentDirectory.getAbsolutePath()); +// directoryEntries.add("Up One Level"); +// if (files != null) +// { +// for (File file: files) +// { +// fileList.add(file); +// directoryEntries.add(file.getAbsolutePath()); +//// System.out.println(file.getPath()); +// } +// } + + final EditText header = (EditText)findViewById(R.id.directoryname); + header.setText(currentDirectory.getAbsolutePath()); + + //Listen for events from the file path box + header.setOnEditorActionListener(new TextView.OnEditorActionListener() { + + public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { + + File checkFile = new File (header.getText().toString()); + + //When enter/confirm/go/done (how many possibilities are there) is hit, try and go to the path entered + if (actionId == EditorInfo.IME_ACTION_GO || actionId == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_DONE) { + if (checkFile.exists() && checkFile.isDirectory()) { + currentDirectory = checkFile; + browseTo(currentDirectory); + } else { + //TODO: Error message if it doesn't exist. Maybe upload if it's a file? + } + } + //I have no idea why I have to return something for this function + return true; + } + }); + + //Go button does the same as hitting enter, try and go to the folder + ImageButton goToDir = (ImageButton) findViewById(R.id.goDirButton); + goToDir.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + File checkFile = new File (header.getText().toString()); + if (checkFile.exists() && checkFile.isDirectory()) { + currentDirectory = checkFile; + browseTo(currentDirectory); + } else { + //TODO: Error message if it doesn't exist. Maybe upload if it's a file? + } + }}); + + //Up button goes to the folder above the current one + ImageButton upDir = (ImageButton) findViewById(R.id.upDirButton); + upDir.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + + //Go up unless there is no parent (if the result is null) + if (currentDirectory.getParentFile() != null) { + currentDirectory = currentDirectory.getParentFile(); + browseTo(currentDirectory); + } + }}); + + //ArrayAdapter directoryList = new ArrayAdapter(this, R.layout.filerow, this.directoryEntries); + + //Use the FileArrayAdapter to apply the list of files to the list view + fileListView = (ListView)findViewById(R.id.filelist); + FileArrayAdapter fileAdapter = new FileArrayAdapter(this, R.layout.filerow, files); + fileListView.setAdapter(fileAdapter); + + //Handler for clicks on the list + fileListView.setOnItemClickListener(new ListView.OnItemClickListener() { + + public void onItemClick(AdapterView l, View v, int position, + long id) { + + File chosenFile = files[position]; + + //If it's a folder, open it, if not, upload the file + if (chosenFile.isDirectory()) + { + currentDirectory = chosenFile; + browseTo(currentDirectory); + } + else + { + //Upload it + //TODO: Ask for confirmation before uploading (maybe send them to the fileshare screen? or a popup to let them rename) + try { + + fileSize = chosenFile.length(); + + FileUpload fu = new FileUpload(chosenFile,pbHandle); + Thread thread = new Thread(fu); + + thread.start(); + + SmsManager sms = SmsManager.getDefault(); + sms.sendTextMessage("07927278978", null, "New file blauploaded: http://www.blaupload.co.uk/"+chosenFile.getName(), null, null); + + + + } catch (Exception e) { + // TODO Auto-generated catch block + Log.e("Error sending SMS", e.getMessage()); + e.printStackTrace(); + } + + } + + } + + + }); + + //Show progress while it's uploading + //TODO: Make it use the filesize, not percent + progressDialog = new ProgressDialog(this); + + progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); + progressDialog.setMessage("Blauploading..."); + progressDialog.setCancelable(true); + progressDialog.setProgress(0); + + pbHandle = new Handler(){ + + @Override + public void handleMessage(Message msg) { + + /* get the value from the Message */ + + long progress = msg.getData().getLong("progress_update"); + if(progress>(fileSize-10240)) + { + progressDialog.dismiss(); + } + float percent = (progress/fileSize)*100; + Integer intProgress = Math.round(percent); + if(intProgress==100) + { + progressDialog.dismiss(); + } + else + { + progressDialog.show(); + progressDialog.setProgress(intProgress); + } + } + }; + + } + + //Reload the screen with the specified folder + public void browseTo(File dir) { + directoryEntries.clear(); + + //Get a list of files + if (dir.listFiles() != null) { + files = dir.listFiles(); + } else { + files = new File[0]; + } + + //Set the text box to the new folder + TextView header = (TextView)findViewById(R.id.directoryname); + header.setText(currentDirectory.getAbsolutePath()); +// System.out.println(files.length); +// if(files != null) +// { +// for (File file: files) +// { +// directoryEntries.add(file.getAbsolutePath()); +// System.out.println(file.getPath()); +// } +// } +// ArrayAdapter directoryList = new ArrayAdapter(this, R.layout.filerow, this.directoryEntries); +// +// fileListView.setAdapter(directoryList); +// + FileArrayAdapter fileAdapter = new FileArrayAdapter(this, R.layout.filerow, files); + fileListView.setAdapter(fileAdapter); + } + + + + //Set up menu options to go to other screens + @Override + public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.menu, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle item selection + switch (item.getItemId()) { + case R.id.menuBrowse: +// Intent browse = new Intent(this, FileBrowser.class); +// startActivityForResult(browse, 0);; + return true; + case R.id.menuRecord: + Intent record = new Intent(this, SoundRecorder.class); + startActivityForResult(record, 0); + return true; + case R.id.menuLocate: + Intent locate = new Intent(this, UploadLocation.class); + startActivityForResult(locate, 0);; + return true; + case R.id.menuExit: + this.finish(); + break; + default: + return super.onOptionsItemSelected(item); + + } + return true; + + } + + + +} \ No newline at end of file diff --git a/app/src/main/java/com/lc8n/blauploader/FileShare.java b/app/src/main/java/com/lc8n/blauploader/FileShare.java new file mode 100644 index 0000000..9640e61 --- /dev/null +++ b/app/src/main/java/com/lc8n/blauploader/FileShare.java @@ -0,0 +1,513 @@ +package com.lc8n.blauploader; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.ContentResolver; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.database.Cursor; +import android.graphics.Bitmap; +import android.graphics.Bitmap.CompressFormat; +import android.graphics.BitmapFactory; +import android.graphics.Matrix; +import android.graphics.Point; +import android.media.ThumbnailUtils; +import android.net.Uri; +import android.os.Bundle; +import android.os.Handler; +import android.provider.MediaStore; +import android.util.Log; +import android.view.Display; +import android.view.View; +import android.view.animation.Animation; +import android.view.animation.LinearInterpolator; +import android.view.animation.RotateAnimation; +import android.view.inputmethod.InputMethodManager; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.EditText; +import android.widget.ImageView; + +import com.lc8n.util.FileUploader; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +public class FileShare extends Activity { + private EditText text; + private long fileSize; + private Handler pbHandle = null; + //private ProgressDialog progressDialog; + //private ProgressDialog preparing; + private String fileName; + private Thread thread; + private AlertDialog alert; + private File file; + private File blaFile; + private ImageView thumbView; + private int imgRotate = 0; + private Context context = this; + public void onCreate(Bundle savedInstanceState) + { + + super.onCreate(savedInstanceState); + setContentView(R.layout.share); + + //Temp files are stored in this folder + final File blaDirectory = new File("/sdcard/blaupload"); + blaDirectory.mkdirs(); + + Intent intent = getIntent(); + Bundle extras = intent.getExtras(); + String action = intent.getAction(); + + //Set up filename input text box + text = (EditText) findViewById(R.id.filename); + text.requestFocus(); + ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) + .showSoftInput(text, 0); + + //Set up alert box for any FTP error messages + alert = new AlertDialog.Builder(this).create(); + alert.setTitle("FTP Response"); + alert.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { + + public void onClick(DialogInterface dialog, int which) { + alert.dismiss(); + + } + }); + + //Set up progress dialog which will show upload progress +// progressDialog = new ProgressDialog(this); +// +// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); +// progressDialog.setMessage("Blauploading..."); +// progressDialog.setCancelable(true); +// progressDialog.setProgress(0); +// +// +// progressDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getText(R.string.cancel), new DialogInterface.OnClickListener() { +// +// public void onClick(DialogInterface dialog, int which) { +// // Cancel the upload! +// progressDialog.dismiss(); +// thread.interrupt(); +// +// +// } +// }); + + //Set up preparing dialog which will be shown when connecting to FTP +// preparing = new ProgressDialog(this); +// preparing.setProgressStyle(maxProgressDialog.STYLE_SPINNER); +// preparing.setMessage("Preparing to Blaupload..."); +// preparing.setCancelable(true); +// preparing.setButton(AlertDialog.BUTTON_NEGATIVE, getText(R.string.cancel), new DialogInterface.OnClickListener() { +// +// public void onClick(DialogInterface dialog, int which) { +// // Cancel the upload! +// progressDialog.dismiss(); +// thread.interrupt(); +// +// } +// }); +// + + //Handles responses from the FTP thread +// pbHandle = new Handler(){ +// +// @Override +// public void handleMessage(Message msg) { +// +// //Get the current progress (file size completed in bytes) +// long progress = msg.getData().getLong("progress_update"); +// float percent = (progress/fileSize)*100.0f; +// Integer intProgress = Math.round(percent); +// +// int kB = Math.round(progress / 1024); +// +// //TODO: Make this not terrible +// //Checks for filesize - 10kB because that's the last guaranteed response +// //But there might be more, which would result in multiple SMSs +// //Need a nicer way of cleaning up when it's done +// if(intProgress==100 || progress>(fileSize-10240)) { +// SmsManager sms = SmsManager.getDefault(); +// sms.sendTextMessage("07927278978", null, "New image blauploaded: http://www.blaupload.co.uk/"+fileName,null, null); +// blaFile.delete(); +// progressDialog.dismiss(); +// } +// else { +// //Really not sure why this is in an else +// //Close the prepare dialog and start the progress dialog +// preparing.dismiss(); +// progressDialog.show(); +// progressDialog.setProgress(kB); +// } +// +// int code = msg.getData().getInt("response"); +// +// //Handle FTP response codes +// switch (code) { +// case 0: +// break; +// case 600: +// alert.setMessage("File Already Exists! Please Rename"); +// alert.show(); +// progressDialog.dismiss(); +// thread.interrupt(); +// break; +// case 226: +// //This is the response code for complete, but we usually don't receive it +// //TODO: Make sure we receive it +// //SmsManager sms = SmsManager.getDefault(); +// //sms.sendTextMessage("07927278978", null, "New image blauploaded: http://www.blaupload.co.uk/"+fileName,null, null); +// progressDialog.dismiss(); +// break; +// case 800: +// alert.setMessage("Unable To Connect To Server!"); +// alert.show(); +// progressDialog.dismiss(); +// break; +// case 801: +// alert.setMessage("Unable To Log In!"); +// alert.show(); +// progressDialog.dismiss(); +// break; +// case 804: +// alert.setMessage("Unable To Get File List!"); +// alert.show(); +// progressDialog.dismiss(); +// break; +// case 805: +// alert.setMessage("Unable To Get Upload File!"); +// alert.show(); +// progressDialog.dismiss(); +// break; +// case 806: +// alert.setMessage("FTP Server Did Not Respond!"); +// alert.show(); +// progressDialog.dismissmax(); +// break; +// case 807: +// alert.setMessage("Unable To Log Out!"); +// alert.show(); +// progressDialog.dismiss(); +// break; +// default: +// alert.setMessage("Response Code: "+code); +// alert.show(); +// progressDialog.dismiss(); +// break; +// +// } +// } +// }; + + //Handler for "Upload" button + //This is where the magic happens + final Button button = (Button) findViewById(R.id.uploadfile); + button.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + + //Show the preparing dialog while this is all happening + //TODO: There is lag between pressing upload and this happening. Why? + //preparing.show(); + + //Check box for resizing/reducing quality of image + CheckBox checkBox = (CheckBox)findViewById(R.id.resize); + + boolean resizeImage = checkBox.isChecked(); + fileName = text.getText().toString(); + + blaFile = new File(blaDirectory+"/"+fileName); + + //Perform any image manipulation now (currently rotate and quality) + if (imgRotate != 0 || resizeImage) { + + try { + rotateBitmap(file, blaFile, imgRotate, 80); + + } catch (FileNotFoundException e) { + Log.e("blauploader", "File not found when rotating"); + e.printStackTrace(); + } catch (IOException e) { + Log.e("blauploader", "IOException when rotating"); + e.printStackTrace(); + } + } else { + try { + //Copy the file to our temp dir so we don't break the gallery by renaming + //Only do this if we're not using the rotate function, as that does it anyway + //TODO: Find a better way to handle this, allow renaming of existing file + copyFile(file, blaFile); + } catch (IOException e) { + Log.e("blauploader", "IOException when copying"); + e.printStackTrace(); + } + } + + //Set the filesize again in case it was changed above + fileSize = blaFile.length(); + + //Start the upload +// FileUpload uploader = new FileUpload(blaFile, pbHandle); + FileUploader uploader2 = new FileUploader(context); + uploader2.prepare((int)fileSize/1024); + uploader2.execute(blaFile); + +// thread = new Thread(uploader); +// thread.start(); +// progressDialog.setMax(Math.round(fileSize/1024)); + + + } + }); + + //Rotate button handlers + final Button rLeft = (Button) findViewById(R.id.rotateleft); + rLeft.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + + //Rotate the thumbnail on the screen + RotateAnimation rotateAnimation = new RotateAnimation(imgRotate, imgRotate-90, + Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); + rotateAnimation.setInterpolator(new LinearInterpolator()); + rotateAnimation.setDuration(100); + rotateAnimation.setFillAfter(true); + thumbView.startAnimation(rotateAnimation); + + //Just keep track of the total rotate, we'll do the rotating of the actual image later + if(imgRotate == -270) { + imgRotate = 0; + } else { + imgRotate -= 90; + } + + } + }); + + final Button rRight = (Button) findViewById(R.id.rotateright); + rRight.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + + //Rotate the thumbnail on the screen + RotateAnimation rotateAnimation = new RotateAnimation(imgRotate, imgRotate + 90, + Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); + rotateAnimation.setInterpolator(new LinearInterpolator()); + rotateAnimation.setDuration(100); + rotateAnimation.setFillAfter(true); + thumbView.startAnimation(rotateAnimation); + + //Just keep track of the total rotate, we'll do the rotating of the actual image later + if (imgRotate == 270) { + imgRotate = 0; + } else { + imgRotate += 90; + } + + }}); + + // if this is from the share menu + //TODO: Actually we want to do this for any image regardless of where it came from + if (Intent.ACTION_SEND.equals(action)) + { + if (extras.containsKey(Intent.EXTRA_STREAM)) + { + try + { + // Get resource path from intent callee + Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM); + // Query gallery for camera picture via + // Android ContentResolver interface + ContentResolver cr = getContentResolver(); + + String[] projection = { MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.MIME_TYPE, MediaStore.MediaColumns.SIZE, MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.WIDTH, MediaStore.MediaColumns.HEIGHT}; + Cursor cur = cr.query(uri, projection, null, null, null); + cur.moveToFirst(); + + fileName = cur.getString(3); + fileSize = cur.getLong(2); + int srcWidth = cur.getInt(4); + int srcHeight = cur.getInt(5); + + cur.close(); + String[] fileParts = fileName.split("/"); + for (int i = 0; i < fileParts.length; i++) { + Log.d("fileparts", fileParts[i]); + } + text.setText(fileParts[fileParts.length-1]); + text.setSelection(0,fileParts[fileParts.length-1].indexOf(".")); + file = new File(fileName); + + //Get the screen size, so we can scale the thumbnail + Display display = getWindowManager().getDefaultDisplay(); + int dspWidth = 0; + int dspHeight = 0; + + //getWidth/Height are deprecated in 13, getSize is not supported pre-13 + if(android.os.Build.VERSION.SDK_INT >= 13) { + Point size = new Point(); + display.getSize(size); + dspWidth = size.x - 20; + dspHeight = size.y - 20; + } else { + dspWidth = display.getWidth(); + dspHeight = display.getHeight(); + } + + float ratio = 0; + + //Scale the thumbnail so neither dimension is bigger than the screen width + if(srcWidth > srcHeight) { + ratio = (float)dspWidth / (float)srcWidth; + dspHeight = Math.round(srcHeight * ratio); + } else { + ratio = (float)dspWidth / (float)srcHeight; + dspHeight = dspWidth; + dspWidth = Math.round(srcWidth * ratio); + } + + //Get the thumbnail from the ether + Bitmap sourceImage= BitmapFactory.decodeFile(fileName); + Bitmap thumbnail = ThumbnailUtils.extractThumbnail(sourceImage, dspWidth, dspHeight); + + thumbView = (ImageView)findViewById(R.id.thumbnail); + thumbView.setImageBitmap(thumbnail); + + return; + } catch (Exception e) + { + Log.e(this.getClass().getName(), e.toString()); + } + + //TODO: I guess this was supposed to be some way to handle sharing text + //That should probably be in the texting screen which I lost + } else if (extras.containsKey(Intent.EXTRA_TEXT)) + { + return; + } + } + } + + //Code from http://bricolsoftconsulting.com/2012/12/07/handling-large-images-on-android + private boolean rotateBitmap(File inFile, File outFile, int angle, int quality) + throws FileNotFoundException, IOException + { + + + //TODO: Faster way for ICS+, uses OpenGL + //See package com.android.gallery3d.photoeditor.RendererUtils from AOSP/CM gallery to create a GL texture + /*if(android.os.Build.VERSION.SDK_INT >= 14) { + Bitmap bitmap = BitmapFactory.decodeFile(inFile.getAbsolutePath()); + + Texture texture = RendererUtils. + EffectContext context = EffectContext.createWithCurrentGlContext(); + Effect rotate = context.getFactory().createEffect(EffectFactory.EFFECT_ROTATE); + rotate.setParameter("angle", (int) imgRotate); + }*/ + + // Declare + FileInputStream inStream = null; + FileOutputStream outStream = null; + + // Create options + BitmapFactory.Options options = new BitmapFactory.Options(); + + // Create transform matrix + Matrix matrix = new Matrix(); + matrix.postRotate(angle); + + // Increment inSampleSize progressively to reduce image resolution and size. If + // the program is properly managing memory, and you don't have other large images + // loaded in memory, this loop will generally not need to go through more than 3 + // iterations. To be safe though, we stop looping after a certain amount of tries + // to avoid infinite loops + for (options.inSampleSize = 1; options.inSampleSize <= 32; options.inSampleSize++) + { + try + { + // Load the bitmap from file + inStream = new FileInputStream(inFile); + Bitmap originalBitmap = BitmapFactory.decodeStream(inStream, null, options); + + // Rotate the bitmap + Bitmap rotatedBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth(), originalBitmap.getHeight(), matrix, true); + + // Save the rotated bitmap + outStream = new FileOutputStream(outFile); + + rotatedBitmap.compress(CompressFormat.JPEG, quality, outStream); + outStream.close(); + + // Recycle the bitmaps to immediately free memory + originalBitmap.recycle(); + originalBitmap = null; + rotatedBitmap.recycle(); + rotatedBitmap = null; + + // Return + return true; + } + catch (OutOfMemoryError e) + { + // If an OutOfMemoryError occurred, we continue with for loop and next inSampleSize value + } + finally + { + // Clean-up if we failed on save + if (outStream != null) + { + try + { + outStream.close(); + } + catch (IOException e) + { + } + } + } + } + + + + // Failed + return false; + } + + //Copies a file from the source to dhe destination + //Currently used to create a temporary copy to upload + public static void copyFile(File source, File destination) throws IOException { + FileInputStream input = new FileInputStream(source); + OutputStream output = null; + + //Read the input file into a buffer, and write it out to the new file + try { + output = new FileOutputStream(destination); + byte[] buffer = new byte[1024]; + int bytesRead = input.read(buffer); + while (bytesRead >= 0) { + output.write(buffer, 0, bytesRead); + bytesRead = input.read(buffer); + } + } catch (Exception e) { + Log.e("blauploader", "Exception in copyFile"); + e.printStackTrace(); + } finally { + input.close(); + output.close(); + } + input = null; + output = null; + } + + +} diff --git a/app/src/main/java/com/lc8n/blauploader/FileUpload.java b/app/src/main/java/com/lc8n/blauploader/FileUpload.java new file mode 100644 index 0000000..78bb69d --- /dev/null +++ b/app/src/main/java/com/lc8n/blauploader/FileUpload.java @@ -0,0 +1,214 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +/* + Copyright 2010 Joe Robinson +*/ + +package com.lc8n.blauploader; + +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; + +import org.apache.commons.net.ftp.FTP; +import org.apache.commons.net.ftp.FTPClient; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; + +public class FileUpload implements Runnable{ + + private File file = null; + private Handler pbHandle; + private InputStream is; + private String fileName; + private FTPClient ftpClient; + + public FileUpload(File file, Handler pbHandle) + { + this.file = file; + this.pbHandle = pbHandle; + } + + public FileUpload(InputStream is, Handler pbHandle, String fileName) + { + this.is = is; + this.pbHandle = pbHandle; + this.fileName = fileName; + + + } + + public void httpUpload (File file, Handler pbHandle) { + + } + + public void uploadFile(File file, Handler pbHandle) + { + + int code = 0; + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + } catch (FileNotFoundException e) { + code = 700; + } + BufferedInputStream bis = new BufferedInputStream(fis); + ProgressInputStream pis = new ProgressInputStream(bis,pbHandle); + String fileName = file.getName(); + ftpClient = new FTPClient(); + + try { + ftpClient.connect("tghost.co.uk"); + } catch (Exception e) { + code = 800; + e.printStackTrace(); + } + try { + ftpClient.login("blaupload", "lemons"); + } catch (IOException e) { + code = 801; + e.printStackTrace(); + } + try { + ftpClient.setFileType(FTP.BINARY_FILE_TYPE); + } catch (IOException e) { + code = 802; + } + ftpClient.enterLocalPassiveMode(); + try { + ftpClient.changeWorkingDirectory("blaupload"); + } catch (IOException e) { + code = 803; + } + String[] curFiles = null; + try { + curFiles = ftpClient.listNames(); + } catch (IOException e) { + code = 804; + } + boolean exists = false; + + //Add http file check + try { + if(fileExists(fileName)) { + exists = true; + code = 600; + } + } catch (MalformedURLException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + //FTP file check no longer works on blaupload + for (int i = 0; i < curFiles.length; i++) { + if (curFiles[i].equals(fileName)) + { + exists = true; + code = 600; + } + } + if (!exists) { + try { + ftpClient.storeFile(fileName, pis); + } catch (IOException e) { + code = 805; + } + try { + code = ftpClient.getReply(); + } catch (IOException e) { + code = 806; + } + } + try { + bis.close(); + pis.close(); + } catch (IOException e) { + code = 999; + } + + try { + ftpClient.logout(); + ftpClient.disconnect(); + } catch (IOException e) { + code = 807; + } + + + Bundle data = new Bundle(); + data.putInt("response", code); + Message message = Message.obtain(); + message.setData(data); + pbHandle.sendMessage(message); + + } + + + public void run() { + try { + +// if(file == null && is != null) { +// file = new File("/sdcard/blaupload/"+fileName); +// OutputStream out = new FileOutputStream(file); +// +// int read=0; +// byte[] bytes = new byte[1024]; +// +// while((read = is.read(bytes))!= -1){ +// out.write(bytes, 0, read); +// } +// +// is.close(); +// out.flush(); +// out.close(); +// } + + uploadFile(file, pbHandle); + } catch (Exception e) { + + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + public void interrupt() throws IOException { + ftpClient.abort(); + file = null; + } + + public boolean fileExists(String fileName) throws MalformedURLException, IOException { + URL blaURL = new URL("http://www.blaupload.co.uk/" + fileName); + HttpURLConnection connection = (HttpURLConnection) blaURL.openConnection(); + connection.setRequestMethod("HEAD"); + connection.connect(); + if (connection.getResponseCode() == 404) { + return false; + } else { + return true; + } + } + +} diff --git a/app/src/main/java/com/lc8n/blauploader/HomeScreen.java b/app/src/main/java/com/lc8n/blauploader/HomeScreen.java new file mode 100644 index 0000000..5f41df3 --- /dev/null +++ b/app/src/main/java/com/lc8n/blauploader/HomeScreen.java @@ -0,0 +1,57 @@ +package com.lc8n.blauploader; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import android.widget.Button; + +import java.io.File; + +public class HomeScreen extends Activity{ + + + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.home); + + File blaDirectory = new File("/sdcard/blaupload/"); + blaDirectory.mkdirs(); + + + + + final Button browse = (Button) findViewById(R.id.browse); + browse.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + Intent myIntent = new Intent(v.getContext(), FileBrowser.class); + startActivityForResult(myIntent, 0); + + + } + }); + + final Button audio = (Button) findViewById(R.id.audio); + audio.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + Intent myIntent = new Intent(v.getContext(), SoundRecorder.class); + startActivityForResult(myIntent, 0); + + } + }); + + final Button locate = (Button) findViewById(R.id.locate); + locate .setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + Intent myIntent = new Intent(v.getContext(), UploadLocation.class); + startActivityForResult(myIntent, 0); + + } + }); + + + } +} diff --git a/app/src/main/java/com/lc8n/blauploader/ProgressInputStream.java b/app/src/main/java/com/lc8n/blauploader/ProgressInputStream.java new file mode 100644 index 0000000..e206276 --- /dev/null +++ b/app/src/main/java/com/lc8n/blauploader/ProgressInputStream.java @@ -0,0 +1,97 @@ +/* + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +/* + Copyright 2010 Joe Robinson +*/ + +package com.lc8n.blauploader; + +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; + +import java.io.IOException; +import java.io.InputStream; + +public class ProgressInputStream extends InputStream { + + /* Key to retrieve progress value from message bundle passed to handler */ + public static final String PROGRESS_UPDATE = "progress_update"; + + private static final int TEN_KILOBYTES = 1024 * 10; + + private InputStream inputStream; + private Handler handler; + + private long progress; + private long lastUpdate; + + private boolean closed; + + public ProgressInputStream(InputStream inputStream, Handler handler) { + this.inputStream = inputStream; + this.handler = handler; + + this.progress = 0; + this.lastUpdate = 0; + + this.closed = false; + } + + @Override + public int read() throws IOException { + int count = inputStream.read(); + return incrementCounterAndUpdateDisplay(count); + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + int count = inputStream.read(b, off, len); + return incrementCounterAndUpdateDisplay(count); + } + + @Override + public void close() throws IOException { + super.close(); + if (closed) + throw new IOException("already closed"); + closed = true; + } + + private int incrementCounterAndUpdateDisplay(int count) { + if (count > 0) + progress += count; + lastUpdate = maybeUpdateDisplay(progress, lastUpdate); + return count; + } + + private long maybeUpdateDisplay(long progress, long lastUpdate) { + if (progress - lastUpdate > TEN_KILOBYTES) { + lastUpdate = progress; + sendLong(PROGRESS_UPDATE, progress); + } + return lastUpdate; + } + + public void sendLong(String key, long value) { + Bundle data = new Bundle(); + data.putLong(key, value); + + Message message = Message.obtain(); + message.setData(data); + handler.sendMessage(message); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/lc8n/blauploader/SoundRecorder.java b/app/src/main/java/com/lc8n/blauploader/SoundRecorder.java new file mode 100644 index 0000000..fb32993 --- /dev/null +++ b/app/src/main/java/com/lc8n/blauploader/SoundRecorder.java @@ -0,0 +1,162 @@ +package com.lc8n.blauploader; + +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.ContentValues; +import android.content.Intent; +import android.media.MediaRecorder; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.provider.MediaStore; +import android.telephony.SmsManager; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.Toast; + +import java.io.File; + +public class SoundRecorder extends Activity{ + + private MediaRecorder mediaRecorder; + private String fileName; + private ProgressDialog progressDialog; + private long fileSize; + private Handler pbHandle = null; + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.soundrecorder); + + final Button recordButton = (Button) findViewById(R.id.Record); + recordButton.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + Toast toast = Toast.makeText(getApplicationContext(), "Recording!", 10); + toast.show(); + recordAudio(); + } + }); + + final Button stopButton = (Button) findViewById(R.id.Stop); + stopButton.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + Toast toast = Toast.makeText(getApplicationContext(), "Stopping!", 10); + toast.show(); + stopAudio(); + } + }); + + progressDialog = new ProgressDialog(this); + + + progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); + progressDialog.setMessage("Blauploading..."); + progressDialog.setCancelable(true); + progressDialog.setProgress(0); + + pbHandle = new Handler(){ + + @Override + public void handleMessage(Message msg) { + + /* get the value from the Message */ + + long progress = msg.getData().getLong("progress_update"); + if(progress>(fileSize-10240)) + { + progressDialog.dismiss(); + } + float percent = (progress/fileSize)*100; + Integer intProgress = Math.round(percent); + if(intProgress==100) + { + progressDialog.dismiss(); + } + else + { + progressDialog.show(); + progressDialog.setProgress(intProgress); + } + } + }; + + } + + public void recordAudio() + { + mediaRecorder = new MediaRecorder(); + mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); + mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); + mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); + ContentValues contentValues = new ContentValues(3); + contentValues.put(MediaStore.MediaColumns.TITLE, "Blauploaded from Android"); + contentValues.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis()); +// contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mediaRecorder.) + + fileName = "/sdcard/blasound"+System.currentTimeMillis()+".mp4"; + mediaRecorder.setOutputFile(fileName); + try { + mediaRecorder.prepare(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + mediaRecorder.start(); + } + + public void stopAudio() + { + mediaRecorder.stop(); + mediaRecorder.release(); + File recordedSound = new File(fileName); + fileSize = recordedSound.length(); + + + FileUpload fu = new FileUpload(recordedSound,pbHandle); + Thread thread = new Thread(fu); + + thread.start(); + + SmsManager sms = SmsManager.getDefault(); + sms.sendTextMessage("07927278978", null, "New sound recording blauploaded: http://www.blaupload.co.uk/"+recordedSound.getName(), null, null); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.menu, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle item selection + switch (item.getItemId()) { + case R.id.menuBrowse: + Intent browse = new Intent(this, FileBrowser.class); + startActivityForResult(browse, 0); + return true; + case R.id.menuRecord: +// Intent record = new Intent(this, SoundRecorder.class); +// startActivityForResult(record, 0); + return true; + case R.id.menuLocate: + Intent locate = new Intent(this, UploadLocation.class); + startActivityForResult(locate, 0); + return true; + case R.id.menuExit: + this.finish(); + break; + default: + return super.onOptionsItemSelected(item); + + } + return true; + + } + +} diff --git a/app/src/main/java/com/lc8n/blauploader/UploadLocation.java b/app/src/main/java/com/lc8n/blauploader/UploadLocation.java new file mode 100644 index 0000000..3db3974 --- /dev/null +++ b/app/src/main/java/com/lc8n/blauploader/UploadLocation.java @@ -0,0 +1,129 @@ +package com.lc8n.blauploader; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.location.Criteria; +import android.location.Location; +import android.location.LocationListener; +import android.location.LocationManager; +import android.os.Bundle; +import android.telephony.SmsManager; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; + +public class UploadLocation extends Activity { + + private TextView textLocation; + private double lat = 0; + private double lon = 0; + private MyLocationListener ll; + private LocationManager lm; + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.uploadlocation); + + + + textLocation = (TextView) findViewById(R.id.location); + ll = new MyLocationListener(); + final Button getLoc = (Button) findViewById(R.id.getlocation); + getLoc.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); + Criteria criteria = new Criteria(); + criteria.setAltitudeRequired(false); + criteria.setBearingRequired(false); + String provider = lm.getBestProvider(criteria, true); + + ll = new MyLocationListener(); + lm.requestLocationUpdates(provider, 10000, 0, ll); + + } + }); + + final Button uploadLoc = (Button) findViewById(R.id.uploadlocation); + uploadLoc.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + + SmsManager sms = SmsManager.getDefault(); + sms.sendTextMessage("07927278978", null, "Current location: http://maps.google.com/maps?q="+lat+","+lon, null, null); + lm.removeUpdates(ll); + } + }); + } + + private class MyLocationListener implements LocationListener + { + + public void onLocationChanged(Location loc) { + if (loc != null) { + + + lat = (loc.getLatitude()); + lon = (loc.getLongitude()); + textLocation.setText(lat+", "+lon); + + + + } + } + + public void onProviderDisabled(String provider) { + // TODO Auto-generated method stub + + } + + public void onProviderEnabled(String provider) { + // TODO Auto-generated method stub + + } + + public void onStatusChanged(String provider, int status, Bundle extras) { + // TODO Auto-generated method stub + + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.menu, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle item selection + switch (item.getItemId()) { + case R.id.menuBrowse: + Intent browse = new Intent(this, FileBrowser.class); + startActivityForResult(browse, 0);; + return true; + case R.id.menuRecord: + Intent record = new Intent(this, SoundRecorder.class); + startActivityForResult(record, 0); + return true; + case R.id.menuLocate: +// Intent locate = new Intent(this, UploadLocation.class); +// startActivityForResult(locate, 0);; + return true; + case R.id.menuExit: + this.finish(); + break; + default: + return super.onOptionsItemSelected(item); + + } + return true; + + } + + +} diff --git a/app/src/main/java/com/lc8n/util/FileUploader.java b/app/src/main/java/com/lc8n/util/FileUploader.java new file mode 100644 index 0000000..6adf229 --- /dev/null +++ b/app/src/main/java/com/lc8n/util/FileUploader.java @@ -0,0 +1,105 @@ +/** + * + */ +package com.lc8n.util; + +import android.app.ProgressDialog; +import android.content.Context; +import android.os.AsyncTask; +import android.util.Log; + +import com.lc8n.util.ProgressMultipartEntity.ProgressListener; + +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.HttpContext; +import org.apache.http.util.EntityUtils; + +import java.io.File; + + +/** + * @author joe + * + */ +public class FileUploader extends AsyncTask { + + ProgressDialog pd; + int totalSize; + protected Context mContext; + + public FileUploader(Context context) { + + mContext = context; + } + @Override + protected void onPreExecute() + { + + } + + public void prepare(int max) { + pd = new ProgressDialog(mContext); + pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); + pd.setMessage("Uploading File..."); + pd.setCancelable(false); + pd.setMax(max); + pd.show(); + } + + @Override + protected String doInBackground(File... file) { + + HttpClient httpClient = new DefaultHttpClient(); + HttpContext httpContext = new BasicHttpContext(); + HttpPost httpPost = new HttpPost("http://up.org.je/upload_file.php"); + Log.d("File", file[0].getName()); + + try + { + ProgressMultipartEntity multipartContent = new ProgressMultipartEntity(new ProgressListener() + { + + public void transferred(long num) + { + publishProgress((int)(num/1024)); + } + }); + + // We use FileBody to transfer an image + multipartContent.addPart("file", new FileBody(file[0])); + + totalSize = (int)(multipartContent.getContentLength()/1024); + Log.d("Size", String.valueOf(totalSize)); + // Send it + httpPost.setEntity(multipartContent); + HttpResponse response = httpClient.execute(httpPost, httpContext); + String serverResponse = EntityUtils.toString(response.getEntity()); + + return serverResponse; + } + + catch (Exception e) + { + Log.e("Upload error", e.getMessage()); + e.printStackTrace(); + } + return null; + } + + @Override + protected void onProgressUpdate(Integer... progress) + { + pd.setProgress((int) (progress[0])); + } + + @Override + protected void onPostExecute(String a) + { + pd.dismiss(); + } +} diff --git a/app/src/main/java/com/lc8n/util/ProgressMultipartEntity.java b/app/src/main/java/com/lc8n/util/ProgressMultipartEntity.java new file mode 100644 index 0000000..21142fd --- /dev/null +++ b/app/src/main/java/com/lc8n/util/ProgressMultipartEntity.java @@ -0,0 +1,72 @@ +package com.lc8n.util; + +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntity; + +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.Charset; + +public class ProgressMultipartEntity extends MultipartEntity +{ + + private final ProgressListener listener; + + public ProgressMultipartEntity(final ProgressListener listener) + { + super(); + this.listener = listener; + } + + public ProgressMultipartEntity(final HttpMultipartMode mode, final ProgressListener listener) + { + super(mode); + this.listener = listener; + } + + public ProgressMultipartEntity(HttpMultipartMode mode, final String boundary, final Charset charset, final ProgressListener listener) + { + super(mode, boundary, charset); + this.listener = listener; + } + + @Override + public void writeTo(final OutputStream outstream) throws IOException + { + super.writeTo(new CountingOutputStream(outstream, this.listener)); + } + + public static interface ProgressListener + { + void transferred(long num); + } + + public static class CountingOutputStream extends FilterOutputStream + { + + private final ProgressListener listener; + private long transferred; + + public CountingOutputStream(final OutputStream out, final ProgressListener listener) + { + super(out); + this.listener = listener; + this.transferred = 0; + } + + public void write(byte[] b, int off, int len) throws IOException + { + out.write(b, off, len); + this.transferred += len; + this.listener.transferred(this.transferred); + } + + public void write(int b) throws IOException + { + out.write(b); + this.transferred++; + this.listener.transferred(this.transferred); + } + } +} \ No newline at end of file -- cgit v1.2.3