从SD卡中选择的图片,并将其存储到谷歌驱动器 [英] selecting picture from sdcard and store it to google drive

查看:184
本文介绍了从SD卡中选择的图片,并将其存储到谷歌驱动器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提出的android应用程序,它会简单地选择从SD卡(手机图库)的图像,并将其存储到谷歌驱动器。我做了很多的精力在这,我从由谷歌开发者提供的code的帮助驱动快速启动。 我做了我的main.xml文件中的Button控件,当这个按钮,它需要在手机画廊里,然后点击,当我选择一个图片什么也没有发生。

I am making android app which will simply pick an image from sdcard (phone gallery) and store it to Google drive. I did a lot much effort on this, I took help from the code provided by Google developers on drive quick start. I made a Button control in my main.xml file, when click on this button it takes inside the phone gallery and when I select a picture nothing is happening

这是登录猫从我的Eclipse IDE

This is Log Cat from my eclipse IDE

 05-13 05:05:47.890: D/gralloc_goldfish(16802): Emulator without GPU emulation detected.
05-13 05:08:00.600: W/ActivityThread(17711): Application com.camera is waiting for the debugger on port 8100...
05-13 05:08:00.660: I/System.out(17711): Sending WAIT chunk
05-13 05:08:00.690: I/dalvikvm(17711): Debugger is active
05-13 05:08:00.700: I/System.out(17711): Debugger has connected
05-13 05:08:00.700: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:00.980: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:01.180: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:01.389: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:01.590: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:01.790: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:01.990: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:02.190: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:02.400: I/System.out(17711): waiting for debugger to settle...
05-13 05:08:02.610: I/System.out(17711): debugger has settled (1374)
05-13 05:08:05.090: I/Choreographer(17711): Skipped 40 frames!  The application may be doing too much work on its main thread.
05-13 05:08:05.280: D/gralloc_goldfish(17711): Emulator without GPU emulation detected.
05-13 05:08:10.120: I/Choreographer(17711): Skipped 47 frames!  The application may be doing too much work on its main thread.
05-13 05:08:13.369: I/Choreographer(17711): Skipped 89 frames!  The application may be doing too much work on its main thread.
05-13 05:08:14.699: D/dalvikvm(17711): GC_FOR_ALLOC freed 52K, 8% free 2544K/2752K, paused 187ms, total 220ms
05-13 05:08:14.879: I/dalvikvm-heap(17711): Grow heap (frag case) to 4.455MB for 1920016-byte allocation
05-13 05:08:15.029: D/dalvikvm(17711): GC_FOR_ALLOC freed 4K, 5% free 4415K/4628K, paused 141ms, total 141ms
05-13 05:08:15.059: W/CursorWrapperInner(17711): Cursor finalized without prior close()
05-13 05:08:15.329: D/dalvikvm(17711): GC_CONCURRENT freed <1K, 5% free 4415K/4628K, paused 13ms+34ms, total 303ms
05-13 05:08:16.469: I/Choreographer(17711): Skipped 1536 frames!  The application may be doing too much work on its main thread.
05-13 05:08:17.159: I/Choreographer(17711): Skipped 268 frames!  The application may be doing too much work on its main thread.
05-13 05:08:18.049: I/Choreographer(17711): Skipped 41 frames!  The application may be doing too much work on its main thread.
05-13 05:08:22.580: W/AbstractGoogleClient(17711): Application name is not set. Call Builder#setApplicationName.
05-13 05:08:22.970: I/Choreographer(17711): Skipped 82 frames!  The application may be doing too much work on its main thread.

下面是我的Java code

Here is my Java Code

import java.io.IOException;
import com.camera.R;
import com.google.api.client.extensions.android.http.AndroidHttp;
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.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import android.accounts.AccountManager;
import android.app.Activity;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity{

    private static final int REQUEST_ACCOUNT_PICKER = 1;
    private static final int SELECT_PICTURE = 3;
    private static final int REQUEST_AUTHORIZATION = 2;

    private static Drive service;
    private GoogleAccountCredential credential;  
   private static Uri selectedImageUri;

    private String selectedImagePath;
    private ImageView img;
    private TextView tv;
    Intent pictureintent;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        img = (ImageView)findViewById(R.id.ImageView01);
        ((Button) findViewById(R.id.Button01)).setOnClickListener(new OnClickListener() {
                     public void onClick(View v) {

                         pictureintent = new Intent();
                         pictureintent.setType("image/jpeg");
                         pictureintent.setAction(Intent.ACTION_GET_CONTENT);
                         pictureintent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
                         startActivityForResult(pictureintent, SELECT_PICTURE);

                    }
                }); 


    }


    public void onActivityResult(int requestCode, int resultCode, 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);
                  saveFileToDrive();
                }
              }
              break;
        case REQUEST_AUTHORIZATION:
              if (resultCode == Activity.RESULT_OK) {
                saveFileToDrive();
              } else {
                startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
              }

        case SELECT_PICTURE:
        if (resultCode == Activity.RESULT_OK) {

                selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                tv = (TextView) findViewById(R.id.text1);
                tv.setText("File Path: " + selectedImagePath);
                //showToast("File Path: " + selectedImagePath);
                //System.out.println("Image Path : " + selectedImagePath);
                img.setImageURI(selectedImageUri); 
                startpictureIntent();

        }

    }
}



    private Drive getDriveService(GoogleAccountCredential credential) {
        return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
            .build();
      }

    public void startpictureIntent(){


        credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
        startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);


    }



    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(selectedImageUri.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());

              }

            }catch (UserRecoverableAuthIOException e) {
                startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
            }   catch (IOException e) {
              e.printStackTrace();
            }
          }
        });
        t.start();
      }



        public String getPath(Uri uri) {
             String[] projection = { MediaStore.Images.Media.DATA };
             Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null);
             int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
             cursor.moveToFirst();
            return cursor.getString(column_index);
        }  



         public void showToast(final String toast) {
                runOnUiThread(new Runnable() {
                  @Override
                  public void run() {

                    Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_LONG).show();

                  }
                });
              }

}

最后,这是我的Andr​​oid的Manifest.xml

Finally This is my Android Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.camera"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.READ_SYNC_STATS" />
    <uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
    <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />



    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >


  <meta-data android:name="com.google.android.apps.drive.APP_ID" android:value="id=829672----" />
        <intent-filter>
            <action android:name="android.intent.action.GoogleDrive" />
        <action android:name="com.google.android.apps.drive.DRIVE_OPEN" />
        <data android:mimeType="application/vnd.google-apps.drive-sdk.829672----" />
        <data android:mimeType="image/png" />
        <data android:mimeType="image/jpeg" />
        <data android:mimeType="image/jpg" />
        </intent-filter>

        <activity
            android:name="com.example.drivequickstart.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />                
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

任何帮助将AP preciated。在此先感谢

any help will be appreciated. Thanks in advance

推荐答案

最后,我发现我的解决方案,现在我能够将图像从相机(它可以在驱动器快速启动)和第二部分,我已经做了选择从画廊的照片,并将其存储到谷歌驱动器为好。请参阅下面

At Last I have found my solution and now I am able to send images to Google Drive from camera (Which is available on Drive Quick Start) and second part I have done that select a picture from Gallery and store it to Google Drive as well. See Code below

@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);
                }
            }
            break;

        case REQUEST_AUTHORIZATION:
            if (resultCode == Activity.RESULT_OK) 
            {
                saveFileToDrive();
            } 

            else 
            {
                startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
            }
            break;

        case SELECT_PICTURE:
            if (resultCode == Activity.RESULT_OK) 
            {
                    selectedImageUri = data.getData();
                    selectedImagePath = getPath(selectedImageUri);
                    tvPath.setText("File Path: " + selectedImagePath);
                    System.out.println("Image Path : " + selectedImagePath);
                    img.setImageURI(selectedImageUri); 
            }
            break;

        case CAPTURE_IMAGE:
            if (resultCode == Activity.RESULT_OK) 
            {
                /*String mediaStorageDir = Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES).getPath();
                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
                selectedImageUri = Uri.fromFile(new java.io.File(mediaStorageDir + java.io.File.separator + "IMG_"
                        + timeStamp + ".jpg"));*/
                selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                img.setImageURI(selectedImageUri);
            }
            break;
        }
    }

/*************** This method leads you to start your device's camera *****************/
    private void startCameraIntent() 
    { 
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
        startActivityForResult(cameraIntent, CAPTURE_IMAGE);
    }

    /*************** This method will take you to gallery *****************/
    private void selectPictureIntent() 
    {       
        Intent pictureintent = new Intent();
        pictureintent.setType("image/jpeg");
        pictureintent.setAction(Intent.ACTION_GET_CONTENT);
        pictureintent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
        startActivityForResult(pictureintent, SELECT_PICTURE);

    }

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(selectedImagePath);// here I was wrong I was sending selectedImageUri.getPath(); and now I am getting path by making getPath() Method and get Path where the image is saved in phone.
            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) 
                    {                       
                        pd.dismiss();

                    }
                    else
                    {
                        pd.dismiss();
                                            System.out.println("File not sent...");


                    }
                } 

                catch (UserRecoverableAuthIOException e) 
                {
                    startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
                } 

                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
        });
        t.start();
}

    public String getPath(Uri uri) 
        {
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
           return cursor.getString(column_index);
       } 

这篇关于从SD卡中选择的图片,并将其存储到谷歌驱动器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