OnDestroy() of Intent - android

I'm convert from a googledrive example to my class that can handle It easier.
On this example, It call a menthod that return an Intent (this intent used to choose google account).
Main activity call startActivityForResult(intent). and check session & login on onActivityResult.
The googledrive example
public class GoogleActivity extends Activity {
static final int REQUEST_ACCOUNT_PICKER = 1;
static final int REQUEST_AUTHORIZATION = 2;
static final int CAPTURE_IMAGE = 3;
private static Uri fileUri;
private static Drive service;
private GoogleAccountCredential credential;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
//Start account picker here (the intent I've told above)
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
//credential.newChooseAccountIntent() return an intent that can choose google account
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_ACCOUNT_PICKER:
//Process it when intent exit
if (resultCode == RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
service = getDriveService(credential);
startCameraIntent();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
saveFileToDrive();
} else {
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
break;
case CAPTURE_IMAGE:
if (resultCode == Activity.RESULT_OK) {
saveFileToDrive();
}
}
}
private void startCameraIntent() {
String mediaStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
fileUri = Uri.fromFile(new java.io.File(mediaStorageDir + java.io.File.separator + "IMG_" + timeStamp + ".jpg"));
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, CAPTURE_IMAGE);
}
private void saveFileToDrive() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
// File's binary content
java.io.File fileContent = new java.io.File(fileUri.getPath());
FileContent mediaContent = new FileContent("image/jpeg", fileContent);
// File's metadata.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType("image/jpeg");
File file = service.files().insert(body, mediaContent).execute();
if (file != null) {
showToast("Photo uploaded: " + file.getTitle());
startCameraIntent();
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
private Drive getDriveService(GoogleAccountCredential credential) {
return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});
}
}
Now I want to create a class to handle some feature of googledrive including login. My Login() menthod handle everything about login.
I can call Account Picker intent outside main activity but I can't handle when that intent exit/destroy.
My class is something like this:
public class GoogleHandler {
Activity act;
public GoogleHandler(Activity act) {
this.act = act;
}
public void Login() {
//start
act.startActivity(intent, requestCode);
}
// And then, how to handle when intent exit ??
}
Any suggestion also helped me.

The Intent that you pass to startActivity() doesn't ever start or finish. That's not what Intents do; Intents start up another Activity (or Service), which then starts and finishes.
When the Google Account Picker Activity finishes, the onActivityResult() method of the calling Activity is called. In your example, act recvieves a call to onActivityResult(). You can see an example of how to properly use the result in the Google Drive sample code you posted.
In order to properly receive this callback, the act Activity must override onActivityResult(). You cannot do this within the Login() method or the GoogleHandler class unless you change GoogleHandler to an Activity.

Related

UCrop from a fragment no requestCode being sent

I am trying to use Ucrop from a fragment. The issue I am facing is that onActivityresult is not receiving requestCode == UCrop.REQUEST_CROP thus not performing the actions I need to do with the image. I have searched around for tutorials but I haven't managed to find any.
The following is the code of the fragment that is using UCrop:
public class FragmentSettingsTabImage extends Fragment {
private String TAG = "----->";
Tools t;
private String currentPhotoPath;
private final int REQUEST_TAKE_PHOTO = 1;
private final int CAMERA_PERMISSIONS = 2;
private ImageView imgTabImageDriver;
private Button btnSettingsSaveImage;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good so launch take picture from here
dispatchTakePictureIntent();
} else {
// Permission denied. Warn the user and kick out of app
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.permsDeniedCameraTitle);
builder.setMessage(R.string.permsDeniedCameraMessage);
builder.setCancelable(false);
builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Objects.requireNonNull(getActivity()).finishAffinity();
}
});
builder.create().show();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
Uri starturi = Uri.fromFile(new File(currentPhotoPath));
Uri destinationuri = Uri.fromFile(new File(currentPhotoPath));
UCrop.Options options = AppConstants.makeUcropOptions(Objects.requireNonNull(getActivity()));
UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity());
}
Log.d(TAG, "onActivityResult: CCCCCCC" + resultCode + " " + requestCode);
// On result from cropper add to imageview
getActivity();
if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
final Uri resultUri = UCrop.getOutput(data);
assert resultUri != null;
File imgFile = new File(resultUri.getPath());
Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getActivity()));
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
builder.build().load(imgFile).into(imgTabImageDriver, new Callback() {
#Override
public void onSuccess() {
btnSettingsSaveImage.setEnabled(true);
}
#Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
SharedPreferences preferences = Objects.requireNonNull(this.getActivity()).getSharedPreferences("mykago-driver", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
View view = inflater.inflate(R.layout.fragment_settings_tab_image, container, false);
imgTabImageDriver= view.findViewById(R.id.imgTabImageDriver);
ImageView imgTakeSettingsDriverPicture = view.findViewById(R.id.imgTakeSettingsDriverPicture);
btnSettingsSaveImage = view.findViewById(R.id.btnSettingsSaveImage);
imgTakeSettingsDriverPicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
imgTabImageDriver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
btnSettingsSaveImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putString("driver_picture", currentPhotoPath);
editor.apply();
}
});
Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getContext()));
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
Log.d(TAG, "onCreateView: " + preferences.getString("driver_picture", ""));
builder.build().load(new File(preferences.getString("id_picture", ""))).into(imgTabImageDriver);
return view;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(Objects.requireNonNull(getActivity()).getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("IMAGE CREATION", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.mytestapp.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "didimage_" + timeStamp + "_";
File storageDir = Objects.requireNonNull(getActivity()).getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".png",
storageDir
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
}
The same code from a normal activity works without any issues. Any help appreciated.
Managed to solve the issue. To pass the result of the UCrop activity to the fragment and not to the hosting activity you need to call the UCrop....start() method as follows:
UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity().getApplicationContext(), getFragmentManager().findFragmentByTag("your_fragment_tag"));
so
.start(Context, Fragment)
This will make sure that the onActivityResult of the fragment gets called and not the one of the hosting activity.
This works also:
UCrop.of(sourceUri,destinationUri)
.withOptions(options)
.start(getActivity(),YourFragment.this);
If you want to start uCrop activity from Fragment use this.
UCrop.of(uri, destinationFileName)
.withAspectRatio(1, 1)
.start(getContext(), this, UCrop.REQUEST_CROP);

