繁体   English   中英

Android,如何在后台自动将文件上传到DropBox(我有代码!)

[英]Android, How to upload file to DropBox automatically in background (I have a code!)

我对以下代码(来自Github)进行了一些修改,以使其将视频而不是图片上传到dropBox,并且工作正常。 但是我必须单击将我定向到Android上的Gallery的按钮,然后才能选择要上传的视频文件。

我想要的是每当我启动应用程序时都直接上传特定的视频文件,而无需单击任何按钮! 我的意思是直接转到“ /sdcard/DCIM/Camera/20140920_125202.mp4”(或任何其他选择的目录)并上传视频。

我尝试将以下内容添加到“ onCreate”中,以使其在应用程序启动时上传视频,但这不起作用吗?

Uri uri = null;
uri = Uri.parse("/sdcard/DCIM/Camera/20140920_125202.mp4");
File file = new File(getRealPathFromURI(uri));
UploadPicture upload = new UploadPicture(this, mApi,PHOTO_DIR, file);
upload.execute();

码:

@SuppressLint("SimpleDateFormat")
public class DBRoulette extends Activity {
private static final String TAG = "DBRoulette";

final static private String APP_KEY = "6c9q8fbtktytgi6";
final static private String APP_SECRET = "xxxxxxxxxxxxxxx";

// You don't need to change these, leave them alone.
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";

private static final boolean USE_OAUTH1 = false;

DropboxAPI<AndroidAuthSession> mApi;

private boolean mLoggedIn;

// Android widgets
private Button mSubmit;
private RelativeLayout mDisplay;
private Button  mGallery;

private ImageView mImage;

private final String PHOTO_DIR = "/Motion/";

@SuppressWarnings("unused")
final static private int NEW_PICTURE = 50;
private String mCameraFileName;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        mCameraFileName = savedInstanceState.getString("mCameraFileName");

    }

    // We create a new AuthSession so that we can use the Dropbox API.
    AndroidAuthSession session = buildSession();
    mApi = new DropboxAPI<AndroidAuthSession>(session);

    // Basic Android widgets
    setContentView(R.layout.main);

    checkAppKeySetup();

    mSubmit = (Button) findViewById(R.id.auth_button);

    mSubmit.setOnClickListener(new OnClickListener() {
        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            // This logs you out if you're logged in, or vice versa
            if (mLoggedIn) {
                logOut();
            } else {
                // Start the remote authentication
                if (USE_OAUTH1) {
                    mApi.getSession().startAuthentication(DBRoulette.this);
                } else {
                    mApi.getSession().startOAuth2Authentication(
                            DBRoulette.this);
                }
            }
        }
    });

    mDisplay = (RelativeLayout) findViewById(R.id.logged_in_display);

    // This is where a photo is displayed
    mImage = (ImageView) findViewById(R.id.image_view);

    // This is the button to take a file from gallery
    mGallery = (Button) findViewById(R.id.gallery_button);

    mGallery.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            intent.setType("*/*");
            intent.setAction(Intent.ACTION_PICK);
            try {
                startActivityForResult(intent, 1);
            } catch (ActivityNotFoundException e) {
                showToast("There doesn't seem to be a gallery.");
            }
        }
    });


    // Display the proper UI state if logged in or not
    setLoggedIn(mApi.getSession().isLinked());

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putString("mCameraFileName", mCameraFileName);
    super.onSaveInstanceState(outState);
}

@Override
protected void onResume() {
    super.onResume();
    AndroidAuthSession session = mApi.getSession();

    // The next part must be inserted in the onResume() method of the
    // activity from which session.startAuthentication() was called, so
    // that Dropbox authentication completes properly.
    if (session.authenticationSuccessful()) {
        try {
            // Mandatory call to complete the auth
            session.finishAuthentication();

            // Store it locally in our app for later use
            storeAuth(session);
            setLoggedIn(true);
        } catch (IllegalStateException e) {
            showToast("Couldn't authenticate with Dropbox:"
                    + e.getLocalizedMessage());
            Log.i(TAG, "Error authenticating", e);
        }
    }
}

