NewMeRequest in the Facebook Android API in C# - c#

I've been trying to do a Request.NewMeRequest with the Facebook API for Android in Xamarin Studio through the following code:
Request.NewMeRequest (currentSession, new Request.IGraphUserCallback() {
override void OnCompleted(IGraphUser user, Response Response){
Console.WriteLine(user.FirstName);
}
}).ExecuteAsync ();
But Xamarin Studio gives some errors, so I think i am not doing this the right way in C#. Does someone have some sample code of how to do this or some exaplanation of why this isn't working?
Thanks in advance!
EDIT:
Thanks #Guilherme for the help, it doesn't return any errors now, but i've run into the following problem:
I've changed the code to your answer like this:
public class MainActivity : Activity, ILocationListener, Request.IGraphUserCallback
{
...
Session currentSession = Session.ActiveSession;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
...
Console.WriteLine ("current session: " + currentSession.AccessToken);
Request.NewMeRequest (currentSession, this).ExecuteAsync();
}
public void OnCompleted (IGraphUser user, Response response)
{
Console.WriteLine (user.Username);
}
...
}
But now it doesn't retun the username of the current logged in user. The session is not the problem because it is correct.

For sure this will not work on c#, because it does not support Anonymous class
Make your class implement the IGraphUserCallback and pass it as a parameter and then:
Request.NewMeRequest (currentSession, this).ExecuteAsync ();

Related

Xamarin AndroidX.Preferences - Cannot convert from 'SettingsFragment' to 'Android.Support.V4.App.Fragment'

I'm trying to update the settings/preferences screen of my Xamarin Android app, which was using the PreferenceManager class. Since I'm targeting Android 10, this class is deprecated and I'd like to use the AndroidX.Preference library instead.
I followed Google's guide for making a settings screen with AndroidX. Here's the code I'm using
namespace SmartLyrics
{
[Activity(Label = "Settings", ConfigurationChanges = Android.Content.PM.ConfigChanges.ScreenSize | Android.Content.PM.ConfigChanges.Orientation, ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]
public class SettingsFragment : PreferenceFragmentCompat
{
public override void OnCreatePreferences(Bundle savedInstanceState, string rootKey)
{
AddPreferencesFromResource(Resource.Xml.perfs);
}
}
public class SettingsActivity : AppCompatActivity
{
protected override async void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.main_settings);
SupportFragmentManager
.BeginTransaction()
.Replace(Resource.Id.settingsContainer, new SettingsFragment()) //<--error here
.Commit();
}
}
}
I'm getting the error Cannot convert from 'SmartLyrics.SettingsFragment' to 'Android.Support.V4.App.Fragment'. I looked around online and couldn't find a workaround or anything about this error. I'd really like to use the AndroidX library to prevent any problems with unsupported code later on.
Any help is appreciated. Thanks!
Check which package AppCompatActivity refers to ?
If it:
using Android.Support.V7.App;
change it to :
using AndroidX.AppCompat.App;

Facebook Audience Network in XAMARIN. No docs and error messages like "do not retry" and "internal error"

