Launch other activity after createChooser - android

How can you redirect to another activity once the application that was launched by createChooser such as show below is complete?
My attempt below ends up with the second intent being triggered before the createChooser launches. I noticed that when I press the back button on the newly launched activity is when the createChooser appears on the activity I wanted to launch it from.
I also tried to wrap the createChooser in startActivityForResult and then launch the second intent using onActivityResult but the result was the same
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
Intent trackIntent = new Intent(InformContacts.this, TrackOffers.class);
startActivity(trackIntent);
Here's the entire code:
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class InformContacts extends Activity {
private static String ITEM_NAME = "Item name";
private static String ITEM_PRICE = "Item price";
private static String ITEM_PIC_URI = "Item pic uri";
public static final int REQUEST_SEND_EMAIL = 0;
ArrayList<Contact> listContacts;
ListView lvContacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inform_contacts);
listContacts = new ContactFetcher(this).fetchAll();
lvContacts = (ListView) findViewById(R.id.lvContacts);
final ContactsAdapter adapterContacts = new ContactsAdapter(this, listContacts);
lvContacts.setAdapter(adapterContacts);
final Button informButton = (Button) findViewById(R.id.button6);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final String uriSharedPref = preferences.getString(ITEM_PIC_URI, "item pic uri");
informButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList emailsList = adapterContacts.emailsSelected;
String item = preferences.getString(ITEM_NAME, "item name");
Float price = preferences.getFloat(ITEM_PRICE,0);
//May use the uriSharedPref string to embed actual url in email and show recipients like I did with publishing house
String sellingMessage = "Hello,\n\nI'm selling my "+ item +" for KES "+price+".\n\nGet back to me if you're interested in buying.\n\n" + uriSharedPref;
String subject = "Selling my "+item;
sendEmail(emailsList, sellingMessage, subject);
//Intent trackIntent = new Intent(InformContacts.this, TrackOffers.class);
//startActivity(trackIntent);
}
});
}
protected void sendEmail(ArrayList<String> arrayOfEmails, String message, String subject) {
Log.i("Send email", "");
Intent emailIntent = new Intent(Intent.ACTION_SEND);
//First Step: convert ArrayList to an Object array
Object[] objEmails = arrayOfEmails.toArray();
//Second Step: convert Object array to String array
String[] strEmails = Arrays.copyOf(objEmails, objEmails.length, String[].class);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, strEmails);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, message);
PackageManager packageManager = getPackageManager();
List activities = packageManager.queryIntentActivities(emailIntent, PackageManager.MATCH_DEFAULT_ONLY);
boolean isIntentSafe = activities.size() > 0;
if(isIntentSafe){
startActivityForResult(Intent.createChooser(emailIntent, "Send mail..."), REQUEST_SEND_EMAIL);
//finish();
Log.i("Done sending email...", "");
}
else{
Toast.makeText(InformContacts.this, "No email app found. Email won't be sent.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
if(requestCode == REQUEST_SEND_EMAIL){
Intent intent = new Intent(this, TrackOffers.class);
startActivity(intent);
}
}
}
}

Try this
Change to:
if(requestCode == REQUEST_SEND_EMAIL){
Intent intent = new Intent(this, TrackOffers.class);
startActivity(intent);
}
Instead of:
if (resultCode == RESULT_OK){
if(requestCode == REQUEST_SEND_EMAIL){
Intent intent = new Intent(this, TrackOffers.class);
startActivity(intent);
}
}

Related

send a image from gallery in email service in android