// This is what gets called on finishing a media piece to import
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

        // return from file upload
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1) {
                Uri uri = null;
                if (data != null) {
                    uri = Uri.parse(data.getData().toString());
                }
                File file = new File(getRealPathFromURI(uri));
                if (uri != null) {
                    UploadPicture upload = new UploadPicture(this, mApi,PHOTO_DIR, file);
                    upload.execute();
                }
            } else if(requestCode == 2){
                Uri uri = null;
                if (data != null) {
                    uri = data.getData();
                }
                if (uri == null && mCameraFileName != null) {
                    uri = Uri.fromFile(new File(mCameraFileName));
                }
                File file = new File(mCameraFileName);

                if (uri != null) {
                    UploadPicture upload = new UploadPicture(this, mApi,
                            PHOTO_DIR, file);
                    upload.execute();
                }
            }

        } else {
            Log.w(TAG, "Unknown Activity Result from mediaImport: "
                    + resultCode);
        }
}

private void logOut() {
    // Remove credentials from the session
    mApi.getSession().unlink();

    // Clear our stored keys
    clearKeys();
    // Change UI state to display logged out version
    setLoggedIn(false);
}
@SuppressWarnings("deprecation")
public String getRealPathFromURI(Uri contentUri) 
{
     String[] proj = { MediaStore.Audio.Media.DATA };
     Cursor cursor = managedQuery(contentUri, proj, null, null, null);
     int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
     cursor.moveToFirst();
     return cursor.getString(column_index);
}
/**
 * Convenience function to change UI state based on being logged in
 */
private void setLoggedIn(boolean loggedIn) {
    mLoggedIn = loggedIn;
    if (loggedIn) {
        mSubmit.setText("Logout from Dropbox");
        mDisplay.setVisibility(View.VISIBLE);
    } else {
        mSubmit.setText("Login with Dropbox");
        mDisplay.setVisibility(View.GONE);
        mImage.setImageDrawable(null);
    }
}

private void checkAppKeySetup() {
    // Check to make sure that we have a valid app key
    if (APP_KEY.startsWith("CHANGE") || APP_SECRET.startsWith("CHANGE")) {
        showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the DBRoulette ap before trying it.");
        finish();
        return;
    }

    // Check if the app has set up its manifest properly.
    Intent testIntent = new Intent(Intent.ACTION_VIEW);
    String scheme = "db-" + APP_KEY;
    String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test";
    testIntent.setData(Uri.parse(uri));
    PackageManager pm = getPackageManager();
    if (0 == pm.queryIntentActivities(testIntent, 0).size()) {
        showToast("URL scheme in your app's "
                + "manifest is not set up correctly. You should have a "
                + "com.dropbox.client2.android.AuthActivity with the "
                + "scheme: " + scheme);
        finish();
    }
}

private void showToast(String msg) {
    Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
    error.show();
}

/**
 * Shows keeping the access keys returned from Trusted Authenticator in a
 * local store, rather than storing user name & password, and
 * re-authenticating each time (which is not to be done, ever).
 */
private void loadAuth(AndroidAuthSession session) {
    SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
    String key = prefs.getString(ACCESS_KEY_NAME, null);
    String secret = prefs.getString(ACCESS_SECRET_NAME, null);
    if (key == null || secret == null || key.length() == 0
            || secret.length() == 0)
        return;

    if (key.equals("oauth2:")) {
        // If the key is set to "oauth2:", then we can assume the token is
        // for OAuth 2.
        session.setOAuth2AccessToken(secret);
    } else {
        // Still support using old OAuth 1 tokens.
        session.setAccessTokenPair(new AccessTokenPair(key, secret));
    }
}

/**
 * Shows keeping the access keys returned from Trusted Authenticator in a
 * local store, rather than storing user name & password, and
 * re-authenticating each time (which is not to be done, ever).
 */
private void storeAuth(AndroidAuthSession session) {
    // Store the OAuth 2 access token, if there is one.
    String oauth2AccessToken = session.getOAuth2AccessToken();
    if (oauth2AccessToken != null) {
        SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME,
                0);
        Editor edit = prefs.edit();
        edit.putString(ACCESS_KEY_NAME, "oauth2:");
        edit.putString(ACCESS_SECRET_NAME, oauth2AccessToken);
        edit.commit();
        return;
    }
    // Store the OAuth 1 access token, if there is one. This is only
    // necessary if
    // you're still using OAuth 1.
    AccessTokenPair oauth1AccessToken = session.getAccessTokenPair();
    if (oauth1AccessToken != null) {
        SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME,
                0);
        Editor edit = prefs.edit();
        edit.putString(ACCESS_KEY_NAME, oauth1AccessToken.key);
        edit.putString(ACCESS_SECRET_NAME, oauth1AccessToken.secret);
        edit.commit();
        return;
    }
}

private void clearKeys() {
    SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
    Editor edit = prefs.edit();
    edit.clear();
    edit.commit();
}