Open DialogFragment after using camera application in Android

I am starting from my fragment the standard android camera app. Everything works fine and the image gets saved as I wish. After the user has taken a picture (and only then) I would like to launch a DialogFragment.
I tried using intents and calling onActivetyResult() from the same fragment. But onActivityResult() never gets called.
How I start the camera in my fragment:
MyCamera camera = new MyCamera(getActivity());
camera.start();
Im my MyCamera class I am starting the intent like so:
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
activity.startActivityForResult(takePictureIntent, Constants.TAKE_PHOTO);
Back in the the fragment I am calling onActivityResult():
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
// do something
}
}
How can I achieve this task? Thanks in advance for the help!
Here the entire MyCamera class:
public class MyCamera {
private Activity activity;
private static final String TAG = "MyCamera";
private String currentPhotoPath;
private String currentFileName;
private File currentFile;
private Uri contentUri;
public MyCamera(Activity activity) {
this.activity = activity;
}
public void start() {
dispatchPictureIntent();
addPictureToGallery();
currentPhotoPath = null;
}
private void dispatchPictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// check if device has camera
if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
currentPhotoPath = photoFile.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(activity, R.string.msg_picture_not_saved, Toast.LENGTH_LONG).show();
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
takePictureIntent.putExtra(Constants.IMAGE_FILE_NAME, currentFileName);
activity.startActivityForResult(takePictureIntent, Constants.TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// set up storage dir
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
if (!storageDir.exists()) {
if (!storageDir.mkdirs()) {
Log.e(TAG, "failed to create directory");
return null;
}
}
// set up file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fileName = "img_" + timeStamp + "_";
String suffix = ".jpg";
File image = File.createTempFile(fileName, suffix, storageDir);
currentFileName = image.getName();
currentFile = image;
return image;
}
private void addPictureToGallery() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
contentUri = getUri(currentPhotoPath);
mediaScanIntent.setData(contentUri);
activity.sendBroadcast(mediaScanIntent);
}
private Uri getUri(String currentPhotoPath) {
File f = new File(currentPhotoPath);
return Uri.fromFile(f);
}
}
Based on this post: onActivityResult is not being called in Fragment
try adding in your hosting activity
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
It will allow to pass unhandled activity result to your fragment.
Also, make sure you call fragment.startActivityForResult() instead of activity.startActivityForResult().
I tried using intents and calling onActivetyResult() from the same fragment. But onActivityResult() never gets called.
That is because you are calling startActivityForResult() on the Activity, not on the fragment. Your onActivityResult() method goes on the object on which you call startActivityForResult(). So, if you want the fragment to have onActivityResult(), call startActivityForResult() on the fragment.

Android: Upload image just taken bij camera

