Sunday, 16 December 2012
Upload File to specific folder in Google Drive From Android (Eclipse Development)
First of all, you must put all file+folder into FileRequest and query the folder String as "Storage" (one of my foldername under Google Drive), then obtian folder id by using parent.getId() function and proceed last step to upload files.
for (int count = 0 ; count < Files.length;count ++){
String folderId = null;
File fileContent = new java.io.File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/" + Files[count].getName());
FileContent mediaContent = new FileContent("image/jpeg", fileContent);
Files.List request = drive
.files()
.list()
.setMaxResults(200)
.setQ("'root' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false and title='Storage' ");
FileList files = request.execute();
//ParentReference pr = files.getItems();
for (com.google.api.services.drive.model.File parent : files.getItems()) {
Log.d(TAG,"folder id:" + parent.getId());
folderId=parent.getId();
}
com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
body.setTitle(fileContent.getName());
body.setMimeType("image/jpeg");
body.setParents(
Arrays.asList(new ParentReference().setId(folderId)));
//--body.setMimeType("video/mp4");
com.google.api.services.drive.model.File file = drive.files().insert(body, mediaContent).execute();
}
Friday, 14 December 2012
How to programmatically upload file from android to Google Drive (eclipse development)
For purpose I created out this post of tutorial simply felt sympathy to lack of practical + example documentation and a lot of mistake (found on "https://developers.google.com/drive/quickstart-android" ) support to programmatically upload file from Android to Google Drive by using Oath2 authority protocol (You must use it not other choises). Mostly if you have account setup on your gmail account on your android phone, it will automatically upload it to Google somethings known backend server which is not provide support to browseable but only sync it, but I preferred always "Do It Yourself (DIY)", with this ability you can master it to upload even sync your offline document , message, sms or contact details to your google drive for future see able or even your want to share it with your partners.
I've grind it until taken 13 day simply to under for all of these awesome Things!!!!
11.Don't forget include below external Google Drive API lib into libs folder of your project location.
I've grind it until taken 13 day simply to under for all of these awesome Things!!!!
6.
10.Download my copied android file attachment from "http://rapidgator.net/file/63338103/com.android.example.googledrivet.GoogleTest.zip.html" or create out a new project and copied the following code to your .java class file.
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.common.base.Preconditions;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class GoogleTest 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;
private static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
private static final String CLIENTSECRETS_LOCATION ="client_secrets.json";
private static final String CLIENT_ID ="YOUR_CLIENT_ID";
private static final String CLIENT_SECRET="YOUR_CLIENT_SECRET ";
private static GoogleClientSecrets clientSecrets = null;
private static final List<String> SCOPES = Arrays.asList(
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_test);
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();
// saveFileToDrive();
}
}
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"));
fileUri = Uri.fromFile(new java.io.File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/" + "IMG_"
+ timeStamp + ".jpg"));
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, CAPTURE_IMAGE);
}
private void saveFileToDrive() {
final String TAG= null;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
//media scanned to each file for every new times it was created
File fil=new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/");
File[] Files=fil.listFiles();
for (int count = 0 ; count < Files.length;count ++){
File fs = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/" + Files[count].getName());
MediaScannerConnection.scanFile(GoogleTest.this, new String[]{fs.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// TODO Auto-generated method stub
}
});
}
// File's binary content
AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] accounts = am.getAccountsByType("com.google");
AccountManagerFuture<Bundle> accFut = AccountManager.get(getApplicationContext()).getAuthToken(accounts[0], "oauth2:"+"https://www.googleapis.com/auth/drive", true, null, null);
Bundle authTokenBundle;
authTokenBundle = accFut.getResult();
final String token = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();
am.invalidateAuthToken("com.google", token);
HttpTransport httpTransport2 = new NetHttpTransport();
Log.d(TAG,"AuthToken: "+token);
JacksonFactory jsonFactory2 = new JacksonFactory();
Log.d(TAG,"RefreshToken 123");
//Intent intent = new Intent();
String accountname=authTokenBundle.get(AccountManager.KEY_ACCOUNT_NAME).toString();
Log.d(TAG,"Account Name : " + accountname);
GoogleCredential credent=new GoogleCredential.Builder()
.setTransport(new NetHttpTransport())
.setJsonFactory(new JacksonFactory())
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.build().setAccessToken(token);
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, credent);
final Drive drive = b.build();
Log.d(TAG,"Drive is been build 789");
java.io.File fileContent = new java.io.File(fileUri.getPath());
// java.io.File fileContent = new java.io.File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/IMG.jpg");
FileContent mediaContent = new FileContent("image/jpeg", fileContent);
// File's metadata.
com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
body.setTitle(fileContent.getName());
body.setMimeType("image/jpeg");
com.google.api.services.drive.model.File file = drive.files().insert(body, mediaContent).execute();
Log.d(TAG,"File is been sent 101112");
if (file != null) {
showToast("Photo is uploaded to Google drive: " + file.getTitle());
startCameraIntent();
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
}
private static GoogleClientSecrets loadClientSecrets(JsonFactory jsonFactory) throws IOException {
if (clientSecrets == null) {
InputStream inputStream = GoogleTest.class.getResourceAsStream(CLIENTSECRETS_LOCATION);
Preconditions.checkNotNull(inputStream, "missing resource %s", CLIENTSECRETS_LOCATION);
clientSecrets = GoogleClientSecrets.load(jsonFactory, inputStream);
Preconditions.checkArgument(!clientSecrets.getDetails().getClientId().startsWith("[[")
&& !clientSecrets.getDetails().getClientSecret().startsWith("[["),
"Please enter your client ID and secret from the Google APIs Console in %s from the "
+ "root samples directory",CLIENTSECRETS_LOCATION);
}
return clientSecrets;
}
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();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_google_test, menu);
return true;
}
}
11.Don't forget include below external Google Drive API lib into libs folder of your project location.
12. Last for your manifest file, you need to include four lines of below to allow access permission.
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
Saturday, 27 October 2012
WIFI Transfer Multiples File from Android to differ location inside sdcard, Smb Host and Remote Host (WAN)
WIFI Transfer Multiples File from Android to sdcard, Smb Host and Remote Host
-The main purpose I created this tutorial post is to help those who want backup\instant transfer file from android to Smb Host ( PC client in the same network range), Remote Host ( Host far away from your place with differ in static IP address), another location in same internal storage of sdcard. Of cause you can customized to suit your own requirement with easy press one button send to multiple location as you need.
-Don't forget to allow the port 5991 to be opened.(any port is never mind, my using port 5991 at here tutorial).
-Refer to my attachment contains Server Socket folder, placed it into your eclipse Java Project and export
it into Runable .Jar file and proceed into .exe file by using Launch4j (google & download it!!). Of cause
you can use my ServerRun.exe which has convert from ServerRun.jar. This time you can dounble it to run this .exe file and it would be appeared as javaw.exe in background windows.
P.S: The port 5991 is found to be ready open by verify under open port test after running on this .exe file.
(before it is closed.)
its server coding,
-For Smb Host side, I've created "C:\share" folder and made it it to be SHARED. So I can transfer my file from android (IP Address : 192.168.1.3) to this Smb Host (192.168.1.2). Simple!!!
-Finally, this is my simple android application code used to be performed like these.
import java.io.BufferedInputStream;
-My Project Attachment Download Link =
http://rapidgator.net/file/52871160/FileTransfer.rar.html
-Don't forget to allow the port 5991 to be opened.(any port is never mind, my using port 5991 at here tutorial).
-Refer to my attachment contains Server Socket folder, placed it into your eclipse Java Project and export
it into Runable .Jar file and proceed into .exe file by using Launch4j (google & download it!!). Of cause
you can use my ServerRun.exe which has convert from ServerRun.jar. This time you can dounble it to run this .exe file and it would be appeared as javaw.exe in background windows.
P.S: The port 5991 is found to be ready open by verify under open port test after running on this .exe file.
(before it is closed.)
its server coding,
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class ServerRun {
/**
* @param args
*/
public static void main(String[] args) throws IOException,EOFException {
// TODO Auto-generated method stub
FileOutputStream fos;
BufferedOutputStream bos;
OutputStream output;
DataOutputStream dos;
int len;
int smblen;
InputStream in;
boolean flag=true;
DataInputStream clientData;
BufferedInputStream clientBuff;
ServerSocket serverSocket = new ServerSocket(5991);
Socket clientSocket = null;
clientSocket = serverSocket.accept();
while (true){
//while(true && flag==true){
while(flag==true){
in = clientSocket.getInputStream(); //used
clientData = new DataInputStream(in); //use
clientBuff = new BufferedInputStream(in); //use
System.out.println("Starting...");
int fileSize = clientData.read();
ArrayList<File>files=new ArrayList<File>(fileSize); //store list of filename from client directory
ArrayList<Integer>sizes = new ArrayList<Integer>(fileSize); //store file size from client
//Start to accept those filename from server
for (int count=0;count < fileSize;count ++){
File ff=new File(clientData.readUTF());
files.add(ff);
}
for (int count=0;count < fileSize;count ++){
sizes.add(clientData.readInt());
}
for (int count =0;count < fileSize ;count ++){
if (fileSize - count == 1){
flag =false;
}
len=sizes.get(count);
System.out.println("File Size ="+len);
output = new FileOutputStream("C:/share/" + files.get(count));
dos=new DataOutputStream(output);
bos=new BufferedOutputStream(output);
byte[] buffer = new byte[1024];
bos.write(buffer, 0, buffer.length); //This line is important
// while (len > 0 && (smblen = clientData.read(buffer)) > 0) {
while (len > 0 && (smblen = clientData.read(buffer, 0, (int) Math.min(buffer.length,len))) != -1) {
dos.write(buffer, 0, smblen);
len = len - smblen;
dos.flush();
}
dos.close(); //It should close to avoid continue deploy by resource under view
}
}
if (flag==false){
clientSocket = serverSocket.accept();
flag = true;
}
} //end of while(true)
}
}
-For Smb Host side, I've created "C:\share" folder and made it it to be SHARED. So I can transfer my file from android (IP Address : 192.168.1.3) to this Smb Host (192.168.1.2). Simple!!!
-Finally, this is my simple android application code used to be performed like these.
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
import android.app.Activity;
import android.content.Context;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class FileTransferLite extends Activity {
private Button send;
private Button sendWan;
private Socket socket;
private File f,fdst;
private FileInputStream fin,fises;
private static Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_transfer_lite);
send=(Button)findViewById(R.id.send);
sendWan=(Button)findViewById(R.id.sendWan);
FileTransferLite.context = getApplicationContext();
send.setOnClickListener(new OnClickListener(){
public void onClick(View view){
try {
NtlmPasswordAuthentication authentication = new NtlmPasswordAuthentication(null, "x", "0465"); // replace with actual values
System.out.println("Connecting...");
File fil=new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/");
File[] Files=fil.listFiles();
for (int count=0;count < Files.length;count ++){
System.out.println(Files[count].getName());
}
///~~~~~~~~~~~~~~~~~~~~~ sending Multiple Files to sdcard inside~~~///
for (int count = 0 ; count < Files.length;count ++){
fin=new FileInputStream(Files[count].toString());
//String filename= Files[count].getName();
FileOutputStream fos= new FileOutputStream(Environment.getExternalStorageDirectory() + "/Storage/" + Files[count].getName() );
byte[] buff = new byte[8192];
int lenf;
while ((lenf = fin.read(buff)) > 0) {
fos.write(buff, 0, lenf);
fos.flush();
}
fos.close();
File fs = new File(Environment.getExternalStorageDirectory() + "/Storage/" + Files[count].getName());
MediaScannerConnection.scanFile(FileTransferLite.this, new String[]{fs.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// TODO Auto-generated method stub
}
});
}
System.out.println("New files is about created");
Toast.makeText(getApplicationContext(),"New Files is about created", Toast.LENGTH_SHORT).show();
//~~~~sending file to smb host in the same network
//byte[] buf = new byte[1024];
for (int count = 0 ; count < Files.length;count ++ ){
fises=new FileInputStream(Files[count].toString());
SmbFile fss=new SmbFile("smb://192.168.1.2/share/" + Files[count].getName(),authentication);
SmbFileOutputStream smbout=new SmbFileOutputStream(fss);
byte[] buf = new byte[8192];
int smblen;
while ((smblen = fises.read(buf)) > 0) {
smbout.write(buf, 0, smblen);
smbout.flush();
}
smbout.close();
}
Toast.makeText(getApplicationContext(),"Transfer file is completed!!", Toast.LENGTH_LONG).show();
//closing FileInputStream
fin.close();
fises.close();
//close socket connection
//socket.close();
}
catch(Exception e){
System.out.println("Error::"+e);
//System.out.println(e.getMessage());
//e.printStackTrace();
//Log.i("******* :( ", "UnknownHostException");
}
}
});
sendWan.setOnClickListener(new OnClickListener(){
public void onClick(View view){
try {
Socket sock = new Socket("219.92.229.225", 5991); //replace with your remote host static IP address.
System.out.println("Connecting.........");
File myFile = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera/");
File[] Files = myFile.listFiles();
OutputStream os = sock.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(Files.length);
for (int count=0;count<Files.length;count ++){
dos.writeUTF(Files[count].getName());
}
for (int count=0;count<Files.length;count ++){
int filesize = (int) Files[count].length();
dos.writeInt(filesize);
}
for (int count=0;count<Files.length;count ++){
int filesize = (int) Files[count].length();
byte [] buffer = new byte [filesize];
//FileInputStream fis = new FileInputStream(myFile);
FileInputStream fis = new FileInputStream(Files[count].toString());
BufferedInputStream bis = new BufferedInputStream(fis);
//Sending file name and file size to the server
bis.read(buffer, 0, buffer.length); //This line is important
dos.write(buffer, 0, buffer.length);
dos.flush();
//dos.close();
}
//Closing socket
//dos.close();
sock.close();
Toast.makeText(getApplicationContext(),"Transfer file is completed!!", Toast.LENGTH_LONG).show();
socket.close();
}
catch(Exception e){
System.out.println("Error::"+e);
//System.out.println(e.getMessage());
//e.printStackTrace();
//Log.i("******* :( ", "UnknownHostException");
}
}
});
}
}
-One more important things for communication or even transfer file to SMB host, you are required to have JCIFS libraries which is know as external library that is unsupported in eclipse where you need to download latest jcifs-1.3.17 from http://jcifs.samba.org/src/. Extract it and you will find "jcifs-1.3.17" .jar file.
The way to include this external library:
-Right-click your android project folder in project explorer, click properties, click on libraries tab,
click on "Add External JARs button to add "jcifs-1.3.17.jar" file.
-Don't forget to check this libraries on "ORDER and ADD"
Now you are able to use below libraries import link.
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
-My Project Attachment Download Link =
http://rapidgator.net/file/52871160/FileTransfer.rar.html
Subscribe to:
Posts (Atom)