private AndroidAuthSession buildSession() {
    AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);

    AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
    loadAuth(session);
    return session;
}
}

这听起来像是AsyncTask的工作,看着您的代码,看起来您已使所有代码正确上传,您可能只需要将其卸载到后台线程即可。 然后,当一切完成后,可以将回调发送到您的主应用程序线程。

如果需要,您还可以在过程中使用显示的加载指示器,但这是可选的。

http://developer.android.com/reference/android/os/AsyncTask.html

我通过在定义的“ mApi”之后添加一些修改来解决我的问题。 现在,当我调用应用程序时,该应用程序会将视频文件“ 20140920_125202.mp4”直接上传到dropBox。 谢谢大家

@SuppressLint("SimpleDateFormat")
public class DBRoulette extends Activity {
private static final String TAG = "DBRoulette";

final static private String APP_KEY = "6c9q8fbtktytgi6";
final static private String APP_SECRET = "xxxxxxxxxxxxxxx";

// You don't need to change these, leave them alone.
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";

private static final boolean USE_OAUTH1 = false;

DropboxAPI<AndroidAuthSession> mApi;

private boolean mLoggedIn;

// Android widgets
private Button mSubmit;
private RelativeLayout mDisplay;
private Button  mGallery;

private ImageView mImage;

private final String PHOTO_DIR = "/Motion/";

@SuppressWarnings("unused")
final static private int NEW_PICTURE = 50;
private String mCameraFileName;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        mCameraFileName = savedInstanceState.getString("mCameraFileName");          
    }

    // We create a new AuthSession so that we can use the Dropbox API.
    AndroidAuthSession session = buildSession();
    mApi = new DropboxAPI<AndroidAuthSession>(session);

    // Basic Android widgets
    setContentView(R.layout.main);

    checkAppKeySetup();

    mSubmit = (Button) findViewById(R.id.auth_button);

    mSubmit.setOnClickListener(new OnClickListener() {
        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            // This logs you out if you're logged in, or vice versa
            if (mLoggedIn) {
                logOut();
            } else {
                // Start the remote authentication
                if (USE_OAUTH1) {
                    mApi.getSession().startAuthentication(DBRoulette.this);
                } else {
                    mApi.getSession().startOAuth2Authentication(
                            DBRoulette.this);


                }
            }
        }
    });

    mDisplay = (RelativeLayout) findViewById(R.id.logged_in_display);

    // This is where a photo is displayed
    mImage = (ImageView) findViewById(R.id.image_view);

    // This is the button to take a file from gallery
    mGallery = (Button) findViewById(R.id.gallery_button);

    mGallery.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            intent.setType("*/*");
            intent.setAction(Intent.ACTION_PICK);
            try {
                startActivityForResult(intent, 1);
            } catch (ActivityNotFoundException e) {
                showToast("There doesn't seem to be a gallery.");
            }
        }
    });


    File outFile = new File("/mnt/sdcard/DCIM/Camera/20140920_125202.mp4");
    mCameraFileName = outFile.toString();
    UploadPicture upload = new UploadPicture(DBRoulette.this, mApi, PHOTO_DIR,outFile);
    upload.execute();



    // Display the proper UI state if logged in or not
    setLoggedIn(mApi.getSession().isLinked());

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putString("mCameraFileName", mCameraFileName);
    super.onSaveInstanceState(outState);
}

@Override
protected void onResume() {
    super.onResume();
    AndroidAuthSession session = mApi.getSession();

    // The next part must be inserted in the onResume() method of the
    // activity from which session.startAuthentication() was called, so
    // that Dropbox authentication completes properly.
    if (session.authenticationSuccessful()) {
        try {
            // Mandatory call to complete the auth
            session.finishAuthentication();

            // Store it locally in our app for later use
            storeAuth(session);
            setLoggedIn(true);
        } catch (IllegalStateException e) {
            showToast("Couldn't authenticate with Dropbox:"
                    + e.getLocalizedMessage());
            Log.i(TAG, "Error authenticating", e);
        }
    }
}

// This is what gets called on finishing a media piece to import
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

        // return from file upload
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1) {
                Uri uri = null;
                if (data != null) {
                    uri = Uri.parse(data.getData().toString());
                }
                File file = new File(getRealPathFromURI(uri));
                if (uri != null) {
                    UploadPicture upload = new UploadPicture(this, mApi,PHOTO_DIR, file);
                    upload.execute();
                }
            } else if(requestCode == 2){
                Uri uri = null;
                if (data != null) {
                    uri = data.getData();
                }
                if (uri == null && mCameraFileName != null) {
                    uri = Uri.fromFile(new File(mCameraFileName));
                }
                File file = new File(mCameraFileName);

                if (uri != null) {
                    UploadPicture upload = new UploadPicture(this, mApi,
                            PHOTO_DIR, file);
                    upload.execute();
                }
            }

        } else {
            Log.w(TAG, "Unknown Activity Result from mediaImport: "
                    + resultCode);
        }
}