I'm trying to make an app that uses the camera to take photos and sends this to my NAS, I managed to do create an app through a tutorial, which takes a picture, saves the picture and shows it onscreen. Another tutorial shows me how to upload a "selected" image by pressing an "extra" button on the screen, it's just that I want to get rid of this step and instead of showing the picture, it directly sends the picture to my NAS.
The current app I created:
package com.deshpande.camerademo;
public class MainActivity extends AppCompatActivity {
private Button takePictureButton;
private ImageView imageView;
private Uri file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePictureButton = (Button) findViewById(R.id.button_image);
imageView = (ImageView) findViewById(R.id.imageview);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(false);
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
takePictureButton.setEnabled(true);
}
}
}
public void takePicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = Uri.fromFile(getOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, 100);
}
private static File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "WedCam");
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
Log.d("WedCam", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
try {
final FTPClient client = new FTPClient();
final File image = new File(file.getPath());
final FileInputStream fis = new FileInputStream(image);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
client.connect("ftp://127.0.0.1:2221");
client.login("francis", "francis");
client.storeFile(image.getName(), fis);
client.logout();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
Thanks to #Matthias F. I got it all working, this guy is great!
You need to use your saved URI from the camera for the FileInputStream. Try it with this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
try {
final FTPClient client = new FTPClient();
final File image = new File(file.getPath());
final FileInputStream fis = new FileInputStream(image);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
client.connect("127.0.0.1", 2221);
client.login("francis", "francis");
client.setFileType(FTP.BINARY_FILE_TYPE);
client.storeFile(image.getName(), fis);
client.logout();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Now the FileInputStream points to the created image.
EDIT:
The problem was that the upload was executed on the ui thread and that is not allowed in android. Now a new thead is created for the upload process. Also I forgot to say that you need to access a android permission for using network functionalities. So you need to set
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> in the AndroidManifest.xml.

error in google drive api example

this code is from google drive api example and i am trying to implement this code but it show error in line .....credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);....and the given error is......The method usingOAuth2(Context, Collection) in the type GoogleAccountCredential is not applicable for the arguments (MainActivity, String)....how slove this error...
public class MainActivity extends Activity {
static final int REQUEST_ACCOUNT_PICKER = 1;
static final int REQUEST_AUTHORIZATION = 2;
static final int CAPTURE_IMAGE = 3;
private static Uri fileUri;
private static Drive service;
private GoogleAccountCredential credential;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
credential = GoogleAccountCredential.usingOAuth2(this,
DriveScopes.DRIVE);
startActivityForResult(credential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
}
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null
&& data.getExtras() != null) {
String accountName = data
.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
service = getDriveService(credential);
startCameraIntent();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
saveFileToDrive();
} else {
startActivityForResult(credential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
}
break;
case CAPTURE_IMAGE:
if (resultCode == Activity.RESULT_OK) {
saveFileToDrive();
}
}
}
private void startCameraIntent() {
String mediaStorageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getPath();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)
.format(new Date());
fileUri = Uri.fromFile(new java.io.File(mediaStorageDir
+ java.io.File.separator + "IMG_" + timeStamp + ".jpg"));
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, CAPTURE_IMAGE);
}
private void saveFileToDrive() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
// File's binary content
java.io.File fileContent = new java.io.File(fileUri
.getPath());
FileContent mediaContent = new FileContent("image/jpeg",
fileContent);
// File's metadata.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType("image/jpeg");
File file = service.files().insert(body, mediaContent)
.execute();
if (file != null) {
showToast("Photo uploaded: " + file.getTitle());
startCameraIntent();
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
private Drive getDriveService(GoogleAccountCredential credential) {
return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential).build();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast,
Toast.LENGTH_SHORT).show();
}
});
}
}
The answer is in the question.
The method expects a Collection object, but you are passing a simple String object.
And that is not the only error. I have an extensive list of required changes and a working example hosted at:
https://github.com/hanscappelle/more-android-examples/blob/master/DriveQuickstart/README.md

How to upload files from my application to google drive

How to upload files from my application to google drive. For this application i followed the https://developers.google.com/drive/quickstart-android steps it works fine upto take picture then the picture will not be uploaded in googel drive.
public class MainActivity extends Activity {
static final int REQUEST_ACCOUNT_PICKER = 1;
static final int REQUEST_AUTHORIZATION = 2;
static final int CAPTURE_IMAGE = 3;
private static Uri fileUri;
private static Drive service;
private GoogleAccountCredential credential;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
service = getDriveService(credential);
startCameraIntent();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
saveFileToDrive();
} else {
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
break;
case CAPTURE_IMAGE:
if (resultCode == Activity.RESULT_OK) {
saveFileToDrive();
}
}
}
private void startCameraIntent() {
String mediaStorageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getPath();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
fileUri = Uri.fromFile(new java.io.File(mediaStorageDir + java.io.File.separator + "IMG_"
+ timeStamp + ".jpg"));
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, CAPTURE_IMAGE);
}
private void saveFileToDrive() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
// File's binary content
java.io.File fileContent = new java.io.File(fileUri.getPath());
FileContent mediaContent = new FileContent("image/jpeg", fileContent);
// File's metadata.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType("image/jpeg");
File file = service.files().insert(body, mediaContent).execute();
if (file != null) {
showToast("Photo uploaded: " + file.getTitle());
startCameraIntent();
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
private Drive getDriveService(GoogleAccountCredential credential) {
return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
.build();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run()
{
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});
}
}

Categories

Resources