android - 在 Android App 中集成 flickr api

标签 android social-networking flickr

我正在为 Android 创建一个社交网络集成应用程序。我已经可以在 Facebook、Twitter 和 Linkedin 上发帖了。现在我必须在应用程序中集成 Flickr。我找不到合适的示例来说明如何在 Android 应用程序中集成闪烁。

我的源代码如下:

这是 FlickrViewerActivity 类:

 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();
      }

    }

OAuthTask 类:

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();
        }
}

}

list 文件:

<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>

我在以下位置学习教程:

http://code.google.com/p/flickrj-android/wiki/HowToGuide4Android

代码未执行,我正在寻找 Android 中集成了 Flickr 的解决方案或示例项目源代码。

最佳答案

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

如何获取此 oauth token 和 token secret ?我通过在 flickr 上添加我的应用程序获得了 api key 和 key ,但我的代码中出现了 oauth 错误?

关于android - 在 Android App 中集成 flickr api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12388203/

相关文章:

android - AdapterView 和 addView 的问题

java - Rect.intersects 不工作

android - 在没有wifi的情况下在Android上访问LAN

algorithm - 社交网络功能查找您可能知道的联系

search - Flickr API 搜索与 www.flickr.com 的不一致

Android Studio gradle 构建问题 : local variable type mismatch

ruby-on-rails - 潜在事件流垃圾邮件的 UX 解决方案

ios - 在 iPhone 中没有推文表的情况下通过应用程序发送推文

c# - Linq:添加额外的 'Where' 子句给出随机结果

iphone - 没有用户登录的 flickr 公共(public)图片库适用于 iphone 应用程序