How to handle SecondaryTile click event in windows apps - c#

Present i am working with SecondaryTile, i want to fire an event when tile is clicked, is there any possibility for that please help me..
Here is my code,
SecondaryTile initialData = new SecondaryTile();
initialData = new SecondaryTile(
ShowID,
ojsShow.Title,
"NoArguments",
new Uri("ms-appx:///Images/" + ojsShow.TileImage),
TileSize.Square150x150);
initialData.VisualElements.ShowNameOnSquare150x150Logo = true;
await initialData.RequestCreateAsync();

In app.xaml you can find whether clicked title or not
protected override void OnActivated(IActivatedEventArgs args)
{
var data= e.TileId;
if(data=="App")
{
//code for normal app start...
}
else
{
//code for tile click..
//you can see the tile in data parameter
}
}

The only thing you can do is to open the app and send some parameters to take action/ handle it..
for the SecondaryTile, I believe you can set the page/ parameters by your new instance ..
for the handling process, you can override the OnActivated event and check the parameters and the page:
protected override void OnActivated(IActivatedEventArgs args)

Related

Handler fires to early

I have an device with an integrated bixolon printer in it. I want to create an app to print on the printer. My OnCreate method looks as follow:
protected override void OnCreate(Bundle bundle){
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
printer = new BixolonPrinter(this, new MyHandler(), Looper.MainLooper);
printer.FindUsbPrinters();
//button connect
Button button = FindViewById<Button>(Resource.Id.buttonConnect);
button.Click += delegate {
printer.ConnectUsb();//in the brackets I would need the value of the Handler back once it is available
}; }
My Handler is as follow:
private class MyHandler : Handler
{
public override void HandleMessage(Message msg)
{
switch (msg.What)
{
case BixolonPrinter.MessageUsbDeviceSet:
Console.WriteLine("U S B device::: " + msg.Obj);
//can not return the msg.Obj back to the button event
break;
}
}
}
The problem is the once the instance of the BixolonPrinter is created it immediately fires the Handler. There is no way to bring back the result of the Handler to the button event. To make that problem a litte bit more complicated, the BixolonPrinter is a Java .jar file. So how can I get the result back to the event button?
When you use MainLooper, everything will be executed on main thread. Create HandlerThread for interaction instead. To postpone execution, use Handler.postDelayed() method, or, what is better, use RxJava library

Adding code to a Toast Notification UWP

I've a Toast notification that execute from outside the project (In a background one). Here you have:
private void SendMessage(string title, string text)
{
ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
XmlNodeList textElements = toastXml.GetElementsByTagName("text");
textElements[0].AppendChild(toastXml.CreateTextNode(title));
textElements[1].AppendChild(toastXml.CreateTextNode(text));
ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
}
My problem is when I try to execute code when the user click the toast, I want to execute part of the code form the Main project. Is there a way to do this?
Thanks
In this article you can find section Handling activation from a toast notification
Shortly:
after toast clicked OnActivated event invoked and you can check arguments.
Using new toast template:
protected override void OnActivated(IActivatedEventArgs e)
{
if (e is ToastNotificationActivatedEventArgs)
{
}
}
and using old template (like I think you have):
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
string launchString = args.Arguments
// ....
}

Error Unable to start activity: java.lang.illegalStateException: Foreground dispatch can only be enabled when your activity is resumed

I am working with NFC using Xamarin Android.
My scenario is to read nfc tag. I have implemented the following, which works using a button. But I would like it so the user doesn't have to press Scan button to scan nfc tag.
OnCreate
scanButton.Click += (object sender, EventArfs e) =>{
var view = (View)sender;
if(view == Resource.Id.scan){
var mesgEl = FindViewById<TextView>(Resource.Id.msg);
msgEl.Text = "Ready to Scan. Touch and hold the tag against the phone.";
InitNfcScanner();
}
}
InitNfcScanner
private void InitialiseNfcScanner(){
// Create an intent filter for when an NFC tag is discovered. When
// the NFC tag is discovered.
var tagDetected = new IntentFilter(NfcAdapter.ActionTagDiscovered);
var filters = new[] { tagDetected };
// When an NFC tag is detected, Android will use the PendingIntent to come back to this activity.
// The OnNewIntent method will invoked by Android.
var intent = new Intent(this, GetType()).AddFlags(ActivityFlags.SingleTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);
if (_nfcAdapter == null) {
var alert = new AlertDialog.Builder (this).Create ();
alert.SetMessage ("NFC is not supported on this device.");
alert.SetTitle ("NFC Unavailable");
alert.SetButton ("OK", delegate {
// display message here
});
alert.Show ();
} else {
_nfcAdapter.EnableForegroundDispatch (this, pendingIntent, filters, null);
}
}
OnNewIntent
protected override void OnNewIntent(Intent intent)
{
// onResume gets called after this to handle the intent
Intent = intent;
}
OnResume()
protected override void OnResume ()
{
base.OnResume ();
InitialiseNfcScanner();
if (NfcAdapter.ActionTagDiscovered == Intent.Action) {
// do stuff
}
}
But if i remove the button delegate from OnCreate, and call InitNfcScanner(), I get the error Unable to start activity: java.lang.illegalStateException: Foreground dispatch can only be enabled when your activity is resumed.
I want the user to be able to just scan the asset, once the activity is loaded. What would be a good solution to achieve this?
Can you please add the button delegate in OnCreate and Just call button.PerformClick() in OnResume.
I have now resolved this issue.
The objective was to be able to read nfc tag without pressing Button.
So i removed the button from the view, and I removed the ScanButton delegate from OnCreate.
As I was calling InitialiseNfcScanner inside the OnResume(), this is all i needed, because _nfcAdapter.EnableForegroundDispatch (this, pendingIntent, filters, null);
would create a pendingIntent and looking at the Android Guidelines for this, the ForgroundDispatch can only been called from the OnResume().
See http://developer.android.com/reference/android/nfc/NfcAdapter.html
enableForegroundDispatch

Xamarin C# - Android - Prevent an AlertDialog from closing on PositiveButton click

I'm new to Xamarin and I don't know how to do the following in c#. I want to prevent an alertdialog from closing when clicking on the Positive/Negative buttons. I need to do some validation on the input first. If the input is correct, the dialog can close, else I will show a message with instructions. Basically, I have the following code:
private void CreateAddProjectDialog() {
//some code
var alert = new AlertDialog.Builder (this);
alert.SetTitle ("Create new project");
alert.SetView (layoutProperties);
alert.SetCancelable (false);
alert.SetPositiveButton("Create", HandlePositiveButtonClick);
alert.SetNegativeButton("Cancel", HandelNegativeButtonClick);
}
private void HandlePositiveButtonClick (object sender, EventArgs e) {
//Do some validation here and return false (prevent closing of dialog) if invalid, else close....
}
Now, I red the following post on StackOverflow: How to prevent a dialog from closing when a button is clicked
I think the code below (taken from the thread) has the solution, but I don't know how to rewrite my c# code to implement the Java:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Test for preventing dialog close");
builder.setPositiveButton("Test",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//Do nothing here because we override this button later to change the close behaviour.
//However, we still need this because on older versions of Android unless we
//pass a handler the button doesn't get instantiated
}
});
AlertDialog dialog = builder.create();
dialog.show();
//Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Boolean wantToCloseDialog = false;
//Do stuff, possibly set wantToCloseDialog to true then...
if(wantToCloseDialog)
dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
How to code this in c#? Especially the override part in the setPositiveButton area...
This requires to think a bit outside the box. You will have to manipulate the AlertDialog object directly:
// Build the dialog.
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Click me!");
// Create empty event handlers, we will override them manually instead of letting the builder handling the clicks.
builder.SetPositiveButton("Yes", (EventHandler<DialogClickEventArgs>)null);
builder.SetNegativeButton("No", (EventHandler<DialogClickEventArgs>)null);
var dialog = builder.Create();
// Show the dialog. This is important to do before accessing the buttons.
dialog.Show();
// Get the buttons.
var yesBtn = dialog.GetButton((int)DialogButtonType.Positive);
var noBtn = dialog.GetButton((int)DialogButtonType.Negative);
// Assign our handlers.
yesBtn.Click += (sender, args) =>
{
// Don't dismiss dialog.
Console.WriteLine("I am here to stay!");
};
noBtn.Click += (sender, args) =>
{
// Dismiss dialog.
Console.WriteLine("I will dismiss now!");
dialog.Dismiss();
};

