使用 Xamarin.Android 为 Parse.com 服务器制作更漂亮的 Facebook 登录屏幕
Making a prettier Facebook Login Screen for Parse.com Server with Xamarin.Android
我正在尝试为 Xamarin.Android 创建一个登录系统,以便在 Parse 服务器上使用。我想用 Facebook 登录用户并保存他的真实姓名和他的小用户照片。
我当前显示登录系统的代码是这样的:
using Xamarin.Auth;
loginFacebookButton.Click += (sender, e) =>
{
if (CrossConnectivity.Current.IsConnected)
LoginToFacebook();
else
{
DisplayNoConnectivityMessage();
}
};
loginTwitterButton.Click += (sender, e) =>
{
LoginToTwitter();
};
}
void DisplayNoConnectivityMessage()
{
AlertDialog.Builder alert2 = new AlertDialog.Builder(this);
alert2.SetTitle("Network error");
alert2.SetMessage("Connection with the Internet is required. Please check your connectivity and try again.");
alert2.Show();
}
void DisplayLoadingMessage(bool Dismiss)
{
RunOnUiThread(() =>
{
if (!Dismiss)
{
builder = new AlertDialog.Builder(this);
builder.SetTitle("Signing in");
builder.SetMessage("Please wait...");
builder.SetCancelable(false);
alert = builder.Create();
alert.Show();
} else {
if (alert != null)
if (alert.IsShowing)
{
alert.Dismiss();
alert.Dispose();
}
}
});
}
async void LoginToFacebook()
{
var auth = new OAuth2Authenticator(
clientId: "809804315805408",
scope: "user_about_me",
authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html")
);
auth.AllowCancel = false;
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += LoginComplete;
var intent = auth.GetUI(this);
StartActivity(intent);
}
public async void LoginComplete(object sender, AuthenticatorCompletedEventArgs e)
{
string id = "";
string name = "";
JsonValue obj;
if (!e.IsAuthenticated)
{
var builder = new AlertDialog.Builder(this);
builder.SetMessage("Not Authenticated");
builder.SetPositiveButton("Ok", (o, c) => { });
builder.Create().Show();
return;
}
else {
DisplayLoadingMessage(false);
AccountStore.Create(this) .Save(e.Account, "Facebook");
// Now that we're logged in, make a OAuth2 request to get the user's info.
var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me"), null, e.Account);
await request.GetResponseAsync().ContinueWith(t =>
{
var builder2 = new AlertDialog.Builder(this);
if (t.IsFaulted)
{
builder2.SetTitle("Error");
builder2.SetMessage(t.Exception.Flatten().InnerException.ToString());
builder2.Show();
}
else if (t.IsCanceled)
{
builder2.SetTitle("Task Canceled");
builder2.Show();
}
else {
obj = JsonValue.Parse(t.Result.GetResponseText());
id = obj["id"];
name = obj["name"];
}
builder.SetPositiveButton("Ok", (o, c) => { });
builder.Create();
}, UIScheduler);
var accessToken = e.Account.Properties["access_token"];
var expiresIn = Convert.ToDouble(e.Account.Properties["expires_in"]);
var expiryDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn);
var user = await ParseFacebookUtils.LogInAsync(id, accessToken, expiryDate);
try
{
user.Add("Name", name);
}
catch (Exception ex)
{
Console.WriteLine("LoginFragment.cs | LoginComplete() :: user.Add (\"Name\",name); :: " + ex.Message);
}
var webClient = new WebClient();
//var httpClient = new HttpClient(new NativeMessageHandler());
var url = new Uri("http://graph.facebook.com/" + id + "/picture?type=small");
application.currentUserImageUrl = url.ToString();
application.currentUserName = name;
byte[] bytes = null;
//bytes = await httpClient.GetByteArrayAsync(url);
bytes = await webClient.DownloadDataTaskAsync(url);
ParseFile saveImageFile = new ParseFile("profileImage.jpg", bytes);
try
{
user.Add("profile_pic", saveImageFile);
}
catch (Exception ex)
{
Console.WriteLine("LoginFragment.cs | LoginComplete() :: user.Add (\"profile_pic\",saveImageFile); :: " + ex.Message);
}
application.currentUser = user;
await user.SaveAsync();
DisplayLoadingMessage(true);
ChangeScreen();
}
}
这段代码的问题是:
- 登录后,我收到 成功 消息(一个简单的
白页上的成功消息)必须来自 facebook 和
显然我不想显示在用户身上。
- 虽然
LoginCompete 代码是 运行 应用程序在后台运行,用户看不到任何内容,就像应用程序关闭后
登录再次打开。我尝试显示一个 AlertDialog
函数 DisplayNoConnectivityMessage 但未显示
在用户中任何我不知道的方式。
在 Parse 上使用 Facebook 登录的最简单方法是官方 Parse SDK 结合官方 Facebook Android SDK 来处理单点登录场景。
只需一些小步骤即可达到预期结果:
按照这个小指南为 Facebook SDK 设置您的应用程序:https://components.xamarin.com/gettingstarted/facebookandroid
设置 Parse SDK
public App()
{
// App.xaml initialization
ParseClient.Initialize("Your Application ID", "Your .NET Key");
ParseFacebookUtils.Initialize("Your Facebook App Id");
// Other initialization
}
将 FB 登录按钮添加到您的视图。
<com.facebook.login.widget.LoginButton
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp" />
获取回调并使用令牌通过 Parse 登录用户。
public class MainActivity : Activity, IFacebookCallback
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
// SetContentView (Resource.Layout.Main);
var callbackManager = CallbackManagerFactory.Create();
var loginButton = FindViewById<LoginButton>(Resource.Id.login_button);
loginButton.RegisterCallback(callbackManager, this);
}
#region IFacebookCallback
public void OnCancel()
{
// Handle Cancel
}
public void OnError(FacebookException error)
{
// Handle Error
}
public async void OnSuccess(Object result)
{
// We know that this is a LoginResult
var loginResult = (LoginResult) result;
// Convert Java.Util.Date to DateTime
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var expireDate = epoch.AddMilliseconds(loginResult.AccessToken.Expires.Time);
// FB User AccessToken
var accessToken = loginResult.AccessToken.Token;
ParseUser user = await ParseFacebookUtils.LogInAsync("Your Facebook App Id", accessToken, expireDate);
}
#endregion
...
}
(可选)与 Facebook SDK 和 ParseUser 交互
// You can simply pass the acquired AccessToken to the GraphRequest
var parameters = new Bundle();
parameters.PutString("fields", "id,email,gender,cover,picture.type(small)");
var request = new GraphRequest(loginResult.AccessToken, "me", parameters, HttpMethod.Get);
// Execute request and Handle response (See FB Android SDK Guide)
// to get image as byte[] from GraphResponse
byte[] data;
// Store the image into the ParseUser
user["image"] = new ParseFile("image.jpg", data);
Instead of using the GraphRequest you can always fallback to the HttpClient
/ WebClient and pass the AccessToken as URL parameter. Docs
额外
这里是官方文档的link:http://parseplatform.github.io/docs/dotnet/guide/#facebook-users
从 Nuget 中选择 SDK:https://www.nuget.org/packages/Xamarin.Facebook.Android/
Xamarin Facebook Android SDK 的工作方式类似于 Java SDK,因此该文档也值得一看:https://developers.facebook.com/docs/facebook-login/android#addbutton
我的问题终于是:
通过在 facebook 开发人员仪表板中禁用 facebook 登录应用程序设置的安全浏览,我能够获得成功消息的肋骨。
将 Activity 设置为“NoHistory = true”,会使社交登录出现问题,导致社交平台对 Activity 未按应有的方式进行跟踪。这也是没有显示 AlertDialog 的问题(我永远不会猜到)。
但是 @paul-reichelt 的回答是本机 facebook 登录的最佳方法。
我正在尝试为 Xamarin.Android 创建一个登录系统,以便在 Parse 服务器上使用。我想用 Facebook 登录用户并保存他的真实姓名和他的小用户照片。 我当前显示登录系统的代码是这样的:
using Xamarin.Auth;
loginFacebookButton.Click += (sender, e) =>
{
if (CrossConnectivity.Current.IsConnected)
LoginToFacebook();
else
{
DisplayNoConnectivityMessage();
}
};
loginTwitterButton.Click += (sender, e) =>
{
LoginToTwitter();
};
}
void DisplayNoConnectivityMessage()
{
AlertDialog.Builder alert2 = new AlertDialog.Builder(this);
alert2.SetTitle("Network error");
alert2.SetMessage("Connection with the Internet is required. Please check your connectivity and try again.");
alert2.Show();
}
void DisplayLoadingMessage(bool Dismiss)
{
RunOnUiThread(() =>
{
if (!Dismiss)
{
builder = new AlertDialog.Builder(this);
builder.SetTitle("Signing in");
builder.SetMessage("Please wait...");
builder.SetCancelable(false);
alert = builder.Create();
alert.Show();
} else {
if (alert != null)
if (alert.IsShowing)
{
alert.Dismiss();
alert.Dispose();
}
}
});
}
async void LoginToFacebook()
{
var auth = new OAuth2Authenticator(
clientId: "809804315805408",
scope: "user_about_me",
authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html")
);
auth.AllowCancel = false;
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += LoginComplete;
var intent = auth.GetUI(this);
StartActivity(intent);
}
public async void LoginComplete(object sender, AuthenticatorCompletedEventArgs e)
{
string id = "";
string name = "";
JsonValue obj;
if (!e.IsAuthenticated)
{
var builder = new AlertDialog.Builder(this);
builder.SetMessage("Not Authenticated");
builder.SetPositiveButton("Ok", (o, c) => { });
builder.Create().Show();
return;
}
else {
DisplayLoadingMessage(false);
AccountStore.Create(this) .Save(e.Account, "Facebook");
// Now that we're logged in, make a OAuth2 request to get the user's info.
var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me"), null, e.Account);
await request.GetResponseAsync().ContinueWith(t =>
{
var builder2 = new AlertDialog.Builder(this);
if (t.IsFaulted)
{
builder2.SetTitle("Error");
builder2.SetMessage(t.Exception.Flatten().InnerException.ToString());
builder2.Show();
}
else if (t.IsCanceled)
{
builder2.SetTitle("Task Canceled");
builder2.Show();
}
else {
obj = JsonValue.Parse(t.Result.GetResponseText());
id = obj["id"];
name = obj["name"];
}
builder.SetPositiveButton("Ok", (o, c) => { });
builder.Create();
}, UIScheduler);
var accessToken = e.Account.Properties["access_token"];
var expiresIn = Convert.ToDouble(e.Account.Properties["expires_in"]);
var expiryDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn);
var user = await ParseFacebookUtils.LogInAsync(id, accessToken, expiryDate);
try
{
user.Add("Name", name);
}
catch (Exception ex)
{
Console.WriteLine("LoginFragment.cs | LoginComplete() :: user.Add (\"Name\",name); :: " + ex.Message);
}
var webClient = new WebClient();
//var httpClient = new HttpClient(new NativeMessageHandler());
var url = new Uri("http://graph.facebook.com/" + id + "/picture?type=small");
application.currentUserImageUrl = url.ToString();
application.currentUserName = name;
byte[] bytes = null;
//bytes = await httpClient.GetByteArrayAsync(url);
bytes = await webClient.DownloadDataTaskAsync(url);
ParseFile saveImageFile = new ParseFile("profileImage.jpg", bytes);
try
{
user.Add("profile_pic", saveImageFile);
}
catch (Exception ex)
{
Console.WriteLine("LoginFragment.cs | LoginComplete() :: user.Add (\"profile_pic\",saveImageFile); :: " + ex.Message);
}
application.currentUser = user;
await user.SaveAsync();
DisplayLoadingMessage(true);
ChangeScreen();
}
}
这段代码的问题是:
- 登录后,我收到 成功 消息(一个简单的 白页上的成功消息)必须来自 facebook 和 显然我不想显示在用户身上。
- 虽然 LoginCompete 代码是 运行 应用程序在后台运行,用户看不到任何内容,就像应用程序关闭后 登录再次打开。我尝试显示一个 AlertDialog 函数 DisplayNoConnectivityMessage 但未显示 在用户中任何我不知道的方式。
在 Parse 上使用 Facebook 登录的最简单方法是官方 Parse SDK 结合官方 Facebook Android SDK 来处理单点登录场景。
只需一些小步骤即可达到预期结果:
按照这个小指南为 Facebook SDK 设置您的应用程序:https://components.xamarin.com/gettingstarted/facebookandroid
设置 Parse SDK
public App() { // App.xaml initialization ParseClient.Initialize("Your Application ID", "Your .NET Key"); ParseFacebookUtils.Initialize("Your Facebook App Id"); // Other initialization }
将 FB 登录按钮添加到您的视图。
<com.facebook.login.widget.LoginButton android:id="@+id/login_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="30dp" android:layout_marginBottom="30dp" />
获取回调并使用令牌通过 Parse 登录用户。
public class MainActivity : Activity, IFacebookCallback { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource // SetContentView (Resource.Layout.Main); var callbackManager = CallbackManagerFactory.Create(); var loginButton = FindViewById<LoginButton>(Resource.Id.login_button); loginButton.RegisterCallback(callbackManager, this); } #region IFacebookCallback public void OnCancel() { // Handle Cancel } public void OnError(FacebookException error) { // Handle Error } public async void OnSuccess(Object result) { // We know that this is a LoginResult var loginResult = (LoginResult) result; // Convert Java.Util.Date to DateTime var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var expireDate = epoch.AddMilliseconds(loginResult.AccessToken.Expires.Time); // FB User AccessToken var accessToken = loginResult.AccessToken.Token; ParseUser user = await ParseFacebookUtils.LogInAsync("Your Facebook App Id", accessToken, expireDate); } #endregion ... }
(可选)与 Facebook SDK 和 ParseUser 交互
// You can simply pass the acquired AccessToken to the GraphRequest var parameters = new Bundle(); parameters.PutString("fields", "id,email,gender,cover,picture.type(small)"); var request = new GraphRequest(loginResult.AccessToken, "me", parameters, HttpMethod.Get); // Execute request and Handle response (See FB Android SDK Guide) // to get image as byte[] from GraphResponse byte[] data; // Store the image into the ParseUser user["image"] = new ParseFile("image.jpg", data);
Instead of using the GraphRequest you can always fallback to the
HttpClient
/ WebClient and pass the AccessToken as URL parameter. Docs
额外
这里是官方文档的link:http://parseplatform.github.io/docs/dotnet/guide/#facebook-users
从 Nuget 中选择 SDK:https://www.nuget.org/packages/Xamarin.Facebook.Android/
Xamarin Facebook Android SDK 的工作方式类似于 Java SDK,因此该文档也值得一看:https://developers.facebook.com/docs/facebook-login/android#addbutton
我的问题终于是:
通过在 facebook 开发人员仪表板中禁用 facebook 登录应用程序设置的安全浏览,我能够获得成功消息的肋骨。
将 Activity 设置为“NoHistory = true”,会使社交登录出现问题,导致社交平台对 Activity 未按应有的方式进行跟踪。这也是没有显示 AlertDialog 的问题(我永远不会猜到)。
但是 @paul-reichelt 的回答是本机 facebook 登录的最佳方法。