コメント
コメントの投稿
※名前とタイトルが入力されていないコメントでは他のコメントとの区別ができません。
入力されていないコメントには返信しませんのであらかじめご了承くださいませ。
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
namespace AppName.Droid
{
[Activity(Label = "AppName"]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity,
GoogleApiClient.IConnectionCallbacks,
GoogleApiClient.IOnConnectionFailedListener
{
public const int RC_SIGN_IN = 9001;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
//Google SignIn
Scope calendarScope = new Scope("https://www.googleapis.com/auth/calendar");
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
.RequestScopes(new Scope(Scopes.Email),
calendarScope)
.RequestEmail()
//.RequestServerAuthCode(serverClientId, false) //必要なし
//.RequestIdToken(serverClientId) //必要なし
.Build();
GoogleSignInService.GoogleApiClient = new GoogleApiClient.Builder(this)
.EnableAutoManage(this, this)
.AddApi(PlusClass.API)
.AddScope(calendarScope)
.Build();
}
protected override void OnActivityResult(int requestCode, Result resultCode, global::Android.Content.Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN)
{
//Google SignIn の認証結果を受け取る
GoogleSignInResult result = Auth.GoogleSignInApi.GetSignInResultFromIntent(data);
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result)
{
if (result != null &&
result.IsSuccess)
{
Task.Run(() =>
{
//メールアドレス・トークンを取得する
GoogleSignInAccount account = result.SignInAccount;
GoogleSignInService.MailAddress = account.Email;
GoogleSignInService.AccessToken = Android.Gms.Auth.GoogleAuthUtil.GetToken(
Application.Context,
new Android.Accounts.Account(account.Email, "com.google"),
"oauth2:" + "https://www.googleapis.com/auth/calendar");
}).ConfigureAwait(false);
}
}
}
}
public class GoogleSignInService : IGoogleSignInService
{
public static GoogleApiClient GoogleApiClient;
//サインイン
public void SignIn()
{
if (GoogleSignInService.GoogleApiClient != null)
{
Intent signInIntent = Auth.GoogleSignInApi.GetSignInIntent(GoogleSignInService.GoogleApiClient);
((Activity)Forms.Context).StartActivityForResult(signInIntent, MainActivity.RC_SIGN_IN);
}
}
//サインアウト
public void SignOut()
{
if (GoogleSignInService.GoogleApiClient != null &&
GoogleSignInService.GoogleApiClient.IsConnected)
{
Auth.GoogleSignInApi.SignOut(GoogleSignInService.GoogleApiClient);
}
}
//切断処理
public void Disconnect()
{
if (GoogleSignInService.GoogleApiClient != null &&
GoogleSignInService.GoogleApiClient.IsConnected)
{
Auth.GoogleSignInApi.RevokeAccess(GoogleSignInService.GoogleApiClient);
}
}
}
※名前とタイトルが入力されていないコメントでは他のコメントとの区別ができません。
入力されていないコメントには返信しませんのであらかじめご了承くださいませ。