How to Navigate to CameraCaptureTask from LensPicker

I have created a small sample Lens application, and I would like to be able to directly navigate to the CameraCaptureTask when the Lens icon is clicked in the default camera application. In my application I am already calling the CameraCaptureTask within a button click event during normal app operations. How might I set this up to work as well from the LensPicker option?
I have been referencing
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj662936(v=vs.105).aspx
LensExampleUriMapper.cs
private string tempUri;
public override Uri MapUri(Uri uri)
{
tempUri = uri.ToString();
// Look for a URI from the lens picker.
if (tempUri.Contains("ViewfinderLaunch"))
{
// Launch as a lens, launch viewfinder screen.
return new Uri("/MainPage.xaml", UriKind.Relative);
}
// Otherwise perform normal launch.
return uri;
}
I was thinking of passing a QueryString value in return new Uri("/MainPage.xaml", UriKind.Relative); so that in my MainPage OnNavigatedTo event I could check that QueryString value and call the CameraCaptureTask, and then just route the result to the already existing event handler I have created (which displays the resulting image in MainPage). For some reason I am getting a debugging error when trying to create the QueryString to pass, and I am unsure of why?
EDIT** No longer getting error, but an infinite loop occurs when calling CameraCaptureTask. Why?
LensExampleUriMapper.cs
private string tempUri;
public override Uri MapUri(Uri uri)
{
tempUri = uri.ToString();
// Look for a URI from the lens picker.
if (tempUri.Contains("ViewfinderLaunch"))
{
// Launch as a lens, launch viewfinder screen.
return new Uri("/MainPage.xaml?fromLensPicker=" + "fromLensPicker", UriKind.Relative);
}
// Otherwise perform normal launch.
return uri;
}
MainPage.xaml.cs
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string fromLensPicker = null;
if (NavigationContext.QueryString.TryGetValue("fromLensPicker", out fromLensPicker))
{
if (fromLensPicker == "fromLensPicker")
{
newButton_Click(null, null); //click event that calls CameraCaptureTask
fromLensPicker = null; //Temporarily nullifies value until MainPage is OnNavigatedTo after CameraCaptureTask completes
}
}
}
I believe that when CameraCaptureTask is called, the application is tombstoned and then resumed on MainPage, in which the QueryString value fromLensPicker == "fromLensPicker" and the entire cycle starts over again, repetitively. How might I solve this?
Use NavigationMode property in MainPage. I think you can't clear QueryString. But you can check how navigation to your page occured to know if its returning from CameraCaptureTask
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if(e.NavigationMode == NavigationMode.New)
// continue further
}
or
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if(e.NavigationMode == NavigationMode.Back)
return;
// else continue further
}
Instead of making fromLensPicker = null in MainPage.xaml.cs, I now have NavigationContext.QueryString.Remove("fromLensPicker") as referenced from WP7 Navigation with parameters
MainPage.xaml.cs
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string fromLensPicker = null;
if (NavigationContext.QueryString.TryGetValue("fromLensPicker", out fromLensPicker))
{
if (fromLensPicker == "fromLensPicker")
{
NavigationContext.QueryString.Remove("fromLensPicker");
//Perform Action
}
}
}

Categories

Resources