Book Image

Xamarin Mobile Development for Android Cookbook

By : Matthew Leibowitz
Book Image

Xamarin Mobile Development for Android Cookbook

By: Matthew Leibowitz

Overview of this book

Xamarin is used by developers to write native iOS, Android, and Windows apps with native user interfaces and share code across multiple platforms not just on mobile devices, but on Windows, Mac OS X, and Linux. Developing apps with Xamarin.Android allows you to use and re-use your code and your skills on different platforms, making you more productive in any development. Although it’s not a write-once-run-anywhere framework, Xamarin provides native platform integration and optimizations. There is no middleware; Xamarin.Android talks directly to the system, taking your C# and F# code directly to the low levels. This book will provide you with the necessary knowledge and skills to be part of the mobile development era using C#. Covering a wide range of recipes such as creating a simple application and using device features effectively, it will be your companion to the complete application development cycle. Starting with installing the necessary tools, you will be guided on everything you need to develop an application ready to be deployed. You will learn the best practices for interacting with the device hardware, such as GPS, NFC, and Bluetooth. Furthermore, you will be able to manage multimedia resources such as photos and videos captured with the device camera, and so much more! By the end of this book, you will be able to create Android apps as a result of learning and implementing pro-level practices, techniques, and solutions. This book will ascertain a seamless and successful app building experience.
Table of Contents (20 chapters)
Xamarin Mobile Development for Android Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Asynchronous tasks


All apps need to perform tasks that may take longer than a few milliseconds. If a task blocks the UI thread for longer than a few seconds, Android will terminate it, crashing the application.

How to do it...

If we want to do work in the background, we use a new thread. To do this, we make use of the Task Parallel Library (TPL) and the async/await keywords:

  1. The first thing that is needed is the method that we wish to execute:

    public async Task DoWorkAsync() {
      await Task.Run(() => {
        // some long running task
      });
    }
  2. We then invoke it like a normal method, but just with the await keyword:

    await DoWorkAsync();
  3. We can also attach it to an event:

    doWork.Click += async (sender, args) => {
      await DoWorkAsync();
    }
  4. We can also override the void methods by simply inserting the async keyword before the return type:

    protected override async void OnCreate(Bundle bundle) {
      base.OnCreate(bundle);
      await DoWorkAsync();
    }
  5. If the method needs to return a value, we use Task<>:...