I want to send images via email in my android app. For which I'm using Android Native Camera app and Intents to use the respective service. I've used the following code:
Email is getting send but if I'm trying to add image the app gets crash.
public class Complaints extends AppCompatActivity {
Button sendEmail;
EditText to, subject, msg;
Bitmap image;
Button camera;
File pic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complaints);
to = (EditText) findViewById(R.id.et1);
subject = (EditText) findViewById(R.id.et2);
msg = (EditText) findViewById(R.id.et3);
sendEmail = (Button) findViewById(R.id.s_Email);
camera = (Button) findViewById(R.id.btn_img);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent,"Select Picture"));
}
});
sendEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Emailid = to.getText().toString();
String sub = subject.getText().toString();
String message = msg.getText().toString();
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{Emailid});
email.putExtra(Intent.EXTRA_SUBJECT, sub);
email.putExtra(Intent.EXTRA_TEXT, message);
email.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//this will make such that when user returns to your app, your app is displayed, instead of the email app.
email.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic));
email.setType("message/rfc822");
email.setType("image/jpeg");
try {
startActivity(Intent.createChooser(email, "Message was Sent"));
}
catch (ActivityNotFoundException e) {
Toast t = Toast.makeText(Complaints.this, "There is No Emial Client installed ", Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER, 0, 10);
t.show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10) {
image = (Bitmap) data.getExtras().get("Data");
ImageView i = (ImageView) findViewById(R.id.img);
i.setImageBitmap(image);
try
{
File root= Environment.getExternalStorageDirectory();
if(root.canWrite())
{
pic=new File(root,"pic.jpeg");
FileOutputStream out=new FileOutputStream(pic);
image.compress(Bitmap.CompressFormat.JPEG,100,out);
out.flush();
out.close();
}
} catch (IOException e)
{
Log.e("BROKEN", "Could not write file " + e.getMessage());
}
}
}
}
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.Media;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
public class Complaints extends Activity {
Button send;
Bitmap thumbnail;
File pic;
EditText address, subject, emailtext;
protected static final int CAMERA_PIC_REQUEST = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complaints);
send=(Button) findViewById(R.id.emailsendbutton);
address=(EditText) findViewById(R.id.emailaddress);
subject=(EditText) findViewById(R.id.emailsubject);
emailtext=(EditText) findViewById(R.id.emailtext);
Button camera = (Button) findViewById(R.id.button1);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0){
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"dummy#email.com"});
i.putExtra(Intent.EXTRA_SUBJECT,"dummy subject");
//Log.d("URI#!##!#!###!", Uri.fromFile(pic).toString() + " " + pic.exists());
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic));
i.setType("image/png");
startActivity(Intent.createChooser(i,"Share this"));
}
});
}
Getting The Image Path and converting path into Uri :
File photo = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Fault", imagename+".png")
Uri imageuri = Uri.fromFile(photo);
Sending through Email Intent :
Intent send_report = new Intent(Intent.ACTION_SEND);
send_report.putExtra(Intent.EXTRA_EMAIL, new String[]{ email_emailid});
send_report.putExtra(Intent.EXTRA_SUBJECT, email_subject);
send_report.putExtra(Intent.EXTRA_STREAM, imageuri);
send_report.putExtra(Intent.EXTRA_TEXT, email_body);
send_report.setType("text/plain");
send_report.setType("image/png");
startActivityForResult(Intent.createChooser(send_report, "Choose an Email client"), 77);

Back to the previous activity on back pressed

I have a function which display FileDialog and Intent to use Bluetooth.
But when I press back button, it comes to previous activity, it is visible but not clickable (like screenshot) and I have to press the back button once again.
I tried function onBackPressed() { finish(); }, but nothing worked properly.
MainActivity:
...
if(item == shareMenu) {
startActivity(new Intent(getBaseContext(), ShareViaBluetoothActivity.class));
}
...
ShareViaBluetoothActivity:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.util.List;
public class ShareViaBluetoothActivity extends Activity {
private static final int DISCOVER_DURATION = 300;
private static final int REQUEST_BLU = 1;
private FileDialog fileDialog;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
private File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
File mPath = new File(Environment.getExternalStorageDirectory(), "//DIR//");
fileDialog = new FileDialog(this, mPath);
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file) {
Log.d(getClass().getName(), "selected file " + file.toString());
setFile(file);
sendViaBluetooth();
}
});
fileDialog.showDialog();
}
public void sendViaBluetooth() {
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if(btAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this device!", Toast.LENGTH_LONG).show();
} else {
enableBluetooth();
}
}
public void enableBluetooth() {
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVER_DURATION);
startActivityForResult(discoveryIntent, REQUEST_BLU);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == DISCOVER_DURATION && requestCode == REQUEST_BLU) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(file.toString())));
intent.setPackage("com.android.bluetooth");
PackageManager pm = getPackageManager();
List<ResolveInfo> appsList = pm.queryIntentActivities(intent, 0);
if(appsList.size() > 0) {
String packageName = null;
String className = null;
boolean found = false;
for(ResolveInfo info : appsList) {
packageName = info.activityInfo.packageName;
if(packageName.equals("com.android.bluetooth")) {
className = info.activityInfo.name;
found = true;
break;
}
}
if (!found) {
Toast.makeText(this, "Bluetooth havn't been found",
Toast.LENGTH_LONG).show();
} else {
intent.setClassName(packageName, className);
startActivity(intent);
}
}
} else {
Toast.makeText(this, "Bluetooth is cancelled", Toast.LENGTH_LONG)
.show();
}
}
}
What you described was not so complete. But I this there are some reasons may result to this, then you can check it.
1. use super.onBackPressed() or give onBackPressed() return can make different
2. please check activity launch mode work.
but you'd better give a more detailed code,then I can help you

Would someone please straighten me out with this Android voice recognition class?

I'm analyzing this Voice Recognizer class and need help understanding this line in the code. What is the role of the following line? Does it create a list of all of the activities on the android platform loaded on the device? I especially find the resolve info bit confusing...
List activities = pm.queryIntentActivities(new Intent(
Here is the code used in context
package com.example.voicerecognitionactivity;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
public class VoiceRecognitionActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private EditText metTextHint;
private ListView mlvTextMatches;
private Spinner msTextMatches;
private Button mbtSpeak;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
metTextHint = (EditText) findViewById(R.id.etTextHint);
mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
msTextMatches = (Spinner) findViewById(R.id.sNoOfMatches);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
}
public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// Specify the calling package to identify your application
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
// Display an hint to the user about what he should say.
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, metTextHint.getText()
.toString());
// Given an hint to the recognizer about what the user is going to say
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
// If number of Matches is not selected then return show toast message
if (msTextMatches.getSelectedItemPosition() == AdapterView.INVALID_POSITION) {
Toast.makeText(this, "Please select No. of Matches from spinner",
Toast.LENGTH_SHORT).show();
return;
}
int noOfMatches = Integer.parseInt(msTextMatches.getSelectedItem()
.toString());
// Specify how many results you want to receive. The results will be
// sorted where the first result is the one with higher confidence.
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches);
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (!textMatchList.isEmpty()) {
// If first Match contains the 'search' word
// Then start web search.
if (textMatchList.get(0).contains("search")) {
String searchQuery = textMatchList.get(0).replace("search",
" ");
Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
search.putExtra(SearchManager.QUERY, searchQuery);
startActivity(search);
} else {
// populate the Matches
mlvTextMatches
.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
textMatchList));
}
}
//Result code for various error.
}else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
showToastMessage("Audio Error");
}else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
showToastMessage("Client Error");
}else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
showToastMessage("Network Error");
}else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
showToastMessage("No Match");
}else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
showToastMessage("Server Error");
}
super.onActivityResult(requestCode, resultCode, data);
}
void showToastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
This, i think, is the simplest way of checking if voice recognition is present or not:
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_LONG);
t.show();
}
ANd after that:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
et_task_notes.setText(text.get(0));
}
break;
}
}
}

how to set text on "to" textarea in email activity

i have made an activity
at subscribe button, i have to send email to some default email for which my code is:
package sditm.app;
import android.R.string;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class subscribeActivity extends Activity {
/** Called when the activity is first created. */
EditText name,age,address;
databaseforsubscribe addressBook;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subscribe);
Button store = (Button)findViewById(R.id.button1);
name=(EditText)findViewById(R.id.editText1);
age=(EditText)findViewById(R.id.editText2);
address=(EditText)findViewById(R.id.editText3);
addressBook = new databaseforsubscribe(this,"addressDB",null,2);
store.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String s=new String();
String m=new String();
String n=new String();
s=name.getText().toString();
m=age.getText().toString();
n=address.getText().toString();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL, "aman4251#gmail.com");
// i.putExtra(Intent.EXTRA_EMAIL , new String[]{"aman4251#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT ,"NAME: "+s+" ; MOBILE: "+m+" ; EMAIL: "+n);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(subscribeActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
which open an intent like this
now either i have to set the email id to "To" textbox (and make it uneditable"), or to automatically click on that "send" button so that user dont see this intent and email is send in back ground..
Try this code:
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"recipient#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT , "body of email");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MyActivity.this, "There are no email clients installed.",Toast.LENGTH_SHORT).show();
}
Hi try this piece of code
Intent sendIntent = new Intent(Intent.ACTION_SEND);
// Add attributes to the intent
sendIntent.putExtra(Intent.EXTRA_EMAIL, "");
sendIntent.putExtra(Intent.EXTRA_CC, "");
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "");
sendIntent.putExtra(Intent.EXTRA_TEXT, "");
sendIntent.setType("text/plain");
PackageManager pm = getPackageManager();
List<ResolveInfo> activityList = pm
.queryIntentActivities(sendIntent, 0);
Iterator<ResolveInfo> it = activityList.iterator();
boolean isEmailSetUp = false;
while (it.hasNext()) {
ResolveInfo info = it.next();
if ("com.android.email.activity.MessageCompose"
.equalsIgnoreCase(info.activityInfo.name)) {
isEmailSetUp = true;
sendIntent.setClassName(info.activityInfo.packageName,
info.activityInfo.name);
}
}
if (isEmailSetUp) {
startActivity(sendIntent);
} else {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("No Mail Accounts");
dlgAlert.setTitle("Please set up a Mail account in order to send email");
dlgAlert.setPositiveButton(getResources().getString(R.string.ok),
null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
i dono know whether it is possible to make the email id edit text uneditable
But you can send mail in background by click on button
for that refer this link

How to upload file to Amazon S3 from Android

Hi, I have integrated these codes such that I will be able to upload file rather than photo selected to AmazonS3, but for some parts, they are still part of uploading image suchs as "intent.setType("image/");"*
Please let me know if anything can be changed to these codes to have my file uploaded to AmazonS3 successfully. Thank you very much.
package com.amazonaws.demo;
import java.net.URL;
import java.util.Date;
import com.amazonaws.demo.R;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.ResponseHeaderOverrides;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
public class S3UploaderActivity extends Activity {
private AmazonS3Client s3Client = new AmazonS3Client( new BasicAWSCredentials( Constants.ACCESS_KEY_ID, Constants.SECRET_KEY ) );
private Button selectFile = null;
private Button showInBrowser = null;
private static final int FILE_SELECTED = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
selectFile = (Button) findViewById(R.id.select_file_button);
selectFile.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Start the image picker.
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, FILE_SELECTED);
}
});
showInBrowser = (Button) findViewById(R.id.show_in_browser_button);
showInBrowser.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Ensure that the image will be treated as such.
ResponseHeaderOverrides override = new ResponseHeaderOverrides();
override.setContentType( "image/jpeg" );
// Generate the presigned URL.
Date expirationDate = new Date( System.currentTimeMillis() + 3600000 ); // Added an hour's worth of milliseconds to the current time.
GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest( Constants.getPictureBucket(), Constants.FILE_NAME );
urlRequest.setExpiration( expirationDate );
urlRequest.setResponseHeaders( override );
URL url = s3Client.generatePresignedUrl( urlRequest );
// Display in Browser.
startActivity( new Intent( Intent.ACTION_VIEW, Uri.parse( url.toURI().toString() ) ) );
}
catch ( Exception exception ) {
S3UploaderActivity.this.displayAlert( "Browser Failure", exception.getMessage() );
}
}
});
}
// This method is automatically called by the image picker when an image is selected.
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case FILE_SELECTED:
if (resultCode == RESULT_OK) {
// THe file location of the image selected.
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
// Put the image data into S3.
try {
s3Client.deleteBucket(Constants.getPictureBucket());
PutObjectRequest por = new PutObjectRequest( Constants.getPictureBucket(), Constants.FILE_NAME, new java.io.File( filePath) ); // Content type is determined by file extension.
s3Client.putObject( por );
}
catch ( Exception exception ) {
displayAlert( "Upload Failure", exception.getMessage() );
}
}
}
}
// Display an Alert message for an error or failure.
protected void displayAlert( String title, String message ) {
AlertDialog.Builder confirm = new AlertDialog.Builder( this );
confirm.setTitle( title);
confirm.setMessage( message );
confirm.setNegativeButton( "OK", new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int which ) {
S3UploaderActivity.this.finish();
}
} );
confirm.show().show();
}
}
You could use this http://code.google.com/p/android-file-dialog/ activity and get the file selected by user.

Categories

Resources