Android Studio 解决方案:
我刚刚通过使用gplus-quickstart的代码示例,并使用问题中链接的指南添加了一个+1按钮,使得简单的示例可以工作。
build.gradle 依赖项:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
compile 'com.google.android.gms:play-services:7.0.0'
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.plustest.daniel.googleplusone" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</manifest>
我在activity_main.xml的底部添加了com.google.android.gms.plus.PlusOneButton
,该文件基于main_activity.xml的快速启动代码。
xmlns:plus="http://schemas.android.com/apk/lib/com.google.android.gms.plus"
android:id="@+id/plus_one_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
plus:size="standard"
plus:annotation="inline" />
带有新增的+1按钮的MainActivity.java。
请注意,我使用了卡内基梅隆计算机科学学院的Google+页面作为URL
。
public class MainActivity extends FragmentActivity implements
ConnectionCallbacks, OnConnectionFailedListener,
ResultCallback<LoadPeopleResult>, View.OnClickListener,
CheckBox.OnCheckedChangeListener, GoogleApiClient.ServerAuthCodeCallbacks {
private static final String TAG = "android-plus-quickstart";
private static final int STATE_DEFAULT = 0;
private static final int STATE_SIGN_IN = 1;
private static final int STATE_IN_PROGRESS = 2;
private static final int RC_SIGN_IN = 0;
private static final String SAVED_PROGRESS = "sign_in_progress";
private static final String WEB_CLIENT_ID = "WEB_CLIENT_ID";
private static final String SERVER_BASE_URL = "SERVER_BASE_URL";
private static final String EXCHANGE_TOKEN_URL = SERVER_BASE_URL + "/exchangetoken";
private static final String SELECT_SCOPES_URL = SERVER_BASE_URL + "/selectscopes";
private int mSignInProgress;
private PendingIntent mSignInIntent;
private int mSignInError;
private boolean mRequestServerAuthCode = false;
private boolean mServerHasToken = true;
private SignInButton mSignInButton;
private Button mSignOutButton;
private Button mRevokeButton;
private TextView mStatus;
private ListView mCirclesListView;
private ArrayAdapter<String> mCirclesAdapter;
private ArrayList<String> mCirclesList;
private PlusOneButton mPlusOneButton;
private String URL = "https://plus.google.com/101009371381835899795/posts";
private static final int PLUS_ONE_REQUEST_CODE = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
mSignOutButton = (Button) findViewById(R.id.sign_out_button);
mRevokeButton = (Button) findViewById(R.id.revoke_access_button);
mStatus = (TextView) findViewById(R.id.sign_in_status);
mCirclesListView = (ListView) findViewById(R.id.circles_list);
mPlusOneButton = (PlusOneButton) findViewById(R.id.plus_one_button);
mSignInButton.setOnClickListener(this);
mSignOutButton.setOnClickListener(this);
mRevokeButton.setOnClickListener(this);
((CheckBox) findViewById(R.id.request_auth_code_checkbox)).setOnCheckedChangeListener(this);
((CheckBox) findViewById(R.id.has_token_checkbox)).setOnCheckedChangeListener(this);
mCirclesList = new ArrayList<String>();
mCirclesAdapter = new ArrayAdapter<String>(
this, R.layout.circle_member, mCirclesList);
mCirclesListView.setAdapter(mCirclesAdapter);
if (savedInstanceState != null) {
mSignInProgress = savedInstanceState
.getInt(SAVED_PROGRESS, STATE_DEFAULT);
}
mGoogleApiClient = buildGoogleApiClient();
}
private GoogleApiClient buildGoogleApiClient() {
GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API, Plus.PlusOptions.builder().build())
.addScope(Plus.SCOPE_PLUS_LOGIN);
if (mRequestServerAuthCode) {
checkServerAuthConfiguration();
builder = builder.requestServerAuthCode(WEB_CLIENT_ID, this);
}
return builder.build();
}
@Override
protected void onResume() {
super.onResume();
mPlusOneButton.initialize(URL, PLUS_ONE_REQUEST_CODE);
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(SAVED_PROGRESS, mSignInProgress);
}
@Override
public void onClick(View v) {
if (!mGoogleApiClient.isConnecting()) {
switch (v.getId()) {
case R.id.sign_in_button:
mStatus.setText(R.string.status_signing_in);
mSignInProgress = STATE_SIGN_IN;
mGoogleApiClient.connect();
break;
case R.id.sign_out_button:
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
}
onSignedOut();
break;
case R.id.revoke_access_button:
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient);
mGoogleApiClient = buildGoogleApiClient();
mGoogleApiClient.connect();
break;
}
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.request_auth_code_checkbox:
mRequestServerAuthCode = isChecked;
buildGoogleApiClient();
if (isChecked) {
findViewById(R.id.layout_has_token).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.layout_has_token).setVisibility(View.INVISIBLE);
}
break;
case R.id.has_token_checkbox:
mServerHasToken = isChecked;
break;
}
}
@Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "onConnected");
mSignInButton.setEnabled(false);
mSignOutButton.setEnabled(true);
mRevokeButton.setEnabled(true);
findViewById(R.id.layout_server_auth).setVisibility(View.GONE);
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
mStatus.setText(String.format(
getResources().getString(R.string.signed_in_as),
currentUser.getDisplayName()));
Plus.PeopleApi.loadVisible(mGoogleApiClient, null)
.setResultCallback(this);
mSignInProgress = STATE_DEFAULT;
}
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "onConnectionFailed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
if (result.getErrorCode() == ConnectionResult.API_UNAVAILABLE) {
Log.w(TAG, "API Unavailable.");
} else if (mSignInProgress != STATE_IN_PROGRESS) {
mSignInIntent = result.getResolution();
mSignInError = result.getErrorCode();
if (mSignInProgress == STATE_SIGN_IN) {
resolveSignInError();
}
}
onSignedOut();
}
private void resolveSignInError() {
if (mSignInIntent != null) {
try {
mSignInProgress = STATE_IN_PROGRESS;
startIntentSenderForResult(mSignInIntent.getIntentSender(),
RC_SIGN_IN, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.i(TAG, "Sign in intent could not be sent: "
+ e.getLocalizedMessage());
mSignInProgress = STATE_SIGN_IN;
mGoogleApiClient.connect();
}
} else {
createErrorDialog().show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
switch (requestCode) {
case RC_SIGN_IN:
if (resultCode == RESULT_OK) {
mSignInProgress = STATE_SIGN_IN;
} else {
mSignInProgress = STATE_DEFAULT;
}
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
break;
}
}
@Override
public void onResult(LoadPeopleResult peopleData) {
if (peopleData.getStatus().getStatusCode() == CommonStatusCodes.SUCCESS) {
mCirclesList.clear();
PersonBuffer personBuffer = peopleData.getPersonBuffer();
try {
int count = personBuffer.getCount();
for (int i = 0; i < count; i++) {
mCirclesList.add(personBuffer.get(i).getDisplayName());
}
} finally {
personBuffer.close();
}
mCirclesAdapter.notifyDataSetChanged();
} else {
Log.e(TAG, "Error requesting visible circles: " + peopleData.getStatus());
}
}
private void onSignedOut() {
mSignInButton.setEnabled(true);
mSignOutButton.setEnabled(false);
mRevokeButton.setEnabled(false);
findViewById(R.id.layout_server_auth).setVisibility(View.VISIBLE);
mStatus.setText(R.string.status_signed_out);
mCirclesList.clear();
mCirclesAdapter.notifyDataSetChanged();
}
@Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
}
private Dialog createErrorDialog() {
if (GooglePlayServicesUtil.isUserRecoverableError(mSignInError)) {
return GooglePlayServicesUtil.getErrorDialog(
mSignInError,
this,
RC_SIGN_IN,
new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
Log.e(TAG, "Google Play services resolution cancelled");
mSignInProgress = STATE_DEFAULT;
mStatus.setText(R.string.status_signed_out);
}
});
} else {
return new AlertDialog.Builder(this)
.setMessage(R.string.play_services_error)
.setPositiveButton(R.string.close,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.e(TAG, "Google Play services error could not be "
+ "resolved: " + mSignInError);
mSignInProgress = STATE_DEFAULT;
mStatus.setText(R.string.status_signed_out);
}
}).create();
}
}
@Override
public CheckResult onCheckServerAuthorization(String idToken, Set<Scope> scopeSet) {
Log.i(TAG, "Checking if server is authorized.");
Log.i(TAG, "Mocking server has refresh token: " + String.valueOf(mServerHasToken));
if (!mServerHasToken) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(SELECT_SCOPES_URL);
HashSet<Scope> serverScopeSet = new HashSet<Scope>();
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
int responseCode = httpResponse.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(httpResponse.getEntity());
if (responseCode == 200) {
String[] scopeStrings = responseBody.split(" ");
for (String scope : scopeStrings) {
Log.i(TAG, "Server Scope: " + scope);
serverScopeSet.add(new Scope(scope));
}
} else {
Log.e(TAG, "Error in getting server scopes: " + responseCode);
}
} catch (ClientProtocolException e) {
Log.e(TAG, "Error in getting server scopes.", e);
} catch (IOException e) {
Log.e(TAG, "Error in getting server scopes.", e);
}
return CheckResult.newAuthRequiredResult(serverScopeSet);
} else {
return CheckResult.newAuthNotRequiredResult();
}
}
@Override
public boolean onUploadServerAuthCode(String idToken, String serverAuthCode) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(EXCHANGE_TOKEN_URL);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("serverAuthCode", serverAuthCode));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
final String responseBody = EntityUtils.toString(response.getEntity());
Log.i(TAG, "Code: " + statusCode);
Log.i(TAG, "Resp: " + responseBody);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, responseBody, Toast.LENGTH_LONG).show();
}
});
return (statusCode == 200);
} catch (ClientProtocolException e) {
Log.e(TAG, "Error in auth code exchange.", e);
return false;
} catch (IOException e) {
Log.e(TAG, "Error in auth code exchange.", e);
return false;
}
}
private void checkServerAuthConfiguration() {
if ("WEB_CLIENT_ID".equals(WEB_CLIENT_ID) ||
"SERVER_BASE_URL".equals(SERVER_BASE_URL)) {
Log.w(TAG, "WEB_CLIENT_ID or SERVER_BASE_URL configured incorrectly.");
Dialog dialog = new AlertDialog.Builder(this)
.setMessage(getString(R.string.configuration_error))
.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
dialog.show();
}
}
}
登录并点击+1按钮后的结果如下: