当前位置: 首页 > 知识库问答 >
问题:

在Android应用程序中集成flickr api

祁远
2023-03-14

我正在为Android创建一个社交网络集成应用程序。我已经可以在脸书、推特和领英上发帖了。现在我必须在应用程序中集成Flickr。我找不到一个合适的例子如何在Android应用程序中集成flicker。

 public class FlickrViewerActivity extends Activity {

    public static final String CALLBACK_SCHEME = "flickrj-android-sample-oauth"; //$NON-NLS-1$
    public static final String PREFS_NAME = "flickrj-android-sample-pref"; //$NON-NLS-1$
    public static final String KEY_OAUTH_TOKEN = "flickrj-android-oauthToken"; //$NON-NLS-1$
    public static final String KEY_TOKEN_SECRET = "flickrj-android-tokenSecret"; //$NON-NLS-1$
    public static final String KEY_USER_NAME = "flickrj-android-userName"; //$NON-NLS-1$
    public static final String KEY_USER_ID = "flickrj-android-userId"; //$NON-NLS-1$

    private static final Logger logger = LoggerFactory.getLogger(FlickrjAndroidSampleActivity.class);


    private ListView listView;
    private TextView textUserTitle;
    private TextView textUserName;
    private TextView textUserId;
    private ImageView userIcon;
    private ImageButton refreshButton;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            this.textUserTitle = (TextView) this.findViewById(R.id.profilePageTitle);
            this.textUserName = (TextView) this.findViewById(R.id.userScreenName);
            this.textUserId = (TextView) this.findViewById(R.id.userId);
            this.userIcon = (ImageView) this.findViewById(R.id.userImage);
            this.listView = (ListView) this.findViewById(R.id.imageList);
            this.refreshButton = (ImageButton)     this.findViewById(R.id.btnRefreshUserProfile);

            this.refreshButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                            load(getOAuthToken());
                    }
            });

            OAuth oauth = getOAuthToken();
            if (oauth == null || oauth.getUser() == null) {
                    OAuthTask task = new OAuthTask(this);
                    task.execute();
            } else {
                    load(oauth);
            }
    }

    private void load(OAuth oauth) {
            if (oauth != null) {
                    new LoadUserTask(this, userIcon).execute(oauth);
                    new LoadPhotostreamTask(this, listView).execute(oauth);
            }
    }

     @Override
        public void onDestroy() {
    listView.setAdapter(null);
    super.onDestroy();
     }

       /* (non-Javadoc)
       * @see android.app.Activity#onNewIntent(android.content.Intent)
       */
       @Override
        protected void onNewIntent(Intent intent) {
            //this is very important, otherwise you would get a null Scheme in the onResume                        later on.
            setIntent(intent);
       }

      public void setUser(User user) {
            textUserTitle.setText(user.getUsername());
            textUserName.setText(user.getRealName());
            textUserId.setText(user.getId());
      }

          public ImageView getUserIconImageView() {
            return this.userIcon;
       }

    @Override
    public void onResume() {
            super.onResume();
            Intent intent = getIntent();
            String scheme = intent.getScheme();
            OAuth savedToken = getOAuthToken();
            if (CALLBACK_SCHEME.equals(scheme) && (savedToken == null || savedToken.getUser() == null)) {
                    Uri uri = intent.getData();
                    String query = uri.getQuery();
                    logger.debug("Returned Query: {}", query); //$NON-NLS-1$
                    String[] data = query.split("&"); //$NON-NLS-1$
                    if (data != null && data.length == 2) {
                            String oauthToken = data[0].substring(data[0].indexOf("=") + 1); //$NON-NLS-1$
                            String oauthVerifier = data[1]
                                            .substring(data[1].indexOf("=") + 1); //$NON-NLS-1$
                            logger.debug("OAuth Token: {}; OAuth Verifier: {}", oauthToken, oauthVerifier); //$NON-NLS-1$

                            OAuth oauth = getOAuthToken();
                            if (oauth != null && oauth.getToken() != null && oauth.getToken().getOauthTokenSecret() != null) {
                                    GetOAuthTokenTask task = new GetOAuthTokenTask(this);
                                    task.execute(oauthToken, oauth.getToken().getOauthTokenSecret(), oauthVerifier);
                            }
                    }
            }

    }

          public void onOAuthDone(OAuth result) {
            if (result == null) {
                    Toast.makeText(this,
                                    "Authorization failed", //$NON-NLS-1$
                                    Toast.LENGTH_LONG).show();
                    } else {
                    User user = result.getUser();
                    OAuthToken token = result.getToken();
                    if (user == null || user.getId() == null || token == null
                                    || token.getOauthToken() == null
                                    || token.getOauthTokenSecret() == null) {
                            Toast.makeText(this,
                                            "Authorization failed", //$NON-NLS-1$
                                            Toast.LENGTH_LONG).show();
                            return;
                    }
           String message = String.format(Locale.US, "Authorization Succeed:        user=%s, userId=%s, oauthToken=%s, tokenSecret=%s", //$NON-NLS-1$
                                    user.getUsername(), user.getId(),   token.getOauthToken(), token.getOauthTokenSecret());
                      Toast.makeText(this,
                                    message,
                                    Toast.LENGTH_LONG).show();
                    saveOAuthToken(user.getUsername(), user.getId(), token.getOauthToken(), token.getOauthTokenSecret());
                    load(result);
            }
    }


        public OAuth getOAuthToken() {
     //Restore preferences
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
      String oauthTokenString = settings.getString(KEY_OAUTH_TOKEN, null);
      String tokenSecret = settings.getString(KEY_TOKEN_SECRET, null);
        if (oauthTokenString == null && tokenSecret == null) {
            logger.warn("No oauth token retrieved"); //$NON-NLS-1$
            return null;
        }
        OAuth oauth = new OAuth();
         String userName = settings.getString(KEY_USER_NAME, null);
        String userId = settings.getString(KEY_USER_ID, null);
         if (userId != null) {
            User user = new User();
            user.setUsername(userName);
            user.setId(userId);
            oauth.setUser(user);
         }
        OAuthToken oauthToken = new OAuthToken();
         oauth.setToken(oauthToken);
         oauthToken.setOauthToken(oauthTokenString);
          oauthToken.setOauthTokenSecret(tokenSecret);
          logger.debug("Retrieved token from preference store: oauth token={}, and token  secret={}", oauthTokenString, tokenSecret); //$NON-NLS-1$
           return oauth;
            }

       public void saveOAuthToken(String userName, String userId, String token, String  tokenSecret) {
       logger.debug("Saving userName=%s, userId=%s, oauth token={}, and token secret={}",    new String[]{userName, userId, token, tokenSecret}); //$NON-NLS-1$
       SharedPreferences sp = getSharedPreferences(PREFS_NAME,
                            Context.MODE_PRIVATE);
            Editor editor = sp.edit();
            editor.putString(KEY_OAUTH_TOKEN, token);
            editor.putString(KEY_TOKEN_SECRET, tokenSecret);
            editor.putString(KEY_USER_NAME, userName);
            editor.putString(KEY_USER_ID, userId);
            editor.commit();
      }

    }
public class OAuthTask extends AsyncTask<Void, Integer, String> {

private static final Logger logger = LoggerFactory
                .getLogger(OAuthTask.class);
private static final Uri OAUTH_CALLBACK_URI = Uri.parse(FlickrjAndroidSampleActivity.CALLBACK_SCHEME
                + "://oauth"); //$NON-NLS-1$

/**
 * The context.
 */
private Context mContext;

/**
 * The progress dialog before going to the browser.
 */
private ProgressDialog mProgressDialog;

/**
 * Constructor.
 * 
 * @param context
 */
public OAuthTask(Context context) {
        super();
        this.mContext = context;
}

@Override
protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = ProgressDialog.show(mContext,
                        "", "Generating the authorization request..."); //$NON-NLS-1$ //$NON-NLS-2$
        mProgressDialog.setCanceledOnTouchOutside(true);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dlg) {
                        OAuthTask.this.cancel(true);
                }
        });
}

/*
 * (non-Javadoc)
 * 
 * @see android.os.AsyncTask#doInBackground(Params[])
 */
@Override
protected String doInBackground(Void... params) {
        try {
                Flickr f = FlickrHelper.getInstance().getFlickr();
                OAuthToken oauthToken = f.getOAuthInterface().getRequestToken(
                                OAUTH_CALLBACK_URI.toString());
                saveTokenSecrent(oauthToken.getOauthTokenSecret());
                URL oauthUrl = f.getOAuthInterface().buildAuthenticationUrl(
                                Permission.READ, oauthToken);
                return oauthUrl.toString();
        } catch (Exception e) {
                logger.error("Error to oauth", e); //$NON-NLS-1$
                return "error:" + e.getMessage(); //$NON-NLS-1$
        }
}

/**
 * Saves the oauth token secrent.
 * 
 * @param tokenSecret
 */