private void logOut() {
    // Remove credentials from the session
    mApi.getSession().unlink();

    // Clear our stored keys
    clearKeys();
    // Change UI state to display logged out version
    setLoggedIn(false);
}
@SuppressWarnings("deprecation")
public String getRealPathFromURI(Uri contentUri) 
{
     String[] proj = { MediaStore.Audio.Media.DATA };
     Cursor cursor = managedQuery(contentUri, proj, null, null, null);
     int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
     cursor.moveToFirst();
     return cursor.getString(column_index);
}
/**
 * Convenience function to change UI state based on being logged in
 */
private void setLoggedIn(boolean loggedIn) {
    mLoggedIn = loggedIn;
    if (loggedIn) {
        mSubmit.setText("Logout from Dropbox");
        mDisplay.setVisibility(View.VISIBLE);
    } else {
        mSubmit.setText("Login with Dropbox");
        mDisplay.setVisibility(View.GONE);
        mImage.setImageDrawable(null);
    }
}

private void checkAppKeySetup() {
    // Check to make sure that we have a valid app key
    if (APP_KEY.startsWith("CHANGE") || APP_SECRET.startsWith("CHANGE")) {
        showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the DBRoulette ap before trying it.");
        finish();
        return;
    }

    // Check if the app has set up its manifest properly.
    Intent testIntent = new Intent(Intent.ACTION_VIEW);
    String scheme = "db-" + APP_KEY;
    String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test";
    testIntent.setData(Uri.parse(uri));
    PackageManager pm = getPackageManager();
    if (0 == pm.queryIntentActivities(testIntent, 0).size()) {
        showToast("URL scheme in your app's "
                + "manifest is not set up correctly. You should have a "
                + "com.dropbox.client2.android.AuthActivity with the "
                + "scheme: " + scheme);
        finish();
    }
}

private void showToast(String msg) {
    Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
    error.show();
}

/**
 * Shows keeping the access keys returned from Trusted Authenticator in a
 * local store, rather than storing user name & password, and
 * re-authenticating each time (which is not to be done, ever).
 */
private void loadAuth(AndroidAuthSession session) {
    SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
    String key = prefs.getString(ACCESS_KEY_NAME, null);
    String secret = prefs.getString(ACCESS_SECRET_NAME, null);
    if (key == null || secret == null || key.length() == 0
            || secret.length() == 0)
        return;

    if (key.equals("oauth2:")) {
        // If the key is set to "oauth2:", then we can assume the token is
        // for OAuth 2.
        session.setOAuth2AccessToken(secret);
    } else {
        // Still support using old OAuth 1 tokens.
        session.setAccessTokenPair(new AccessTokenPair(key, secret));
    }
}

/**
 * Shows keeping the access keys returned from Trusted Authenticator in a
 * local store, rather than storing user name & password, and
 * re-authenticating each time (which is not to be done, ever).
 */
private void storeAuth(AndroidAuthSession session) {
    // Store the OAuth 2 access token, if there is one.
    String oauth2AccessToken = session.getOAuth2AccessToken();
    if (oauth2AccessToken != null) {
        SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME,
                0);
        Editor edit = prefs.edit();
        edit.putString(ACCESS_KEY_NAME, "oauth2:");
        edit.putString(ACCESS_SECRET_NAME, oauth2AccessToken);
        edit.commit();
        return;
    }
    // Store the OAuth 1 access token, if there is one. This is only
    // necessary if
    // you're still using OAuth 1.
    AccessTokenPair oauth1AccessToken = session.getAccessTokenPair();
    if (oauth1AccessToken != null) {
        SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME,
                0);
        Editor edit = prefs.edit();
        edit.putString(ACCESS_KEY_NAME, oauth1AccessToken.key);
        edit.putString(ACCESS_SECRET_NAME, oauth1AccessToken.secret);
        edit.commit();
        return;
    }
}

private void clearKeys() {
    SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
    Editor edit = prefs.edit();
    edit.clear();
    edit.commit();
}

private AndroidAuthSession buildSession() {
    AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);

    AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
    loadAuth(session);
    return session;
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM