官网Instagram集成

20 篇文章 0 订阅
2 篇文章 0 订阅


一、创建WebView(登录对话框)

        mWebView = new WebView(getContext());

        mWebView.setVerticalScrollBarEnabled(false);

        mWebView.setHorizontalScrollBarEnabled(false);

        mWebView.setWebViewClient(new OAuthWebViewClient());

        mWebView.getSettings().setJavaScriptEnabled(true);

        mWebView.loadUrl(mUrl);

        mWebView.setLayoutParams(FILL);

        mContent.addView(mWebView);


二、WebView回调

private class OAuthWebViewClient extends WebViewClient {


        @Override

        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            Log.d(TAG, "Redirecting URL " + url);


            if (url.startsWith(InstagramApp.mCallbackUrl)) {

                String urls[] = url.split("=");

                mListener.onComplete(urls[1]);

                InstagramDialog.this.dismiss();

                return true;

            }

            return false;

        }


        @Override

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

            Log.d(TAG, "Page error: " + description);


            super.onReceivedError(view, errorCode, description, failingUrl);

            mListener.onError(description);

            InstagramDialog.this.dismiss();

        }


        @Override

        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            Log.d(TAG, "Loading URL: " + url);


            super.onPageStarted(view, url, favicon);

            mSpinner.show();

        }


        @Override

        public void onPageFinished(WebView view, String url) {

            super.onPageFinished(view, url);

            String title = mWebView.getTitle();

            if (title != null && title.length() > 0) {

                mTitle.setText(title);

            }

            Log.d(TAG, "onPageFinished URL: " + url);

            mSpinner.dismiss();

        }

    }

三、接口监听

public interface OAuthDialogListener {

        public abstract void onComplete(String accessToken);

        public abstract void onError(String error);

    }

四、创建对话框监听

InstagramDialog.OAuthDialogListener listener = new InstagramDialog.OAuthDialogListener() {

            @Override

            public void onComplete(String code) {

                getAccessToken(code);

            }


            @Override

            public void onError(String error) {

                mListener.onFail("Authorization failed");

            }

        };


五、获取access_token

private void getAccessToken(final String code) {

        mProgress.setMessage("Getting access token ...");

        mProgress.show();


        new Thread() {

            @Override

            public void run() {

                Log.i(TAG, "Getting access token");

                int what = WHAT_FETCH_INFO;

                try {

                    URL url = new URL(TOKEN_URL);

                    // URL url = new URL(mTokenUrl + "&code=" + code);

                    Log.i(TAG, "Opening Token URL " + url.toString());

                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                    urlConnection.setRequestMethod("POST");

                    urlConnection.setDoInput(true);

                    urlConnection.setDoOutput(true);

                    // urlConnection.connect();

                    OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());

                    writer.write("client_id=" + mClientId + "&client_secret=" + mClientSecret

                            + "&grant_type=authorization_code" + "&redirect_uri=" + mCallbackUrl + "&code=" + code);

                    writer.flush();

                    String response = streamToString(urlConnection.getInputStream());

                    Log.i(TAG, "response " + response);

                    JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();


                    mAccessToken = jsonObj.getString("access_token");

                    Log.i(TAG, "Got access token: " + mAccessToken);


                    String id = jsonObj.getJSONObject("user").getString("id");

                    String user = jsonObj.getJSONObject("user").getString("username");

                    String name = jsonObj.getJSONObject("user").getString("full_name");


                    mSession.storeAccessToken(mAccessToken, id, user, name);

                    Log.i(TAG, "userid: " + id);

                } catch (Exception ex) {

                    what = WHAT_ERROR;

                    ex.printStackTrace();

                }


                mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0));

            }

        }.start();

    }

六、获取用户信息

private void fetchUserName() {

        mProgress.setMessage("Finalizing ...");


        new Thread() {

            @Override

            public void run() {

                Log.i(TAG, "Fetching user info");

                int what = WHAT_FINALIZE;

                try {

                    URL url = new URL(API_URL + "/users/" + mSession.getId() + "/?access_token=" + mAccessToken);


                    Log.d(TAG, "Opening URL " + url.toString());

                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                    urlConnection.setRequestMethod("GET");

                    urlConnection.setDoInput(true);

                    urlConnection.connect();

                    String response = streamToString(urlConnection.getInputStream());

                    System.out.println(response);

                    JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();

                    String name = jsonObj.getJSONObject("data").getString("full_name");

                    String bio = jsonObj.getJSONObject("data").getString("bio");

                    Log.i(TAG, "Got name: " + name + ", bio [" + bio + "]");

                } catch (Exception ex) {

                    what = WHAT_ERROR;

                    ex.printStackTrace();

                }


                mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));

            }

        }.start();


    }


七、调用显示登录页

public void authorize() {

        // Intent webAuthIntent = new Intent(Intent.ACTION_VIEW);

        // webAuthIntent.setData(Uri.parse(AUTH_URL));

        // mCtx.startActivity(webAuthIntent);

        mDialog.show();

    }

八、App信息

 public static final String CLIENT_ID = “379d744556c743c090c8a2014345435”;//更换

 public static final String CLIENT_SECRET = "fd6ec75e44054545345088ad2d72f2253";

 public static final String CALLBACK_URL = "instagram://connect";




分享、

 File file = new File(videoPath);

 Uri uri = Uri.fromFile(file);

 Intent share = new Intent(Intent.ACTION_SEND);

// Set the MIME type

share.setType(type);

List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(share, 0);

 List<Intent> targetedShareIntents = new ArrayList<Intent>();

 if (!resInfo.isEmpty()) {

      for (ResolveInfo r : resInfo) {

   Intent targeted = new Intent(Intent.ACTION_SEND);

   targeted.setType(type);

    ActivityInfo activityInfo = r.activityInfo;

if(activityInfo.packageName.contains("com.instagram.android")

                        || activityInfo.name.contains("com.instagram.android.activity.ShareHandlerActivity")) {

       targeted.putExtra(Intent.EXTRA_SUBJECT, "subject");

       targeted.putExtra(Intent.EXTRA_TEXT, "your text");

       targeted.putExtra(Intent.EXTRA_STREAM, uri);

// targeted.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

       targeted.setPackage(activityInfo.packageName);

       targetedShareIntents.add(targeted);

                }

            }

if (targetedShareIntents.size() == 0) {

 L.showToast(getResources().getString(R.string.no_client) + ":instagram");

                return;

         }

 Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Select app to share");

            if (chooserIntent == null) {

                return;

            }

            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));

            try {

                startActivity(chooserIntent);

            } catch (android.content.ActivityNotFoundException ex) {

L.showToast(getResources().getString(R.string.no_client) + ":instagram");

            }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值