Unity接入Google游戏服务

作者:追风剑情 发布于:2017-8-17 20:13 分类:Android

以下代码接入了Google的:广告、排行榜、分享、评论功能。

build.gradle配置


// GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN
buildscript {
	repositories {
		jcenter()
	}

	dependencies {
		classpath 'com.android.tools.build:gradle:2.3.0'
	}

	dependencies {
		classpath 'com.google.gms:google-services:3.0.0'
	}
}

allprojects {
   repositories {
	   jcenter()
      flatDir {
        dirs 'libs'
      }
   }
}

apply plugin: 'com.android.application'

dependencies {
	compile fileTree(dir: 'libs', include: ['*.jar'])
	compile 'com.google.android.gms:play-services-fitness:9.6.1'
	compile 'com.google.android.gms:play-services-wearable:9.6.1'
	compile 'com.google.android.gms:play-services-games:9.6.1'
}

android {
	compileSdkVersion 25
	buildToolsVersion '25.0.2'

	defaultConfig {
		targetSdkVersion 25
		versionCode 7
		versionName "1.7"
		multiDexEnabled true
	}

	lintOptions {
		abortOnError false
	}
	signingConfigs { release {
		storeFile file('D:/h5/UnityProjects/KeyStore/xxx.keystore')
		storePassword 'xxx'
		keyAlias 'xxxxxx'
		keyPassword 'xxxxxxx'
		v1SigningEnabled true
		v2SigningEnabled true
	} }

	buildTypes {
		debug {
			jniDebuggable true
		}
		release {
			minifyEnabled false
			proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'
			signingConfig signingConfigs.release
		}
	}

}

dependencies {
	compile fileTree(dir: 'libs', include: ['*.jar'])

	compile 'com.google.firebase:firebase-core:9.6.1'
	compile 'com.google.firebase:firebase-ads:9.6.1'
	compile 'com.google.firebase:firebase-crash:9.6.1'
	compile 'com.android.support:support-v13:25.1.0'
	compile 'com.android.support:recyclerview-v7:25.1.0'


	// Vungle Adapter for AdMob
	compile(name: 'VungleAdapter', 'ext': 'aar')
	compile('name':'unity-ads', 'ext':'aar')
	compile 'com.google.ads.mediation:unity:2.0.8.0'
	compile 'com.squareup.picasso:picasso:2.5.2'
	compile 'com.android.support:multidex:1.0.1'
}

apply plugin: 'com.google.gms.google-services'


AndroidManifest.xml配置


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.zwwx.game.smallball" xmlns:tools="http://schemas.android.com/tools" android:versionName="1.2" android:versionCode="3" android:installLocation="preferExternal">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
  <application android:theme="@style/UnityThemeSelector" android:icon="@drawable/app_icon" android:roundIcon="@drawable/app_icon" android:label="@string/app_name" android:isGame="true" android:banner="@drawable/app_banner">
    <activity android:label="@string/app_name" android:screenOrientation="portrait" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale" android:name=".MainActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
      </intent-filter>
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
    </activity>
      <meta-data android:name="com.google.android.gms.games.APP_ID"
        android:value="@string/app_id" />
      <meta-data
          android:name="com.google.android.gms.version"
          android:value="@integer/google_play_services_version" />
      <activity android:name="com.vungle.publisher.VideoFullScreenAdActivity"
          android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize"
          android:theme="@android:style/Theme.NoTitleBar.Fullscreen"/>

      <activity android:name="com.vungle.publisher.MraidFullScreenAdActivity"
          android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize"
          android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"/>

      <activity android:name="com.vungle.publisher.FullScreenAdActivity"
          android:configChanges="keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize"
          android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"/>

      <activity
          android:name="com.google.android.gms.ads.AdActivity"
          android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
          android:theme="@android:style/Theme.Translucent" />

      <activity
          android:name="com.inmobi.rendering.InMobiAdActivity"
          android:configChanges="keyboardHidden|orientation|keyboard|smallestScreenSize|screenSize|screenLayout"
          android:hardwareAccelerated="true"
          android:resizeableActivity="false"
          android:theme="@android:style/Theme.NoTitleBar"/>

      <receiver
          android:name="com.inmobi.commons.core.utilities.uid.ImIdShareBroadCastReceiver"
          android:enabled="true"
          android:exported="true" >
          <intent-filter>
              <action android:name="com.inmobi.share.id" />
          </intent-filter>
      </receiver>
  </application>
  <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="25" />
  <uses-feature android:glEsVersion="0x00020000" />

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.RESTART_PACKAGES" />
    <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.READ_LOGS" />
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
    <uses-permission android:name="android.permission.READ_CALENDAR"/>
    <uses-permission android:name="android.permission.WRITE_CALENDAR"/>

    <uses-permission android:name="android.permission.GET_TASKS"/>
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
  <uses-permission android:name="android.permission.READ_PHONE_STATE" />

  <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
  <uses-feature android:name="android.software.leanback" android:required="false"/>
