Show alert on press back button - c#

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.

Related

Button onClick not binding to method in Activity

So I'm trying to test out adding a click event to a Button in an .axml file that my main Activity uses. I've gone through a lot of other threads and I have followed the code provided as best I can. However I am getting the following exception when I run my code.
Java.Lang.IllegalStateException: Could not find method testClick(View)
in a parent or ancestor Context for android:onClick attribute
defined on view class android.widget.Button with id 'login'
In Main.axml
<Button
android:text="Login"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:onClick="testClick"
android:id="#+id/login" />
In Main.cs
public class Main : Activity
{
protected override void OnCreate(Android.OS.Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
}
public void testClick(View view)
{
//Show alert saying clicked...
}
}
Am I missing some configuration, or include to get this to work perhaps?
You can always do this :
Button button1 = FindViewById<Button>(Resource.Id. login);
button1.Click += delegate => {
//Show alert saying clicked...
};
If you don't want to use this way, you should Export your method first as follow take a look on this answer:
[Export("testClick")]
public void testClick(View view)
{
//Show alert saying clicked...
}
If those didn't work add a reference to Mono.Android.Export.dll and then in your Activity put this
[Java.Interop.Export("testClick")]
public void testClick(View view)
{
//Show alert saying clicked...
}
Please try after inheriting interface View.IOnclicklistener :
public class Main: AppcompatActivity, View.IonClickListener
It help to implement the onclick method of the interface like you given:
public void testClick(View view)
{
//Show alert saying clicked...
}

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!

WebView in background won't load webpages

I want my app to navigate every five minutes to a certain webpage while the display is off. Therefore i created an AlarmReceiver:
[BroadcastReceiver]
public class BackgroundAlarmReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
MainActivity.Current.RunOnUiThread(() =>
{
FMain.WV.LoadUrl("http://127.0.0.1/");
});
}
}
WV is attached to the layout of the fragment 'FMain' and a static parameter of it.
This works fine while the screen is on, but when I turn my screen off and turn it on a few minutes later, most of the times I get to see "Webpage not available, ERR_NAME_NOT_RESOLVED" (but sometimes it loads even while the screen is of).
The webview has DomStorage and JavaScript enabled and a standard WebViewClient:
public class MyWebViewClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, IWebResourceRequest request)
{
view.LoadUrl(request.Url.ToString());
return false;
}
}
It happens, because android system kills your web view. Do you really need to render some page every 5 minutes in background, or you just want to send request?

Xamarin iOS Prism (Unity) - Keyboard Extension

I am trying to build a Xamarin Forms Mobile Application using Prism (Unity) Framework - and add a iOS keyboard extension to the Mobile App.
I added the Keyboard Extension Project and added the reference to the iOS application.
I added a ViewController in the Keyboard Extension Project (which created an XIB file as well) as below:
public partial class ViewController1 : UIViewController
{
public ViewController1() : base("ViewController1", null)
{
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
}
}
When I rebuild and run, and install the keyboard and click on the keyboard icon to switch, the view of the keyboard is not returned.
Here is the code for the App.xaml.cs in main application
public partial class App : PrismApplication
{
public App(IPlatformInitializer initializer = null) : base(initializer)
{
}
protected override void OnInitialized()
{
InitializeComponent();
NavigationService.NavigateAsync("NavigationPage/MainPage?title=Hello%20from%20Xamarin.Forms");
}
protected override void RegisterTypes()
{
Container.RegisterTypeForNavigation<NavigationPage>();
Container.RegisterTypeForNavigation<MainPage>();
}
}
I don't know what's missing...?
I can't find any answers on how to bind the view of the Keyboard by code because I am building this using a Windows PC .. any help would be appreciated.
You have to create an instance of your keyboard view and assign that object to your view controller View property:
public override void ViewDidLoad()
{
base.ViewDidLoad();
//bind view to controller
var viewNib = UINib.FromName("KeyboardView", null);
View = viewNib.Instantiate(this, null)[0] as UIView;
}
Replace "KeyboardView" with name of your .xib file

NewMeRequest in the Facebook Android API in 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 ();

Categories

Resources