private void saveTokenSecrent(String tokenSecret) {
        logger.debug("request token: " + tokenSecret); //$NON-NLS-1$
        FlickrjAndroidSampleActivity act = (FlickrjAndroidSampleActivity) mContext;
        act.saveOAuthToken(null, null, null, tokenSecret);
        logger.debug("oauth token secret saved: {}", tokenSecret); //$NON-NLS-1$
}

@Override
protected void onPostExecute(String result) {
        if (mProgressDialog != null) {
                mProgressDialog.dismiss();
        }
        if (result != null && !result.startsWith("error") ) { //$NON-NLS-1$
                mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                                .parse(result)));
        } else {
                Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
        }
}

}

清单文件:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.flickr.test"
    android:versionCode="1"
    android:versionName="1.0" 
    android:installLocation="preferExternal">

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".FlickrViewerActivity"
            android:label="@string/title_activity_flickr_viewer" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />


                <action android:name="android.intent.action.VIEW" />
                                <category android:name="android.intent.category.DEFAULT" />
                                <category android:name="android.intent.category.BROWSABLE" />
                                <data android:scheme="flickrj-android-sample-oauth" />

            </intent-filter>
        </activity>
    </application>

</manifest>

main.xml文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:padding="@dimen/padding_medium"
        android:text="@string/hello_world"
        tools:context=".FlickrViewerActivity" />

</RelativeLayout>

我在下面的教程中学习:

代码没有执行,我正在寻找一个解决方案或与Flickr集成的Android示例项目源代码。

共有1个答案

伯洋
2023-03-14

公共静态最终字符串CALLBACK_SCHEME=“flickrj-android-sample-oauth”;//$non-nls-1$public静态最终字符串PREFS_NAME=“flickrj-android-sample-pref”;//$non-nls-1$public静态最终字符串KEY_OAUTH_TOKEN=“flickrj-android-oauthtoken”;//$non-nls-1$public静态最终字符串KEY_TOKEN_SECRET=“flickrj-android-tokensecret”;//$non-nls-1$public静态最终字符串KEY_USER_NAME=“flickrj-android-username”;//$non-nls-1$public静态最终字符串KEY_USER_ID=“flickrj-android-userid”;//$非NLS-1$

如何获得这个oauth令牌和令牌秘密??我通过在flickr上html" target="_blank">添加我的应用程序获得了api密钥和秘密密钥,但我在代码中得到了oauth错误?

 类似资料:
  • 问题内容: 我从以下文档中不太了解:http : //sqlcipher.net/sqlcipher-for-android/ 我该怎么办,需要执行哪些步骤?似乎该说明仅属于MAC用户,我的操作系统是Windows 7。 谁能告诉我该怎么办?二进制文件包含“ libs”和“ assets”文件夹。如何将它们集成到我现有的应用程序中? 问题答案: 步骤1:将文件夹的内容复制到项目的文件夹中。 步骤2

  • 问题内容: 我在RapidMiner中有一个文本分类过程。它从指定的excel ssheet读取测试数据并进行分类。我还有一个小型Java应用程序,它正在运行此过程。现在,我想在应用程序中添加文件输入部分,以便每次我都可以从应用程序(而不是RapidMiner)中指定excel文件。有什么提示吗? 这是代码: 这是错误: 最好的祝福 Armen 问题答案: 我看到两种方法可以做到这一点。 第一个方

  • 在我们将该项目导出到一个Android项目之后,我们将其与一个现有项目集成,并从中启动我们的游戏。这是正确的工作,但应用程序。Quit()使整个应用程序退出,而不仅仅是Unity活动。因此,我们通过将以下内容添加到清单中,使其在另一个流程上启动: 这解决了这个问题,但是,在使用ProGuard混淆代码后,事情就停止了。Unity仍然正确启动,但是当退出时,应用程序显示一个崩溃错误,Unity停止了

  • 我想集成谷歌照片api在Android,我已经做了谷歌登录过程中,但我不能得到访问令牌,因为我得到错误的FixedCreentalsProvider.create方法,而传递参数。

  • 我已经将我的android应用程序与Paypal集成在一起,并用Paypal沙箱凭据对其进行了测试。Ti测试与其他凭据,我创建了另一个帐户,当我测试这个,我得到错误说.... 请给我宝贵的建议和帮助我

  • 作者:陈希章 发表于 2017年6月25日 谈一谈.NET 的跨平台 终于要写到这一篇了。跨平台的支持可以说是 Office 365 平台在设计伊始就考虑的目标。我在前面的文章已经提到过了,Microsoft Graph 服务针对一些主流的开源平台(主要用来做跨平台应用)都有支持,例如 python,nodejs 等。他们真的非常好用,与此同时我虽然对他们也有一定的了解,但要跟我最熟悉的 Micr