</manifest>


Java代码


package com.zwwx.game.smallball;

import android.content.ActivityNotFoundException;
import android.content.IntentSender;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import android.content.Intent;
import android.net.Uri;
import java.io.File;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
//import com.google.android.gms.appstate.AppStateManager;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.games.Games;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.unity3d.player.UnityPlayer;
import org.json.JSONObject;
import org.json.JSONException;

/**
 * Created by YangLiu on 2017/3/23.
 */

public class MainActivity extends UnityPlayerActivity implements RewardedVideoAdListener, ConnectionCallbacks,
        OnConnectionFailedListener{

    private static final String TAG = "zwwx";

    private static final String CONTINUE_GAME = "ContinueGame";
    private static final String ON_REWARDED_VIDEO = "OnRewardedVideo";
    private static final String ON_REWARDED_VIDEO_AD_LOADED = "OnRewardedVideoAdLoaded";
    private static final String ON_REWARDED_VIDEO_AD_CLOSED = "OnRewardedVideoAdClosed";

    private static final int REQUEST_LEADERBOARD = 100;
    private static final int RC_SIGN_IN = 9001;//登录UI返回的requestCode
    private static final int REQUEST_CODE_RESOLVE_ERR = 1000;

    private String bannerAdsId = null;
    private String interAdsId = null;
    private String videoAdsId = null;

    private String unityObject = null;
    private String unityObjectFun = null;

    private AdView mAdView;
    private InterstitialAd mInterstitialAd;
    private RewardedVideoAd mRewardedVideoAd;
    private boolean mAdsTestModel = false;
    private FirebaseAnalytics mFirebaseAnalytics;
    private GoogleApiClient mGoogleApiClient;

    @Override protected void onCreate (Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //添加横幅广告
                mAdView = new AdView(MainActivity.this);
                mAdView.setAdSize(AdSize.SMART_BANNER);
                mAdView.setAdListener(new AdListener() {
                    @Override
                    public void onAdLoaded() {
                        Log.d(TAG, "Banner Ad loaded: onAdLoaded()");
                        RelativeLayout.LayoutParams view_para = new RelativeLayout.LayoutParams(
                                AdSize.SMART_BANNER.getWidthInPixels(MainActivity.this),
                                AdSize.SMART_BANNER.getHeightInPixels(MainActivity.this));
                        view_para.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.TRUE);
                        view_para.addRule(RelativeLayout.CENTER_HORIZONTAL,RelativeLayout.TRUE);
                        mAdView.setLayoutParams(view_para);
                    }
                });

                int screenW = MainActivity.this.getWindowManager().getDefaultDisplay().getWidth();
                int screenH = MainActivity.this.getWindowManager().getDefaultDisplay().getHeight();
                Log.d(TAG, "screen width: "+screenW);
                Log.d(TAG, "screen height: "+screenH);

                RelativeLayout layout = new RelativeLayout(MainActivity.this);
                layout.addView(mAdView, new RelativeLayout.LayoutParams(screenW, screenH));
                mUnityPlayer.addView(layout);

                //初始化全屏广告
                mInterstitialAd = new InterstitialAd(MainActivity.this);
                mInterstitialAd.setAdListener(new AdListener() {
                    @Override
                    public void onAdClosed() {
                        loadInterstitial();
                        continueGame();
                    }
                });

                //初始化激励视频广告
                mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(MainActivity.this);
                mRewardedVideoAd.setRewardedVideoAdListener(MainActivity.this);
            }
        });

        hideBanner();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Games.API).addScope(Games.SCOPE_GAMES) // Games
                //.addApi(AppStateManager.API).addScope(AppStateManager.SCOPE_APP_STATE) // AppState
                //.addScope(Drive.SCOPE_APPFOLDER) // SavedGames
                .build();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(!mGoogleApiClient.isConnected())
            mGoogleApiClient.connect();
    }

    // 向Unity发消息
    private void sendMessageToUnity(String type)
    {
        sendMessageToUnity(type, "");
    }

    private void sendMessageToUnity(String type, String data)
    {
        if(null == unityObject || null == unityObjectFun)
            return;
        JSONObject jsonObj = new JSONObject();
        try{
            jsonObj.put("type", type);
            jsonObj.put("data", data);
            UnityPlayer.UnitySendMessage(unityObject, unityObjectFun, jsonObj.toString());
        }catch(JSONException e){
            Log.e(TAG, "JSONException: sendMessageToUnity() type="+type);
            Log.e(TAG, e.getLocalizedMessage());
        }
    }

    // 继续游戏
    private void continueGame()
    {
        sendMessageToUnity(CONTINUE_GAME);
    }

    // 设置广告应用ID
    public  void setAdMobId(String appId)
    {
        Log.d(TAG, "admob_id="+appId);
        MobileAds.initialize(this, appId);
    }

    // 设置广告单元ID
    public void setAdUnitId(String bannerAdsId, String interAdsId, String videoAdsId)
    {
        Log.d(TAG, "bannerAdsId="+bannerAdsId);
        Log.d(TAG, "interAdsId="+interAdsId);
        Log.d(TAG, "videoAdsId="+videoAdsId);

        this.bannerAdsId = bannerAdsId;
        this.interAdsId = interAdsId;
        this.videoAdsId = videoAdsId;

        mAdView.setAdUnitId(bannerAdsId);
        mInterstitialAd.setAdUnitId(interAdsId);
        loadInterstitial();
        loadRewardedVideoAd();
    }

    public  void setAdsTestModel(boolean testModel)
    {
        Log.d(TAG, "testModel="+testModel);
        this.mAdsTestModel = testModel;
    }

    public void setUnityListener(String unityObject, String functionName)
    {
        Log.d(TAG, "unityObject="+unityObject+", functionName="+functionName);
        this.unityObject = unityObject;
        this.unityObjectFun = functionName;
    }

    // 加载横幅广告
    private void loadBanner()
    {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(null == bannerAdsId)
                    return;

                if(mAdView.isLoading())
                    return;

                AdRequest.Builder builder = new AdRequest.Builder();
                if(mAdsTestModel)
                {
                    builder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
                    builder.addTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4");
                }
                AdRequest adRequest = builder.build();
                mAdView.loadAd(adRequest);
                Log.d(TAG, "Request banner ad: mAdView.loadAd(adRequest)");
            }
        });
    }

    // 显示横幅广告
    public  void showBanner()
    {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mAdView.setVisibility(View.VISIBLE);
                loadBanner();
            }
        });
    }

    // 隐藏横幅广告
    public  void hideBanner()
    {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mAdView.setVisibility(View.GONE);
            }
        });
    }

    // 加载全屏广告
    private void loadInterstitial()
    {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(null == interAdsId)
                    return;

                if(mInterstitialAd.isLoading() || mInterstitialAd.isLoaded())
                    return;

                AdRequest.Builder builder = new AdRequest.Builder();
                if(mAdsTestModel)
                {
                    builder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
                    builder.addTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4");
                }
                AdRequest adRequest = builder.build();
                mInterstitialAd.loadAd(adRequest);
            }
        });
    }

    // 显示全屏广告
    public void showInterstitial()
    {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mInterstitialAd.isLoaded()) {
                    mInterstitialAd.show();
                } else {
                    continueGame();
                    if(!mInterstitialAd.isLoading())
                        loadInterstitial();
                }
            }
        });
    }

    // 加载激励视频广告
    private void loadRewardedVideoAd()
    {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(null == videoAdsId)
                    return;

                if(mRewardedVideoAd.isLoaded())
                    return;

                // build network extras bundle
                //Bundle extras = new VungleExtrasBuilder()
                //.setSoundEnabled(true)
                //.build();
                //Bundle extras = new Bundle();

                AdRequest.Builder builder = new AdRequest.Builder();
                if(mAdsTestModel)
                {
                    builder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
                    builder.addTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4");
                }
                AdRequest adRequest = builder.build();
                mRewardedVideoAd.loadAd(videoAdsId, adRequest);
                Log.d(TAG, "Request Reward Video: mRewardedVideoAd.loadAd(videoAdsId, adRequest)");
            }
        });
    }

    // 激励视频是否已加载
    private boolean isVideoLoaded;
    public boolean isRewardVideoLoaded()
    {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                isVideoLoaded = mRewardedVideoAd.isLoaded();
            }
        });
        return isVideoLoaded;
    }

    // 显示激励视频
    public  void showRewardVideo()
    {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(!mRewardedVideoAd.isLoaded()){
                    loadRewardedVideoAd();
                    return;
                }
                mRewardedVideoAd.show();
            }
        });
    }

    @Override
    public void onRewardedVideoAdLeftApplication() {
        Log.d(TAG, "onRewardedVideoAdLeftApplication()");
    }

    @Override
    public void onRewardedVideoAdClosed() {
        Log.d(TAG, "onRewardedVideoAdClosed()");
        sendMessageToUnity(ON_REWARDED_VIDEO_AD_CLOSED);
    }

    @Override
    public void onRewardedVideoAdFailedToLoad(int errorCode) {
        Log.d(TAG, "onRewardedVideoAdFailedToLoad() errorCode="+errorCode);
    }

    @Override
    public void onRewardedVideoAdLoaded() {
        Log.d(TAG, "onRewardedVideoAdLoaded()");
        sendMessageToUnity(ON_REWARDED_VIDEO_AD_LOADED);
    }

    @Override
    public void onRewardedVideoAdOpened() {
        Log.d(TAG, "onRewardedVideoAdOpened()");
    }

    @Override
    public void onRewarded(RewardItem reward) {
        Log.d(TAG, "onRewarded()");
        sendMessageToUnity(ON_REWARDED_VIDEO);
    }

    @Override
    public void onRewardedVideoStarted() {
        Log.d(TAG, "onRewardedVideoStarted()");
    }

    // Resume Unity
    @Override protected void onResume()
    {
        super.onResume();

        //侦听网络连接
        intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(intentReceiver, intentFilter);
    }

    // Pause Unity
    @Override protected void onPause()
    {
        super.onPause();
        unregisterReceiver(intentReceiver);
    }

    // Quit Unity
    @Override protected void onDestroy ()
    {
        super.onDestroy();
        mRewardedVideoAd.destroy(this);
    }

    IntentFilter intentFilter;

    //处理侦听到的意图广播
    private BroadcastReceiver intentReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            if(null == activeNetwork)
            {
                //Toast.makeText(getBaseContext(), "无网络连接", Toast.LENGTH_LONG).show();
                Log.d(TAG, "无网络连接");
                return;
            }
            boolean isConnected = activeNetwork.isConnectedOrConnecting();
            boolean isMobile = activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE;
            if(isConnected){
                loadBanner();
                loadInterstitial();
                loadRewardedVideoAd();
                if(!mGoogleApiClient.isConnected())
                    mGoogleApiClient.connect();
            }
            //Toast.makeText(getBaseContext(), "网络已连接:"+isConnected+", 移动网络: "+isMobile, Toast.LENGTH_LONG).show();
            Log.d(TAG, "网络已连接:"+isConnected+", 移动网络: "+isMobile);
        }
    };

    //分享单张图片
    public void shareSingleImage(String title, String imagePath) {
        //String imagePath = Environment.getExternalStorageDirectory() + File.separator + "test.jpg";
        //由文件得到uri
        Uri imageUri = Uri.fromFile(new File(imagePath));
        Log.d("share", "uri:" + imageUri);

        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setType("image/*");
        startActivity(Intent.createChooser(
                shareIntent, title));
    }

    //打开App所在Google商店的下载页面(评论url)
    public void openCommentUrl()
    {
        Uri uri = Uri.parse("market://details?id=" + this.getPackageName());
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
                Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
        try {
            this.startActivity(goToMarket);
        } catch (ActivityNotFoundException e) {
            this.startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://play.google.com/store/apps/details?id=" + this.getPackageName())));
        }
    }

    //解锁成就
    public void unlockAchievement(String achievementId)
    {
        Bundle bundle = new Bundle();
        bundle.putString(FirebaseAnalytics.Param.ACHIEVEMENT_ID, achievementId);
        mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.UNLOCK_ACHIEVEMENT, bundle);
    }

    //GoogleApiClient连接成功
    @Override
    public void onConnected(Bundle connectionHint) {
        Log.d(TAG, "[GoogleApiClient] onConnected: connected!");
    }

    //GoogleApiClient连接失败
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.d(TAG, "[GoogleApiClient] onConnectionFailed: "+result.getErrorMessage() + ", "+result.toString());
        if (result.hasResolution()) {
            try {
                result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
            } catch (IntentSender.SendIntentException e) {
                mGoogleApiClient.connect();
            }
        }
    }

    //GoogleApiClient连接断开
    @Override
    public void onConnectionSuspended(int cause) {
        Log.d(TAG, "[GoogleApiClient] onConnectionSuspended, cause=" + cause);
    }

    //上报积分
    public void submitScore(String leaderboardId, long score){
        if(!mGoogleApiClient.isConnected()) {
            mGoogleApiClient.connect();
            return;
        }
        Games.Leaderboards.submitScore(mGoogleApiClient, leaderboardId, score);
    }

    //打开排行榜界面
    public void showLeaderboardUI(String leaderboardId){
        if(!mGoogleApiClient.isConnected()) {
            mGoogleApiClient.connect();
            return;
        }
        startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,
                leaderboardId), REQUEST_LEADERBOARD);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: requestCode="+requestCode+", resultCode="+resultCode);
        if (requestCode == RC_SIGN_IN) {
            if (resultCode == RESULT_OK) {
                // Sign-in was successful, connect the API Client
                Log.d(TAG, "onActivityResult: RC_SIGN_IN (OK)");
                mGoogleApiClient.connect();
            }else{
                Log.d(TAG, "onActivityResult: RC_SIGN_IN (Error)");
            }
        }
    }
}

完整项目工程
链接:http://pan.baidu.com/s/1c1HX5LY 密码:8e1p

标签: Android

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号