I am working with Xamarin and C# and all the docs refer to Java (as usually.)
This isn't much of a problem since it is pretty easy to convert, however this time I am not able to go anywhere.
What I did so far:
Remove Google from Project;
Add Facebook Ads SDK (newest version);
Add Facebook Audience Network account;
Get my app approved;
Put the AdID into my app.
Write a bit of code that should work (according to the docs):
private InterstitialAd mInterstitialAd;
private void LoadInterstitialAd()
{
mInterstitialAd = new InterstitialAd(this, "YOUR_PLACEMENT_ID");
mInterstitialAd.SetAdListener(new AdListener());
mInterstitialAd.LoadAd();
}
private void ButtonClick()
{
mInterstitialAd.Show();
}
public class AdListener : Activity, IInterstitialAdListener
{
public void Dispose()
{
throw new NotImplementedException();
}
public void OnAdClicked(IAd p0)
{
throw new NotImplementedException();
}
public void OnAdLoaded(IAd p0)
{
throw new NotImplementedException();
}
public void OnError(IAd p0, AdError p1)
{
Log.Debug("y", p1.ErrorMessage);
}
public void OnInterstitialDismissed(IAd p0)
{
throw new NotImplementedException();
}
public void OnInterstitialDisplayed(IAd p0)
{
throw new NotImplementedException();
}
}
So, as you can see, the code is pretty simple. But upon requesting my ad (yes, I let it load for a while before clicking Show(), my adListener class becomes active. To be more precise, before even clicking on show (but upon load() it throws the OnError() function and within the error message it just says (and I am not kidding here:)
do not retry
Do not retry what? This is my first try!
Upon now clicking a button to actually show the ad I get (and again, I am not kidding):
Internal Error
And this is it. All the info I get. Upon Googling those "error codes" I get nothing. No one else seems to have this issue.
I have also not found a way to test with test Interstitials, as I could with Admob.
Has anyone ever made any experience in this field? Is it my code? Do I need another NuGet package? Or do I need to set something else in my console?

FCM and xamarin.android - broadcast receiver doesn't work

I have problem with broadcast receiver in xamarin.android. Can't get it to work.
I have notification in my app working and I want to change some things in my app after I get notification (e.g. Toast message or change icon of a button) But it doesn't work. I don't know what am I doing wrong and I can't find solution because all the topics are Java related. I need something, event or broadcastreceiver to fire when user gets notification and then I want to do some stuff in my MainActivity.
So, this is the code.
BroadcastReceiver class:
[BroadcastReceiver(Enabled = true, Exported = false)]
public class MyMessageReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
bool messageReceived = intent.GetBooleanExtra("messageReceived", false);
}
}
OnMessageReceived method:
{
base.OnMessageReceived(message);
SendNotification(message.GetNotification().Body);
LocalBroadcastManager broadcaster = LocalBroadcastManager.GetInstance(this);
Intent intent = new Intent("message");
intent.PutExtra("messageReceived", true);
broadcaster.SendBroadcast(intent);
}
And OnResume and OnPause methods:
protected override void OnResume()
{
base.OnResume();
LocalBroadcastManager.GetInstance(this).RegisterReceiver(myReceiver, new IntentFilter("message"));
RegisterReceiver(myReceiver, new IntentFilter("message"));
}
protected override void OnPause()
{
base.OnPause();
LocalBroadcastManager.GetInstance(this).UnregisterReceiver(myReceiver);
}
I don't know how to receive that info for example in my OnCreate method in MainActivity? I tried with
messageReceived = Intent.GetBooleanExtra("messageReceived", false);
if (messageReceived)
{
Toast.MakeText(this, "new notification", ToastLength.Long).Show();
}
But that doesn't work, messageReceived is null.
I know it is a bit too late but better late than never :
After analysing the firebase messaging I have done a suitable workaround for this purpose :
When your application is in the background the handle intent method is called by default on receiving push notification :
public override void HandleIntent(Intent p0)
{
base.HandleIntent(intent);
//Your code to know that you received a notification (backgrounnd)
// Use shared preference for this
}
Don't know how to use shared preferences check this.
For more information on how handle intent works check my answer out here.
When the application is in the foreground you can simply use on message received method as such :
public override void OnMessageReceived(Context context, Intent intent)
{
//Your code to know that you received a notification (backgrounnd)
// Use shared preference for this
}
Then, wherever you need to use this you can get a flag or count or whatever using shared preferences.
In case of any queries revert!

Xamarin.GooglePlayServices.Ads: how to add a bundle to the ad request

Considering I have an AdView in a Xamarin.Android project:
private AdView _bannerAd;
I usually initialize it like this:
_bannerAd = new AdView(this)
{
AdSize = AdSize.SmartBanner,
AdUnitId = adUnitId,
Visibility = ViewStates.Visible
};
Then, when I load the banner, I have to build the request. In this case I'd like to add an extra bundle, but when I have to call requestbuilder.AddCustomEventExtrasBundle, I don't know what to put as the first parameter.
var requestbuilder = new AdRequest.Builder();
var extras = new Bundle();
extras.PutString("npa", "1");
requestbuilder.AddCustomEventExtrasBundle(***, extras);
_bannerAd.LoadAd(requestbuilder.Build())
By reading the method definition, I really don't understand what could be an "adapter class".
[Register("addCustomEventExtrasBundle", "(Ljava/lang/Class;Landroid/os/Bundle;)Lcom/google/android/gms/ads/AdRequest$Builder;", "")]
public Builder AddCustomEventExtrasBundle(Class adapterClass, Bundle customEventExtras);
You need to pass the Java Class (via Java.Lang.Class.FromType) of your custom event (ICustomEventBanner).
In my case, I have one called SushiHangoverTextEventBanner that is registered with AdMob.
You need to implement ICustomEventBanner, assumably this is a stand alone object (in my case it is) as AdMob will instance it, inherit it from Java.Lang.Object so Xamarin will create the ACW (JNI/Java wrapper) for it.
public class SushiHangoverTextEventBanner : Java.Lang.Object, ICustomEventBanner
{
SushiHangoverTextAdView customAdView;
public void OnDestroy()
{
customAdView?.Dispose();
}
public void OnPause()
{
~~~
}
public void OnResume()
{
~~~
}
public void RequestBannerAd(Context context, ICustomEventBannerListener listener, string serverParameter, AdSize size, IMediationAdRequest mediationAdRequest, Bundle customEventExtras)
{
customAdView = new SushiHangoverTextAdView(context);
~~~
}
}
I also have a custom ad (SushiHangoverAdView based on a TextView) that is used within that ICustomEventBanner implementation.
Once you register it and implement the AdMob callbacks, you can just pass it to your AdRequest.Builder:
using (var requestbuilder = new AdRequest.Builder())
{
var extras = new Bundle();
extras.PutString("npa", "1");
requestbuilder.AddCustomEventExtrasBundle(Java.Lang.Class.FromType(typeof(SushiHangoverTextEventBanner)), extras);
}
I help recommend going through the Admob custom event example:
https://developers.google.com/admob/android/custom-events
It is expecting a class that extends from CustomEvent, per the Documentation
public AdRequest.Builder addCustomEventExtrasBundle (Class<? extends
CustomEvent> adapterClass, Bundle customEventExtras)
Here is a great tutorial on getting started with custom events, directly from Google, where they go over using the CustomEventBanner. It is in Java, but should be easy enough to port to C#

Show alert on press back button

I writing android app on Xamarin(C#)
I need to Show alert with "Yes" and "No" variantes when I tap back button on Activity.
How can I realize this?
I know how to show alert. How I can make it when i press back button
try this , add to your activity
#Override
public void onBackPressed() {
AlertDialog.Builder builder =
new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
builder.setTitle(getResources().getString(R.string.app_name));
builder.setMessage("" + Message);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//write your code
}
});
builder.setNegativeButton("No", null);
builder.setCancelable(false);
builder.show();
}
Xamarin provides wrappers to the native Android Activity classes. So you probably have a MainActivity and maybe other Activity classes in your Xamarin Android project.
In these classes you can override the OnBackPressed method inherited from FormsApplicationActivity and then create and show your Alert from there.
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
public override void OnBackPressed()
{
// show Alert or pass call on to base.OnBackPressed()
}
}
Since Xamarin Forms 1.3.0 pre3, there is a new method:
protected bool OnBackButtonPressed();
You need to override this on your page.
protected override bool OnBackButtonPressed()
{
// If you want to stop the back button and show alert
return true;
// If you want to continue going back
base.OnBackButtonPressed();
return false;
}
Thanks to Xamarin Forums. Refer this link for more info.

Categories

Resources