如何将谷歌分析数据检索到我的Android应用程序?

时间:2012-04-13 10:41:20

标签: android oauth-2.0

您好我尝试检索谷歌分析数据...我使用此REDIRECT_URI =“urn:ietf:wg:oauth:2.0:oob”直到访问令牌...我没有得到任何错误,但我没有进一步实施。 ..

现在我获得了访问令牌,应用程序说“请复制此代码,切换到您的应用程序并将其粘贴到那里”,此操作后我现在要检索我的分析数据......

=============================================== ================

这些jar文件我正在使用,

libGoogleAnalytics.jar

公地编解码器-1.3.jar

共享记录-1.1.1.jar

htttpclient-4.0.3.jar

httpore-4.0.1.jar

番石榴r09.jar

谷歌OAuth的客户1.6.0-beta.jar

GSON-1.7.1.jar

杰克逊核-ASL-1.9.1.jar

谷歌-API的客户端 - 1.6.0-beta.jar

谷歌-API的分析-V3-REV3-java的1.5.0-beta.jar

google-api-java-client-1.6.0-beta.zip

谷歌-HTTP-客户1.6.0-beta.jar

=============================================== ===============

package com.nasotech.XploreApp;

import java.io.IOException;

import org.apache.http.client.methods.HttpTrace;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.google.api.client.auth.oauth2.draft10.AccessTokenRequest.RefreshTokenGrant;
import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAuthorizationRequestUrl;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.model.Goal;
import com.google.api.services.analytics.model.Profile;
import com.google.api.services.analytics.model.Webproperty;
import com.nasotech.XploreApp.oauthstore.CredentialStore;
import com.nasotech.XploreApp.oauthstore.SharedPreferencesCredentialStore;


public class OauthGoogleAnalytics extends Activity
{

    final String TAG = getClass().getName();
    private SharedPreferences prefs;

     static HttpTrace TRANSPORT=null;
     static HttpTransport httptransport;
     static com.google.api.client.json.JsonFactory JSON_FACTORY=null;

     String authorizationCode;
     String authorizationUrl;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "Starting task to retrieve request token.");
        this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        WebView webview = new WebView(this);
        webview.getSettings().setJavaScriptEnabled(true);  
        webview.setVisibility(View.VISIBLE);
        setContentView(webview);
        TRANSPORT = new HttpTrace();

        authorizationUrl = new GoogleAuthorizationRequestUrl(OAuthGACredentials.CLIENT_ID, OAuthGACredentials.REDIRECT_URI, OAuthGACredentials.SCOPE).build();
        Log.i("AuthorizationUrl1", authorizationUrl);
        Toast.makeText(this, "AuthorizationUrl :"+authorizationUrl, Toast.LENGTH_LONG).show();

        webview.setWebViewClient(new WebViewClient() {  

            @Override  
            public void onPageStarted(WebView view, String url,Bitmap bitmap)  {  
                System.out.println("onPageStarted : " + url);
            }
            @Override  
            public void onPageFinished(WebView view, String url)  {  

                Log.i("OnPageFinished: url :", url);
                if (url.startsWith(OAuthGACredentials.REDIRECT_URI)) {
                    Log.i("url.startsWith(OAuthGACredentials.REDIRECT_URI) :", "true");

                    try {

                        if (url.indexOf("code=")!=-1) {
                            String code = extractCodeFromUrl(url);
                            Log.i("Authorisation code:",code );

                              AccessTokenResponse accessTokenResponse = new GoogleAuthorizationCodeGrant(new NetHttpTransport(),
                                      new JacksonFactory(),
                                      OAuthGACredentials.CLIENT_ID,
                                      OAuthGACredentials.CLIENT_SECRET,
                                      code,
                                      OAuthGACredentials.REDIRECT_URI).execute();


                              CredentialStore credentialStore = new SharedPreferencesCredentialStore(prefs);
                              credentialStore.write(accessTokenResponse);
                              view.setVisibility(View.INVISIBLE);
                              Toast.makeText(OauthGoogleAnalytics.this,"Succcessfully got access token :"+accessTokenResponse.accessToken , Toast.LENGTH_SHORT).show();
                              System.out.println("access token:"+accessTokenResponse.accessToken );

            System.out.println("What is the authorization code?");


                                authorizationCode=accessTokenResponse.accessToken ;
                                Toast.makeText(OauthGoogleAnalytics.this, " getting input"+authorizationCode, Toast.LENGTH_SHORT).show();
                                 System.out.println("getting input"+authorizationCode);

        JacksonFactory jsonFactory = new JacksonFactory();
                            HttpTransport transport = new NetHttpTransport();

                            accessTokenResponse = credentialStore.read();

                            GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(accessTokenResponse.accessToken,
                                    transport,
                                    jsonFactory,
                                    OAuthGACredentials.CLIENT_ID,
                                    OAuthGACredentials.CLIENT_SECRET,
                                    accessTokenResponse.refreshToken);
                            Toast.makeText(OauthGoogleAnalytics.this, "access proteced resource"+accessProtectedResource.toString(),Toast.LENGTH_SHORT).show();
                            System.out.println("Access protected resource:"+accessProtectedResource.toString());

    Analytics analytics = Analytics.builder(httptransport, JSON_FACTORY)
                                    .setHttpRequestInitializer(accessProtectedResource)
                                    .setApplicationName("TRA-Analytics")
                                    .build();
                                Log.i("Analytics","Analytics:management"+analytics.management().toString());

                                com.google.api.services.analytics.model.Accounts accounts=analytics.management().accounts().list().execute();
                                for (com.google.api.services.analytics.model.Account account : accounts.getItems()) {
                                      System.out.println("Account ID: " + account.getId());
                                      System.out.println("Account Name: " + account.getName());
                                      System.out.println("Account Created: " + account.getCreated());
                                      System.out.println("Account Updated: " + account.getUpdated());
                                    }

                            com.google.api.services.analytics.model.Webproperties webproperties = analytics.management().webproperties().list("~all").execute();

                            for (Webproperty webproperty : webproperties.getItems()) {
                                  System.out.println("Account ID: " + webproperty.getAccountId());
                                  System.out.println("Web Property ID: " + webproperty.getId());
                                  System.out.println("Web Property Name: " + webproperty.getName());
                                  System.out.println("Web Property Internal Id: " + webproperty.getInternalWebPropertyId());
                                  System.out.println("Web Property Website URL: " + webproperty.getWebsiteUrl());
                                  System.out.println("Web Property Created: " + webproperty.getCreated());
                                  System.out.println("Web Property Updated: " + webproperty.getUpdated());
                                }

                            com.google.api.services.analytics.model.Profiles profiles = analytics.management().profiles().list("~all", "~all").execute();

                            for (Profile profile : profiles.getItems()) {
                                  System.out.println("Account ID: " + profile.getAccountId());
                                  System.out.println("Web Property ID: " + profile.getWebPropertyId());
                                  System.out.println("Web Property Internal ID: " + profile.getInternalWebPropertyId());
                                  System.out.println("Profile ID: " + profile.getId());
                                  System.out.println("Profile Name: " + profile.getName());

                                  System.out.println("Profile defaultPage: " + profile.getDefaultPage());
                                  System.out.println("Profile Exclude Query Parameters: "
                                      + profile.getExcludeQueryParameters());
                                  System.out.println("Profile Site Search Query Parameters: "
                                      + profile.getSiteSearchQueryParameters());
                                  System.out.println("Profile Site Search Category Parameters: "
                                      + profile.getSiteSearchCategoryParameters());

                                  System.out.println("Profile Currency: " + profile.getCurrency());
                                  System.out.println("Profile Timezone: " + profile.getTimezone());
                                  System.out.println("Profile Updated: " + profile.getUpdated());
                                  System.out.println("Profile Created: " + profile.getCreated());
                                }

                            com.google.api.services.analytics.model.Goals goals = analytics.management().goals().list("~all", "~all", "420").execute();

                            for (Goal goal : goals.getItems()) {
                                  System.out.println("Account ID: " + goal.getAccountId());
                                  System.out.println("Web Property ID: " + goal.getWebPropertyId());
                                  System.out.println("Web Property Internal Id: " + goal.getInternalWebPropertyId());
                                  System.out.println("Profile ID: " + goal.getId());

                                  System.out.println("Goal Number: " + goal.getId());
                                  System.out.println("Goal Name: " + goal.getName());
                                  System.out.println("Is Goal Active: " + goal.getActive());
                                  System.out.println("Goal Value: " + goal.getValue());
                                  System.out.println("Goal Type: " + goal.getType());
                                  System.out.println("Goal Created: " + goal.getCreated());
                                  System.out.println("Goal Updated: " + goal.getUpdated());



                        } else if (url.indexOf("error=")!=-1) {
                            view.setVisibility(View.INVISIBLE);
                            new SharedPreferencesCredentialStore(prefs).clearCredentials();
                            startActivity(new Intent(OauthGoogleAnalytics.this,TabView.class));
                        }

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

                }
                System.out.println("onPageFinished : " + url);

            }


            private String extractCodeFromUrl(String url) {
                return url.substring(OAuthGACredentials.REDIRECT_URI.length()+7,url.length());
            }  
        });  

        webview.loadUrl(authorizationUrl);      
    }

}

=============================================== ==============

请任何人帮助我,我从最近1个月开始尝试 提前谢谢....

0 个答案:

没有答案