Does xamarin.android support DownloadHelper? - xamarin

The download is started by the user clicking on the Download File button. The Xamarin.Android application utilizes a ProgressBar widget to display the download progress.
The button that begins the download has the following asynchronous event handler assigned to it's Click event:
async void StartDownloadHandler(object sender, System.EventArgs e)
{
_progressBar.Progress = 0;
Progress<DownloadBytesProgress> progressReporter = new Progress<DownloadBytesProgress>();
progressReporter.ProgressChanged += (s, args) => _progressBar.Progress = (int)(100 * args.PercentComplete);
Task<int> downloadTask = DownloadHelper.CreateDownloadTask(DownloadHelper.ImageToDownload, progressReporter);
int bytesDownloaded = await downloadTask;
System.Diagnostics.Debug.WriteLine("Downloaded {0} bytes.", bytesDownloaded);
}
In the previous code snippet, the Progress encapsulates a lambda that will update ProgressBar, displaying the percentage of bytes that were downloaded. It is important to realize that Progress will execute in the same SynchronizationContext it which it was instantiated. So, because Progress is created on the UI thread, it will run in the UI thread. It is not necessary to explicitly use RunOnUIThread inside the provided lambda to update the UI.
I dont see DownloadHelper on xamarin.android. I want to create a download method

Related

How to update badge count while app is open?

I am using BottomNavigationBar plugin and it works fine.
My problem is I want to update badge count when notification is received while app is in running mode(i.e. open). I am using Setting Plugin for Xamarin and store count in that. On app initialize it display counts properly. But when my app is open I am changing value of Setting and immediately change the value of badge. How's that can be possible?
Where is several ways to do this.
First, if you are using Xamarin forms then you can use MessagingCenter. It is cross platform Event Bus implementation.
I used Xamarin.Form. Example for sending message
public MainPage()
{
InitializeComponent();
var count = 0;
_button.Clicked += (sender, args) =>
{
MessagingCenter.Send<MainPage, int>(this, "MyMessage", count++);
};
}
Example of reciever
public App()
{
InitializeComponent();
var mp = new MainPage();
MainPage = new MainPage();
MessagingCenter.Subscribe<MainPage, int>(this, "MyMessage", (sender, arg) => {
MainPage.DisplayAlert("MyMessage", $"Hit Count: {arg}", "ok");
});
}
There is more info and examples if you check Link
Second, add event to your settings class, and invoke it in your setter

Geofence is not being triggered in the background in windows phone 8.1

I'm trying to implement geofencing in Windows phone 8.1. First I wanted to create a sample Project to understand how it Works, but i couldnt make it works. What I'm trying to achieve is basically, I'll set the coordinates and close the app by pressing back button and it will trigger a toast notification when the phone is in the area of interest.
I've created a blank Windows phone(silverlight) 8.1 Project(geofence_test_01) and added a Windows RT Component Project(BackgroundTask) into the same solution. Added a reference for BackgroundTask in the geofence_test_01 Project.
ID_CAP_LOCATION is enabled in the app manifest.
MainPage.xaml has only one button to start geofencing.
<Button Name="btnStart" Content="Start" Click="btnStart_Click"/>
In btnSave_Click, I call a method which creates the geofence and registers the background task.
private void btnStart_Click(object sender, RoutedEventArgs e)
{
Init_BackgroundGeofence();
registerBackgroundTask();
}
private async Task Init_BackgroundGeofence()
{
//----------------- Crating Geofence ---------------
var geofenceMonitor = GeofenceMonitor.Current;
var geoId = "building9";
var positionBuilding9 = new BasicGeoposition()
{
Latitude = 47.6397,
Longitude = -122.1289
};
var geofence = new Geofence(geoId, new Geocircle(positionBuilding9, 100),
MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited,
false, TimeSpan.FromSeconds(10));
geofenceMonitor.Geofences.Add(geofence);
}
private async Task registerBackgroundTask()
{
//----------------- Register Background Task ---------------
var backgroundAccessStatus =
await BackgroundExecutionManager.RequestAccessAsync();
var geofenceTaskBuilder = new BackgroundTaskBuilder
{
Name = "GeofenceBackgroundTask",
TaskEntryPoint = "BackgroundTask.GeofenceBackgroundTask"
};
var trigger = new LocationTrigger(LocationTriggerType.Geofence);
geofenceTaskBuilder.SetTrigger(trigger);
var geofenceTask = geofenceTaskBuilder.Register();
}
And finally, in BackgroundTask, I've the following code:
namespace BackgroundTask
{
public sealed class GeofenceBackGroundTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
var geofenceMonitor = GeofenceMonitor.Current;
var geoReports = geofenceMonitor.ReadReports();
var geoId = "building9";
foreach (var geofenceStateChangeReport in geoReports)
{
var id = geofenceStateChangeReport.Geofence.Id;
var newState = geofenceStateChangeReport.NewState;
if (id == geoId && newState == GeofenceState.Entered)
{
//------ Call NotifyUser method when Entered -------
notifyUser();
}
}
}
private void notifyUser()
{
var toastTemplate = ToastTemplateType.ToastText02;
var toastXML = ToastNotificationManager.GetTemplateContent(toastTemplate);
var textElements = toastXML.GetElementsByTagName("text");
textElements[0].AppendChild(toastXML.CreateTextNode("You are in!"));
var toast = new ToastNotification(toastXML);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
}
}
I get no error when building and deploying this in the emulator. I set a breakpoint in the backgroundTask but I've not seen that part of code is called yet. It never hits the breakpoint. I test it by using Additional Tools of the emulator, in Location tab, by clicking somewhere in my geofence area on the map, waiting for a while, but it never hits the breakpoint. Hope somebody can tell me what i am missing here...
I've checked these following links to build this application:
http://www.jayway.com/2014/04/22/windows-phone-8-1-for-developers-geolocation-and-geofencing/
Geofence in the Background Windows Phone 8.1 (WinRT)
Toast notification & Geofence Windows Phone 8.1
http://java.dzone.com/articles/geofencing-windows-phone-81
Thanks
You can download the project here:
https://drive.google.com/file/d/0B8Q_biJCWl4-QndYczR0cjNhNlE/view?usp=sharing
---- Some clues
Thanks to Romasz, I've checked the Lifecycle events and i see "no background tasks" even after registerBackgroundTask() is executed.... Apparently there is something wrong/missing in registerBackgroundTask() method.
I've tried to build my sample (it was easier for me to build a new one) basing on your code and it seems to be working. You can take a look at it at my GitHub.
There are couple of things that may have gone wrong in your case:
remember to add capabilities in WMAppManifest file (IS_CAP_LOCATION) and Package.appxmanifest (Location)
check the names (of namespaces, classes and so on) in BackgroundTask
check if your BackgroundTask project is Windows Runtime Componenet and is added to your main project as a reference
I know you have done some of this things already, but take a look at my sample, try to run it and maybe try to build your own from the very beginning.
Did you add your background task in the Package.appxmanifest under Declarations with the correct supported task types (Namely Location)?

Windows phone 8 Fast Resume when Tombstoned

http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj735579%28v=vs.105%29.aspx
According to the document when I use fast resume in windows phone 8 I can resume my App from main tile.
But when my app is tombstoned ,
for example, mainPage can navigate to ->pageA can naviget to->PageB, I deactived the app from PageA, then the
app is tombstoned, when I click the Tile that navigate to PageB, it's strange that the app back to Page A .
How to fix this problem?
It sounds like you are not saving the application state before it is tombstoned. There are 4 events that are fired for preserving application state:
These are related to completely closing and reopening the application (eg: Phone restart)
Application_Launching
Application_Closing
These are related to tombstoning (task switching)
Application_Activated
Application_Deactivated
It sounds like what you need is the second one relating to activating / deactivating. These methods are placed in the Applications *.cs file and allow you to preserve and reinstate the ViewModel when tombstoning.
This is an example:
private readonly string ModelKey = "Key";
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
PhoneApplicationService.Current.State[ModelKey] = ViewModel;
}
private void Application_Activated(object sender, ActivatedEventArgs e)
{
if (PhoneApplicationService.Current.State.ContainsKey(ModelKey))
{
ViewModel = PhoneApplicationService.Current.State[ModelKey] as FeedViewModel;
RootFrame.DataContext = ViewModel;
}
}

Add contact in WP7 without using show() method

I wish to add new contacts in WP7. I have used the following
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
SavePhoneNumberTask savePhoneNumber = new SavePhoneNumberTask();
code.savePhoneNumber.Completed += new EventHandler<TaskEventArgs>(savePhoneNumber_Completed);
savePhoneNumber.PhoneNumber = "1987654320";
savePhoneNumber.Show();
}
This shows add more details of Contact page, if we press save then only it is saved.
But i want to save the contacts without calling Show() method.
Please anyone help me.....
You can't and you shouldn't be able to.
Imagine that we could add contacts silently. Apps would start spamming my contacts.
This is the way it works.

How to I get access NavigationService in a WIndows Phone app without going through a PhoneApplicationPage?

How to I get access NavigationService in a Windows Phone app without going through a PhoneApplicationPage? My goal is to pass it to the application's primary view-model on startup, a technique that worked quite well for me in WPF and Silverlight.
You can get it from the app's PhoneApplicationFrame. It will be accessible from anywhere in the app since every Windows Phone app has a Frame.
((PhoneApplicationFrame)Application.Current.RootVisual).Navigate(...);
Another place to get it is from the RootFrame field in the default implementation of Application:
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion

Resources