Quantcast
Channel: Envato Tuts+ Code - Mobile Development
Viewing all 1836 articles
Browse latest View live

Google Play Services: Using the Nearby Connections API

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-24534

Introduction

One of the many APIs available in Google Play Services is the Nearby Connections API. Introduced in early 2015, this framework lets you set one device running your application as a host and have multiple other devices connect to it in order to communicate over a Local Area Network (LAN).

Use cases for this feature include connecting a phone to an Android TV for controlling an app and allowing users to participate in a multiplayer game. In this tutorial, you will learn how to set up applications for connecting multiple devices together over a network and how to send data over that connection. A working sample for this tutorial can be found on GitHub.

1. Project Setup

Once you have your initial program created in Android Studio, you will need to import the Play Services library into your app. To do this, place the following line of code under the dependency node of the build.gradle file. At the time of writing, Play Services 7.5.0 is the most recent release for development.

Once Play Services is included in your app, you can close build.gradle and open AndroidManifest.xml. Since this feature uses a LAN to communicate, you will need to include the ACCESS_NETWORK_STATE permission in your manifest.

Next, you will need to add a piece of meta-data in the application node that defines a service identifier that will be used by your app so that it can discover hosts advertising with that same identifier. In this example, our service identifier is defined in strings.xml as tutsplus_service_id.

When you're done with the manifest, you can move to MainActivity.java. This is the class where we will implement both advertising and discovery. In MainActivity, you will also control sending messages between different devices.

In order to start using the Nearby Connections API, you must set up and connect to the Google API Client. Start by implementing ConnectionCallbacks and OnConnectionFailedListener at the top of your class. While we're adding our interfaces, let's also include the three that are needed by the API and an OnClickListener.

Let's now create the member variables that we'll need for this tutorial at the top of the MainActivity class. For the sake of brevity, I'll simply mention that the layout for this class consists of a ListView for displaying messages, an EditText field with a Button for sending messages after connected, a Button for advertising, connecting, or disconnecting, depending on the device's role, and a TextView for displaying basic state information.

You'll notice that there are two boolean flags for designating wether or not the device is connected and if it is the connection host, the GoogleApiClient that is necessary for using the Nearby Connections API, and an array of integers for keeping track of the network connection types we will support for this API.

If you've worked with any Android Google API classes before, the last bit of setup should look fairly familiar. You need to initialize the GoogleApiClient and connect to it in onCreate.

In onStart and onStop, we handle connecting and disconnecting.

2. Advertising and Accepting Connections

Once you have connected to the Google API Client, you can start working with nearby connections. The first component we'll go over is advertising, which allows a device to assume the role of host and manage connections between various peers for communication.

Advertising itself is fairly straightforward. You simply need to check that the device has an acceptable type of connection and then call Nearby.Connections.StartAdvertising with the proper parameters. This will cause the device to advertise across your LAN that it is available for accepting connections from other applications.

In this example, we pass in a timeout of ten seconds for advertising. However, you can pass in a value of 0 to advertise indefinitely. In the following code, isConnectedToNetwork is a helper method meant to check if advertising should occur.

Sample application in advertising mode

Once your host application is advertising, it will be able to receive connection requests from peers. When a device attempts to connect, the following method will be called:

Using this method, you can either accept or reject the connection. To accept the request, you call Nearby.Connections.acceptConnectionRequest with a ResultsCallback. You can then perform actions, depending on whether the connection is successfully accepted or not.

For this example, we'll simply add the remote endpoint to a list to keep track of it and broadcast to any connected peers that this new device has connected. If, for some reason, you determine that the device should not connect to your application, you can reject it by calling Nearby.Connections.rejectConnectionRequest.

Sample host accepting connections from peers

3. Discovery

Just like advertising, discovery relies on being connected to the GoogleApiClient and having an acceptable network connection. You can start discovery by passing the application's service identifier into the Nearby.Connections.startDiscovery method, which sets your user's device into discovery mode.

When the device detects a host that is currently advertising using the predefined service identifier, the onEndpointFound callback will be triggered. It should be noted that this method can be called multiple times if there are multiple hosts broadcasting. In this situation, you can create a dialog for your users that displays all available hosts so that they can select which they would like to be connected to.

For this example, we'll assume that there's only one host advertising at a time, so we'll immediately request to connect by calling Nearby.Connections.sendConnectionRequest. If the connection is accepted or rejected by the host, the sendConnectionRequest result callback will be called. If the connection is accepted, the status will be set to successful and we can save the host endpoint identifier and prepare for sending messages across the connection channel.

Discovering a host

In a situation where you listen for multiple endpoints to present a choice for your users, the onEndpointLost method will let you know if a host has stopped advertising before your user has attempted to connect to it. The onDisconnected callback is also available for client devices and can be used for reconnecting to advertising hosts in the event of an unexpected disconnect.

4. Sending Messages

Once your devices have connected together, it's time to start communicating. There are two kinds of messages that can be sent, reliable and unreliable. If you're familiar with networking technology, you can think of these in terms of TCP (Transmission Control Protocol) and UDP (User Datagram Protocol). A simplified explanation is that reliable messages will retry attempts to send a message if they fail, whereas unreliable messages will simply drop the data if it is not successfully sent and received.

For this tutorial, you will use reliable messages. When a message is received over the API, onMessageReceived will be called. This method accepts the endpoint identifier, a payload, and a boolean indicating whether the connection is reliable or unreliable. The payload contains the message and the endpoint identifier is the identifier of whichever device sent the message.

In the sample application, you will use this to display the payload as a string in a ListView and, if the device is the host, rebroadcast it out to every connected device.

The sendMessage method is a helper method that demonstrates two versions of Nearby.Connections.sendReliableMessage. For host applications, sendReliableMessage will accept a list of endpoints to send the message to. This allows you to communicate to multiple devices with one line of code. For clients, messages only need to go to the host, so only the host name is needed as a parameter with the GoogleApiClient and message byte array.

Sending messages

5. Disconnecting

When you're ready to disconnect on either the host or client side of the application, there is a little bit of clean up that must take place. For hosts, you have to stop advertising and disconnect all of your endpoints.

In the sample code, you'll notice that a message is also sent that attempts to let peers know that the host has disconnected. In a more complete app, you would want your clients to listen for this kind of message so that they can handle the situation appropriately.

If you attempt to disconnect on a client that hasn't connected to a host yet, you simply need to stop discovery. If you've already connected to a host, you call disconnectFromEndpoint and the API will handle severing the connection.

Clean up the connection

Conclusion

In this tutorial, you have learned how to implement communication between various Android devices over a Local Area Network using the Nearby Connections API. You should now be able to enhance your own apps by connecting devices together and keeping them in sync through various updates to each other.

While this tutorial walked you through a fairly simple chat client application, you can take what you've learned here to create polished multiplayer experiences, provide secondary screens for users, or make your apps more contextually aware by providing an additional communication channel for the environment around them.

As the Nearby Connections API continues to grow with the addition of Eddystone beacons and Bluetooth, this will prove to be an invaluable skill to have when developing Android applications.

2015-09-09T17:30:25.000Z2015-09-09T17:30:25.000ZPaul Trebilcox-Ruiz

New Course: Develop Apps for Android Wear

$
0
0

The Android Wear API brings the Android platform to the newest generation of wearable devices and smartwatches. With Android Wear, you can create a user experience designed specifically for wearables. Our latest course gives you a detailed introduction to developing Android Wear apps.

Screenshot from Android Wear app development course

What You’ll Learn

In this course, Tuts+ instructor Paul Trebilcox-Ruiz will teach you about the various UI components specifically designed for Android Wear. You will also learn how to extend your application to use the new Wear notification types. 

Another screenshot from Android Wear app development course

Paul will use practical examples to demonstrate how each of these new components can improve your wearable device applications, and he'll also show you how to create a basic digital watch face to help customize your users' experiences.

Watch the Introduction

Start Learning for Just $15

You can take our new course straight away by subscribing to Tuts+. For just $15 a month, you get access to this course and hundreds of others, with new ones added every week.

2015-09-10T18:15:29.000Z2015-09-10T18:15:29.000ZAndrew Blackman

New Course: Develop Apps for Android Wear

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-24813

The Android Wear API brings the Android platform to the newest generation of wearable devices and smartwatches. With Android Wear, you can create a user experience designed specifically for wearables. Our latest course gives you a detailed introduction to developing Android Wear apps.

Screenshot from Android Wear app development course

What You’ll Learn

In this course, Tuts+ instructor Paul Trebilcox-Ruiz will teach you about the various UI components specifically designed for Android Wear. You will also learn how to extend your application to use the new Wear notification types. 

Another screenshot from Android Wear app development course

Paul will use practical examples to demonstrate how each of these new components can improve your wearable device applications, and he'll also show you how to create a basic digital watch face to help customize your users' experiences.

Watch the Introduction

Start Learning for Just $15

You can take our new course straight away by subscribing to Tuts+. For just $15 a month, you get access to this course and hundreds of others, with new ones added every week.

2015-09-10T18:15:29.000Z2015-09-10T18:15:29.000ZAndrew Blackman

Simplify Android Development Using manifoldJS With Crosswalk

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-24790

With version 0.3.0 of manifoldJS, you can now choose to build your Android apps with Crosswalk instead of the traditional Android webview. It's quite simple to implement as well.

If you're not familiar, manifoldJS is a new open-source framework that can take a website and create an app for Windows, iOS, Android, Chrome, and Firefox, simplifying the creation of hosted apps across platforms. It debuted at the Microsoft Build 2015 conference in April. manifoldJS runs as a command line tool through Node.js, or you can use the web-based tool.

manifoldJS

In this tutorial, I'll show you the simple steps to get it up and running so that you can try it yourself. First, make sure you have manifoldJS installed and running.

Step 1

Install Node.js from nodejs.org.

Step 2

Open your favorite command prompt (Terminal on Mac or Linux) and type:

Now, you simply add the Crosswalk flag to your launch parameters, and watch what happens next:

And…BOOM! You’ve just built a hosted web app with Crosswalk.

Shiftr app on Android phones

A Practical Example of Crosswalk

With Crosswalk, you can be confident that the newest HTML5 features, such as WebGL, IndexedDB, Web Sockets, and CSS3, are there for your app. For example, here's the output from a WebGL application that uses the default webview and was generated by manifoldJS with the following command:

We are sorry but your browser does not seem to support WebGL

And here is the same application with Crosswalk enabled. It was generated after adding the -c (or –-crosswalk) flag to the previous command:

Or:

Your browser supports WebGL

With Crosswalk, you can be sure that all your users get the intended experience.

What Is Crosswalk?

Crosswalk is a web runtime environment engineered by the Crosswalk Project. Crosswalk has taken the open-source Chromium and Blink engines, and compiled them into a modern, up-to-date runtime environment. You can think of Crosswalk as a powerful webview. In fact, when the Crosswalk flag is set, we use it in place of the traditional Android webview.

Why Is Crosswalk Important?

Crosswalk support brings two main advantages. First, it’s an "updated" web runtime environment. That might not be much of an advantage for Android users on a recent version of the Android OS, but for users on older versions of the OS, it's an immense improvement. The Crosswalk webview will give you access to all the latest HTML5 features and performance gains over the traditional webview.

Secondly, Crosswalk provides a consistent runtime environment. With all the different versions of Android in use today, you have that many different versions of the Android webview, so you’re forced to write to the lowest common denominator. Using Crosswalk removes that hindrance. Additionally, the runtime only changes when you update it in your app, not with the OS. We know that many enterprise users rely on this type of consistency for their applications.

Why Would I Not Use Crosswalk?

I can only think of one reason why you wouldn’t want to use Crosswalk: application size. The average .apk file (an application file for Android) that we produce is just a few megabytes. Adding Crosswalk to the app adds an additional 20MB, close to 60MB once installed on the device. You need to decide whether the resource cost is worth it.

Bundling the runtime with the application is the simplest approach for distribution purposes, but Crosswalk applications can also share a single runtime library (in "shared mode") to lighten the load. A package which enables shared mode is part of the Crosswalk for Android distribution. However, you would have to distribute this shared runtime package yourself. Visit the Crosswalk wiki for more details.

Keep in mind that the nature of a hosted web app is that you make your app updates on your webserver. So in most cases, the cost of the added package size will be felt with the initial download, not with every update like a regular native app.

Go Team Crosswalk

We’re excited to be supporting the Crosswalk web runtime environment. It’s filling a gap in the Android system that makes development simpler and more reliable. Give it a try with your next manifoldJS app and see what you think. For more information on Crosswalk, visit the Crosswalk Project website. To start building store apps from your website, go to the manifoldJS website and get started.

More Hands-On With JavaScript

This article is part of the web development series from Microsoft tech evangelists on practical JavaScript learning, open-source projects, and interoperability best practices, including Microsoft Edge browser and the new EdgeHTML rendering engine

We encourage you to test across browsers and devices including Microsoft Edge—the default browser for Windows 10—with free tools on dev.modern.IE:

In-depth tech learning on Microsoft Edge and the Web Platform from our engineers and evangelists:

More free cross-platform tools and resources for the Web Platform:

2015-09-11T16:45:10.000Z2015-09-11T16:45:10.000ZJeff Burtoft

Design Tips for Material Design

$
0
0

Introduction

Over the past months, Material Design has grown in a large design movement. Different components of Material Design, such as content cards and improved use of animation, can be found in many applications we use today.

As many blog posts have covered, on one side this is a good evolution as it's becoming easier than ever to create a solid design. On the other hand, there are voices who disprove the lack of originality as everyone is using a similar style. Besides, having access to a good design language doesn't mean that it's applied correctly.

In this tutorial, we'll be covering how you can take concepts of Material Design and improve them to create better interfaces that are at the same time more distinct in their visual style. We'll also look at a few general tips before you start designing by using Material Design as a starting point.

Material Design as Foundation

First and foremost, starting from Material Design to design interfaces shouldn't be disapproved. Not at all. I, in fact it helps set a foundation which Android users are costumed to.

When it comes to building a good user experience, reinventing the wheel is often not recommended.

Using standards is a particularly great start to assure that you're building something which works. The structure of the interface and its interactions are proven to work. That said, that doesn't mean that there's no room for error or for improvement.

Using Cards In Design

An Example of a Card Design
An Example of a Card Design

The crux of Material Design comes back to the use of content cards. Now, cards are definitely a component that is applicable in a lot of situations hence them being very useful design patterns. Simultaneously, it can be a good design challenge for you to think if there could be more interesting design alternatives. As we're seeing more and more card-based designs, it's good to think how you can design something better.

Take the calendar as an example. Instead of a list per day with a card for each appointment, notice how Sunrise has a combination view in which you see both the monthly view as well as the daily view.

The Combination View in Sunrise
Left: A Material Design Calendar Concept; Right: Sunrise

Games are another great source of inspiration if you're trying to find unique interfaces as a form of inspiration. Check out inspirational websites such as UIMovement to see fresh and new types of interfaces as inspiration.

When you're constructing an interface, would content cards be the most optimal solution or could there be other interesting ways of displaying content that might be a better solution?

Each app is attempting to solve a problem in their own, unique way. With this train of thought, it might make sense that your solution requires a different kind of interface.

Well, how do you proceed? It all begins with content and navigation, which I'll discuss in more detail below.

Beware the Floating Action Button

The Floating Action Button
Example of a Floating Action Button in Google's Inbox

Another design pattern introduced by Material Design is the floating action button. A floating action button is a great way of prominently featuring an action in an interface. At the same time, it can be one of the worst possible design mechanisms. There are plenty of ways to use a floating action button in the wrong way:

  • placing it on a screen that has multiple core user actions instead of just one
  • hiding a menu in a floating action button
  • obstructing important design elements

Personally, I see a couple of instances where a floating action button is a great addition to the product, primarily in apps that have one core interaction for the user. A messaging app is a great example. The floating action button lets the user compose a new message. Uber would be another great example where it makes sense. The core interaction of the product is to hail a car.

The trick is to be careful and see if it makes sense in the context of your product. It's not because it's a standard interface element that it might be a good fit for your app. For more complicated products, where a user is frequently taking multiple actions, a floating action button is rarely a good fit.

User Conversion & Retention Strategies

With a strong design direction to start from, Material Design, it's sometimes fairly easy to forget a strategic foundation before you start designing. How do you decide what you can use from Material Design and what you can improve?

Certain design choices, such as using content cards for example, might limit you early on.

Below, you can find a brief checklist of certain elements of your application that need to be defined well before making these kinds of design decisions.

Asking the right questions gives you a better understanding of what you're trying to build and based upon that you can create interfaces that work better.

Navigation

  • What is the most important user action in my product?
  • On which screen(s) does this occur?
  • What does a flowchart of my product look like?

To conclude, there are two simple rules I tend to keep in mind while structuring the navigation of a product.

Rule 1: 80/20

Apply the 80/20 rule. 80% of my users will use only 20% of my functionality. How can I assure that those 20% of my features are the easiest to access in my product?

Rule 2: Consistency

If there are multiple ways to access a screen in a product, assure that it occurs in a very consistent way. For example, moving from an overview screen to a detail screen should occur in the same fashion.

Based on the above, you can decide what would be the most optimal for users to navigate through a product. If you have a complicated product with a lot of options, a drawer is the right choice. Simple product? Working with tabs is typically your answer. For more information about navigation and Material Design, I recommend browsing the Material Design guidelines.

Content

Music App Concept
This music app concept found on Dribbble is an example of handling multiple types of content.

Every app has content. The following questions should help you decide how to structure and display content from a design perspective:

  • What types of content do I have?
  • How many level(s) of content do I have (for example, an overview screen, followed by a detail screen, and finally an action screen)?
  • What is the typical length of each type of content?
  • What would be the most optimal way of displaying this content? Is it a list? Is it a slideshow? Is it something more unique?

Once you have your content figured out, it's going to be much easier to make design decisions. That's the moment where you can define whether using cards makes sense or if there are better or more interesting alternatives to use for your interface.

Putting Different Types of Users First

The biggest design challenge you can face is the following:

How do I assure that my application is equally gratifying for new users as well as for returning users? How would this affect my content and navigation?

This is a difficult challenge and often comes down to effective onboarding and assuring that the main screen of your product is the screen where most of the value is for your users. Do you need some examples? Take a look at the following products. What is their main screen and what value does it give? How do they approach user onboarding?

  • Instagram
  • Facebook
  • Espresso by The Economist

The above products should give you some inspiration. Don't be discouraged if this feels daunting at first. It has taken the above products multiple iterations to get where they are today.

Onboarding is a subject on its own. I recommend checking out some resources that give you valuable insight, such as User Onboard.

Interface Improvements

Now that we have a good idea how your product fundamentally is going to work plus what possible elements you can use from Material Design, it's time to spice things up a little bit. There are a variety of ways to improve your app aesthetically, some of which are listed below.

Typography

Your font selection contributes tremendously to the look and feel of your product. Picking a custom font can strongly help create a more diverse design and apply a unique look and feel to your product without making a big change. Finding the right fonts can be tricky and much of it also comes down to design taste. My personal favorite resource is Typewolf.

Iconography

Dropbox Iconography
Dropbox is a great example of applying custom icons and illustrations across their products.

Adding custom icons is another way to embed your own custom look and feel within an application. Using custom iconography is tricky as Material Design has created a great standard. For icons, this means that certain actions, navigations, and other elements have the same icon.

If you decide to start working with your own set of icons, there are two important aspects to remind yourself of:

  • Recognizability: Make sure that people understand what each icon implies.
  • Consistency: Typically, it's avoided to combine multiple sets of icons.

Visual Assets

Timehop
Timehop is a great example of using custom illustrations to create a distinct look and feel.

How you display photographic content or the use of illustrations can easily add character to your app. Be creative.

Unique Animations & Interactions

Unique Animations  Interactions
This is an example of a unique animation and corresponding interaction. Source.

Custom animations and interactions require the most effort, but it's gratifying work to see come alive in a product. Unique animations built on unique interfaces that just work are some of the most gratifying design work you can find online.

Unique Color Schemes

Stocks App Design Concept
This design uses Material Design concepts with colors you wouldn't expect. Source.

Material Design provides a great selection of colors you can pick from. That doesn't mean you can't get very creative with your usage of color to create something really unique.

A Word of Caution

There's a reason why most of the interfaces we know on a daily basis are fairly simple designs, it's proven to work and it's something users feel familiar with as they use it.

Experimental design can hurt your app.

That said, with some minor tweaks by, for example, only focusing on typography and color, you can go a long way to design something unique for your app.

Conclusion

Material Design has created a comfortable fallback when you're stuck on a design problem. Until then, you have all the creative freedom to rethink how an interface should work. Snapchat built a gesture-focused product, Facebook Paper (iOS) rethought hierarchy and animation, and Medium effectively reduced an interface to focus on just reading (and writing).

With that in mind, go ahead and design. Any comments or questions? Leave them in the comments or reach out to me on Twitter.

2015-09-11T17:05:52.000Z2015-09-11T17:05:52.000ZSven Lenaerts

Design Tips for Material Design

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-22515

Introduction

Over the past months, Material Design has grown in a large design movement. Different components of Material Design, such as content cards and improved use of animation, can be found in many applications we use today.

As many blog posts have covered, on one side this is a good evolution as it's becoming easier than ever to create a solid design. On the other hand, there are voices who disprove the lack of originality as everyone is using a similar style. Besides, having access to a good design language doesn't mean that it's applied correctly.

In this tutorial, we'll be covering how you can take concepts of Material Design and improve them to create better interfaces that are at the same time more distinct in their visual style. We'll also look at a few general tips before you start designing by using Material Design as a starting point.

Material Design as Foundation

First and foremost, starting from Material Design to design interfaces shouldn't be disapproved. Not at all. I, in fact it helps set a foundation which Android users are costumed to.

When it comes to building a good user experience, reinventing the wheel is often not recommended.

Using standards is a particularly great start to assure that you're building something which works. The structure of the interface and its interactions are proven to work. That said, that doesn't mean that there's no room for error or for improvement.

Using Cards In Design

An Example of a Card Design
An Example of a Card Design

The crux of Material Design comes back to the use of content cards. Now, cards are definitely a component that is applicable in a lot of situations hence them being very useful design patterns. Simultaneously, it can be a good design challenge for you to think if there could be more interesting design alternatives. As we're seeing more and more card-based designs, it's good to think how you can design something better.

Take the calendar as an example. Instead of a list per day with a card for each appointment, notice how Sunrise has a combination view in which you see both the monthly view as well as the daily view.

The Combination View in Sunrise
Left: A Material Design Calendar Concept; Right: Sunrise

Games are another great source of inspiration if you're trying to find unique interfaces as a form of inspiration. Check out inspirational websites such as UIMovement to see fresh and new types of interfaces as inspiration.

When you're constructing an interface, would content cards be the most optimal solution or could there be other interesting ways of displaying content that might be a better solution?

Each app is attempting to solve a problem in their own, unique way. With this train of thought, it might make sense that your solution requires a different kind of interface.

Well, how do you proceed? It all begins with content and navigation, which I'll discuss in more detail below.

Beware the Floating Action Button

The Floating Action Button
Example of a Floating Action Button in Google's Inbox

Another design pattern introduced by Material Design is the floating action button. A floating action button is a great way of prominently featuring an action in an interface. At the same time, it can be one of the worst possible design mechanisms. There are plenty of ways to use a floating action button in the wrong way:

  • placing it on a screen that has multiple core user actions instead of just one
  • hiding a menu in a floating action button
  • obstructing important design elements

Personally, I see a couple of instances where a floating action button is a great addition to the product, primarily in apps that have one core interaction for the user. A messaging app is a great example. The floating action button lets the user compose a new message. Uber would be another great example where it makes sense. The core interaction of the product is to hail a car.

The trick is to be careful and see if it makes sense in the context of your product. It's not because it's a standard interface element that it might be a good fit for your app. For more complicated products, where a user is frequently taking multiple actions, a floating action button is rarely a good fit.

User Conversion & Retention Strategies

With a strong design direction to start from, Material Design, it's sometimes fairly easy to forget a strategic foundation before you start designing. How do you decide what you can use from Material Design and what you can improve?

Certain design choices, such as using content cards for example, might limit you early on.

Below, you can find a brief checklist of certain elements of your application that need to be defined well before making these kinds of design decisions.

Asking the right questions gives you a better understanding of what you're trying to build and based upon that you can create interfaces that work better.

Navigation

  • What is the most important user action in my product?
  • On which screen(s) does this occur?
  • What does a flowchart of my product look like?

To conclude, there are two simple rules I tend to keep in mind while structuring the navigation of a product.

Rule 1: 80/20

Apply the 80/20 rule. 80% of my users will use only 20% of my functionality. How can I assure that those 20% of my features are the easiest to access in my product?

Rule 2: Consistency

If there are multiple ways to access a screen in a product, assure that it occurs in a very consistent way. For example, moving from an overview screen to a detail screen should occur in the same fashion.

Based on the above, you can decide what would be the most optimal for users to navigate through a product. If you have a complicated product with a lot of options, a drawer is the right choice. Simple product? Working with tabs is typically your answer. For more information about navigation and Material Design, I recommend browsing the Material Design guidelines.

Content

Music App Concept
This music app concept found on Dribbble is an example of handling multiple types of content.

Every app has content. The following questions should help you decide how to structure and display content from a design perspective:

  • What types of content do I have?
  • How many level(s) of content do I have (for example, an overview screen, followed by a detail screen, and finally an action screen)?
  • What is the typical length of each type of content?
  • What would be the most optimal way of displaying this content? Is it a list? Is it a slideshow? Is it something more unique?

Once you have your content figured out, it's going to be much easier to make design decisions. That's the moment where you can define whether using cards makes sense or if there are better or more interesting alternatives to use for your interface.

Putting Different Types of Users First

The biggest design challenge you can face is the following:

How do I assure that my application is equally gratifying for new users as well as for returning users? How would this affect my content and navigation?

This is a difficult challenge and often comes down to effective onboarding and assuring that the main screen of your product is the screen where most of the value is for your users. Do you need some examples? Take a look at the following products. What is their main screen and what value does it give? How do they approach user onboarding?

  • Instagram
  • Facebook
  • Espresso by The Economist

The above products should give you some inspiration. Don't be discouraged if this feels daunting at first. It has taken the above products multiple iterations to get where they are today.

Onboarding is a subject on its own. I recommend checking out some resources that give you valuable insight, such as User Onboard.

Interface Improvements

Now that we have a good idea how your product fundamentally is going to work plus what possible elements you can use from Material Design, it's time to spice things up a little bit. There are a variety of ways to improve your app aesthetically, some of which are listed below.

Typography

Your font selection contributes tremendously to the look and feel of your product. Picking a custom font can strongly help create a more diverse design and apply a unique look and feel to your product without making a big change. Finding the right fonts can be tricky and much of it also comes down to design taste. My personal favorite resource is Typewolf.

Iconography

Dropbox Iconography
Dropbox is a great example of applying custom icons and illustrations across their products.

Adding custom icons is another way to embed your own custom look and feel within an application. Using custom iconography is tricky as Material Design has created a great standard. For icons, this means that certain actions, navigations, and other elements have the same icon.

If you decide to start working with your own set of icons, there are two important aspects to remind yourself of:

  • Recognizability: Make sure that people understand what each icon implies.
  • Consistency: Typically, it's avoided to combine multiple sets of icons.

Visual Assets

Timehop
Timehop is a great example of using custom illustrations to create a distinct look and feel.

How you display photographic content or the use of illustrations can easily add character to your app. Be creative.

Unique Animations & Interactions

Unique Animations  Interactions
This is an example of a unique animation and corresponding interaction. Source.

Custom animations and interactions require the most effort, but it's gratifying work to see come alive in a product. Unique animations built on unique interfaces that just work are some of the most gratifying design work you can find online.

Unique Color Schemes

Stocks App Design Concept
This design uses Material Design concepts with colors you wouldn't expect. Source.

Material Design provides a great selection of colors you can pick from. That doesn't mean you can't get very creative with your usage of color to create something really unique.

A Word of Caution

There's a reason why most of the interfaces we know on a daily basis are fairly simple designs, it's proven to work and it's something users feel familiar with as they use it.

Experimental design can hurt your app.

That said, with some minor tweaks by, for example, only focusing on typography and color, you can go a long way to design something unique for your app.

Conclusion

Material Design has created a comfortable fallback when you're stuck on a design problem. Until then, you have all the creative freedom to rethink how an interface should work. Snapchat built a gesture-focused product, Facebook Paper (iOS) rethought hierarchy and animation, and Medium effectively reduced an interface to focus on just reading (and writing).

With that in mind, go ahead and design. Any comments or questions? Leave them in the comments or reach out to me on Twitter.

2015-09-11T17:05:52.000Z2015-09-11T17:05:52.000ZSven Lenaerts

Better Cross-Platform Development: Highlights From the Microsoft Tutorial Series

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-24807

Recently we've been running a series of sponsored tutorials by Microsoft technical evangelists, designed to help you solve the problem of building things that work well across all platforms. 

In case you missed it, here are some of the highlights.

A Fast, Accurate Way to Test Internet Explorer on iOS, Mac OS X, and Android

Testing Internet Explorer on iOS Mac OS X and Android

Microsoft recently launched a new tool to make it easier to test sites in IE regardless of which platform you’re on. It’s called RemoteIE, and is designed to offer a virtualized version of the latest version of IE. This allows you to test out the latest version of IE without having to have a virtual machine installed.

In this tutorial, developer advocate Rey Bango shows you how to set up RemoteIE, and demonstrates what it looks like in Chrome on his MacBook.

Understanding Fluent APIs in JavaScript

Fluent APIs illustration

Have you ever wished that more APIs were fluent? In other words, do you think the community should be able to more easily read, understand, and build upon the work while spending less time in the tech docs?

In this tutorial, David Catuhe walks through fluent APIs: what to consider, how to write them, and cross-browser performance implications. 

Measure the Success of Your Developer Relations Program

Measure the Success of Your Developer Relations Program

Many software companies create developer relations or community outreach programs to win the hearts and minds of developers. But the problem with developer relations is that it’s hard to measure how successful you or your team are and if you’re hitting the mark with your community. In this tutorial, Rey Bango explains what developer advocates do, and examines different ways of measuring the success of outreach efforts.

Deliver Live and On-Demand HTML Video With Azure Media Services

Deliver Live and On-Demand HTML Video With Azure Media Services

Ever want to create your own Twitch.tv-like app for live-streaming your work? How about your own YouTube-esque program for playing back your previously recorded video? You might have used Flash, Java, or Silverlight for rich media in the past, but with Chrome 42 announcing that those plug-ins are no longer supported, now is as good a time to go HTML5 as ever.

In this tutorial, Microsoft technical evangelist David Voyles explains how to use Azure Media Services to get set up and start experimenting with delivering live or on-demand HTML video.

Want to Learn More?

The Microsoft team has contributed plenty more tutorials, on subjects ranging from JavaScript debugging to the Web Audio API. If you want to learn more, you can browse the rest of their Code, Web Design and Game Development tutorials.

2015-09-14T07:12:54.000Z2015-09-14T07:12:54.000ZAndrew Blackman

Getting Started With HealthKit: Part 1

$
0
0

The HealthKit framework was introduced last year at WWDC 2014 as a single place where apps can store, share, and read health-related data. The new Health app, which is the user's view into that data, was one of the flagship features of iOS 8.

One of the main benefits of HealthKit is that fitness and health-related apps can effortlessly share data with each other. During the past year, many developers adopted HealthKit into their apps and tech-savvy users have come to expect that any fitness app integrates with HealthKit.

There are many benefits, gotchas, and best practices when working with this new and exciting framework. Recently, I've had first-hand experience working with the HealthKit framework when I add support for HealthKit to one of my apps, Routie. If you are considering using HealthKit in your own app, then this tutorial is for you.

Why Should I Care About HealthKit?

I've already mentioned some of the benefits of HealthKit, but if you are not sold yet, then let me just say that it's really not that hard to integrate HealthKit. I would even go further and say that it's easier than most other new frameworks that Apple introduced. Obviously, this depends heavily on what you want to achieve with it. But in general, I would say that the ratio between the effort it takes to integrate HealthKit and the benefits it brings to your users is very favorable.

Apart from the straightforward integration into existing apps, it also brings the possibility of building entirely new category of apps. For example, you can pull various data from HealthKit, such as the user's workouts or blood pressure, and display them in an interesting way, leaving the hard work of collecting that data to other apps.

What Will You Learn?

My goal with this tutorial is to teach you the basics by building a sample app. In addition, I will give you a number of useful tips and tricks on how you could or should integrate HealthKit in your own apps. After reading this article, you should have a basic understanding of HealthKit, ready to use it in your apps.

What You Should Know

The following list includes a number of basic facts about HealthKit that you should be aware of:

  • The HealthKit framework is available since iOS 8. Note that it's only available on iPhone, not iPad.
  • Apple is serious about privacy and that's why you must explicitly request access to read and/or write to HealthKit for each data type you need to access. The user has the option to allow access for some types and deny it for others.
  • The HealthKit framework makes heavy use of subclassing.
  • There are two main data types, characteristics and samples. Characteristics, such as the user's birth date or blood type, usually don't change. Sample represent data at a particular point in time.
  • Quantity samples are the most common data types. They include the user's height and weight, steps taken, the user's temperature, pulse rate, etc.
  • Workouts, which belong to the samples category, are intended specifically for representing runs, walks, rides, etc.

For more information about the HealthKit framework, visit Apple's HealthKit Framework Reference.

Before We Get Started

I know you are probably eager to start with the sample project by now, but there are a few important things that you should be aware of before you dive in.

  • The HealthKit store is encrypted when user's phone is locked. This means that you won't be able to read from it when your app is in the background. Writing to HealthKit, however, works even when the phone is locked.
  • You must explain in your App Store description and in your app how your app will use the data obtained from HealthKit. Failing to do so might result in rejection of your app.
  • There is a new section in the App Store review guidelines that covers HealthKit. You should definitely read through it before you decide whether to add support for HealthKit or not.
  • Once your app integrates with HealthKit, you must provide a privacy policy for it. Apple even recommends some documents that specify what Health-related privacy policies should look like. It's important that the privacy policy tells the user how your app treats the their data.

Now that we got this out of the way, let's get started with the tutorial.

The Project

We will build a simple app that integrates with HealthKit and explains some of the basic concepts of the framework. In particular, we will:

  • create a new project from scratch and enable HealthKit
  • ask the user's permission to access their health-related data
  • read the user's birth date
  • write a weight sample to HealthKit
  • write a workout to HealthKit

1. Setting Up the Project

Launch Xcode and select File> New> Project... From the iOS > Application section, select the Tabbed Application template and click Next.

Creating new project - Selecting template

Enter HealthBasics as the project's Product Name and click Next. Select where you want to save the project and click Create.

Creating new project - final step

2. Enabling HealthKit

In the Project Navigator on the left, click the project, select the HealthBasics target, and open the Capabilities tab at the top. Scroll down to the HealthKit section and enable HealthKit toggling the switch on the right. Behind the scenes, Xcode will do the necessary for you to enable HealthKit.

Enabling HealthKit

3. Creating the User Interface

For this project, we won't be using size classes. Because size classes are enabled by default, we need to manually disable them in Xcode. In the Project Navigator on the left, select Main.storyboard. Open the File Inspector on the right and uncheck the checkbox labeled Use Size Classes.

Xcode will show you a warning dialog. Dismiss it by clicking Disable Size Classes, but make to keep size class data for iPhone as shown below.

Xcode - Disabling Size Classes

Remove the two labels in the First View Controller. Next, drag a label and a switch from the Object Library on the right onto the First View Controller. Change the label's text to Health integration and set the state of the switch to off.

First tab UI - part 1

Add two more labels and a button to the First View Controller. Change the first label's text to User's age:, change the second label's text to ??, and align them horizontally as shown in the below screenshot. Finally, change the button's title to Read and position it to the right of the second label. The first scene should now look like this:

First tab UI - part 2

We're not done yet. Add one more label, a text field, and a button to the First View Controller, aligning them horizontally as shown below. Change the label's text to User's weight: and change the button's title to Write.

Select the text field you've just added and, in the Attributes Inspector, change its Keyboard Type to Numbers and Punctuation. That's it. The first scene should now look like this:

First tab UI - part 3

4. Creating the HealthKit Manager

We are going to keep HealthKit-related code in a separate class, the GSHealthKitManager class. Let's create that class now.

In the Project Navigator, right-click the HealthBasics group and select New File.... Make sure Cocoa Touch Class is selected from the list of templates and click Next. Name the class GSHealthKitManager and click Next.

Creating the GSHealthKitManager class

Open the header file of the GSHealthKitManager class and replace the file's contents with the following code. Later, we will call these methods from the FirstViewController class.

Next, ope the implementation file of the GSHealthKitManager class and replace its contents with the following:

While most of the HealthKit-related code is easy enough to understand, let's go over each method to make sure we're on the same page.

  • sharedManager is a class method that creates the singleton object the first time it is called, and returns that instance each time the method is invoked. The dispatch_once function is a GCD (Grand Central Dispatch) function that guarantees that the block passed to it is called only once, even if the sharedManager method would get called from multiple threads at the same time.
  • requestAuthorization is a method that asks the HealthKit store for permissions to read and/or write the specific data that we need. You need to call this method before you use any of the writing/reading APIs of the HKHealthStore class. In case the user denies some (or all) permissions, HealthKit won't inform you about that. The fact that the user doesn't want to share some types of data is information in itself. That's how much Apple cares about privacy.
  • The readBirthDate method returns the user's birth date. It return nil if there was an error or if the user hasn't entered a birth date.
  • writeWeightSample: saves a weight measurement to HealthKit. I've commented the code so you should have a general idea of what's going on in the method. Once we have the HKQuantitySample object, we save it to the HKHealthStore instance, using its saveObject:withCompletion: method. This method is used for every type of health data and we will also use it in the second part of this tutorial when saving workouts.

In this step, you encountered a number of HealthKit classes. You can read more about each class in the HealthKit Framework Reference, but I'll give you a brief summary of each class.

  • HKHealthStore This is your window to HealthKit data. Apple recommends using just one instance of this class in your app and that lends itself to the singleton pattern really well. You use it for asking the user for permissions, saving samples and/or workouts to HealthKit, and querying the stored data. These are just a few of the tasks of the HKHealthStore class.
  • HKUnit Instances of this class can represent either basic units, such as meters, seconds, and grams, or complex units that are created by combining basic units, such as km/h or or g/m³. Complex units can be conveniently created from strings.
  • HKQuantity Instances of this class store a value (represented by double) for a given unit (represented by HKUnit). You can use the doubleValueForUnit: method to convert the quantity's value to the unit that's passed in. An example of such a conversion would be creating distance quantity with unit of meters and asking for its value in feet.
  • HKQuantityType HealthKit uses quantity types to create samples that store a numerical value. It is recommended to use quantityTypeForIdentifier: when creating quantity types. A few examples of quantity types are cycling distance, energy burned, steps, and flights climbed.
  • HKQuantitySample An instance of this class represents a sample that has a quantity type (represented by HKQuantityType), a quantity (represented by HKQuantity), and a start and end date. In case the sample doesn't span over a period of time, the end date can be the same as the start date.

We can now use the GSHealthKitManager singleton from anywhere in our application to work with HealthKit.

Conclusion

In this tutorial, you learned about the basics of the HealthKit framework. I've introduced you to the framework and pointed out some of the caveats to watch out for. We've also built the foundation of the sample app and implemented the GSHealthKitManager class, which we'll use to interact with HealthKit.

In the second part of this series, we'll continue building the sample app and further integrate HealthKit. You can find the source files for this tutorial on GitHub.

2015-09-14T16:45:21.000Z2015-09-14T16:45:21.000ZLukas Petr

Getting Started With HealthKit: Part 1

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-24477

The HealthKit framework was introduced last year at WWDC 2014 as a single place where apps can store, share, and read health-related data. The new Health app, which is the user's view into that data, was one of the flagship features of iOS 8.

One of the main benefits of HealthKit is that fitness and health-related apps can effortlessly share data with each other. During the past year, many developers adopted HealthKit into their apps and tech-savvy users have come to expect that any fitness app integrates with HealthKit.

There are many benefits, gotchas, and best practices when working with this new and exciting framework. Recently, I've had first-hand experience working with the HealthKit framework when I add support for HealthKit to one of my apps, Routie. If you are considering using HealthKit in your own app, then this tutorial is for you.

Why Should I Care About HealthKit?

I've already mentioned some of the benefits of HealthKit, but if you are not sold yet, then let me just say that it's really not that hard to integrate HealthKit. I would even go further and say that it's easier than most other new frameworks that Apple introduced. Obviously, this depends heavily on what you want to achieve with it. But in general, I would say that the ratio between the effort it takes to integrate HealthKit and the benefits it brings to your users is very favorable.

Apart from the straightforward integration into existing apps, it also brings the possibility of building entirely new category of apps. For example, you can pull various data from HealthKit, such as the user's workouts or blood pressure, and display them in an interesting way, leaving the hard work of collecting that data to other apps.

What Will You Learn?

My goal with this tutorial is to teach you the basics by building a sample app. In addition, I will give you a number of useful tips and tricks on how you could or should integrate HealthKit in your own apps. After reading this article, you should have a basic understanding of HealthKit, ready to use it in your apps.

What You Should Know

The following list includes a number of basic facts about HealthKit that you should be aware of:

  • The HealthKit framework is available since iOS 8. Note that it's only available on iPhone, not iPad.
  • Apple is serious about privacy and that's why you must explicitly request access to read and/or write to HealthKit for each data type you need to access. The user has the option to allow access for some types and deny it for others.
  • The HealthKit framework makes heavy use of subclassing.
  • There are two main data types, characteristics and samples. Characteristics, such as the user's birth date or blood type, usually don't change. Sample represent data at a particular point in time.
  • Quantity samples are the most common data types. They include the user's height and weight, steps taken, the user's temperature, pulse rate, etc.
  • Workouts, which belong to the samples category, are intended specifically for representing runs, walks, rides, etc.

For more information about the HealthKit framework, visit Apple's HealthKit Framework Reference.

Before We Get Started

I know you are probably eager to start with the sample project by now, but there are a few important things that you should be aware of before you dive in.

  • The HealthKit store is encrypted when user's phone is locked. This means that you won't be able to read from it when your app is in the background. Writing to HealthKit, however, works even when the phone is locked.
  • You must explain in your App Store description and in your app how your app will use the data obtained from HealthKit. Failing to do so might result in rejection of your app.
  • There is a new section in the App Store review guidelines that covers HealthKit. You should definitely read through it before you decide whether to add support for HealthKit or not.
  • Once your app integrates with HealthKit, you must provide a privacy policy for it. Apple even recommends some documents that specify what Health-related privacy policies should look like. It's important that the privacy policy tells the user how your app treats the their data.

Now that we got this out of the way, let's get started with the tutorial.

The Project

We will build a simple app that integrates with HealthKit and explains some of the basic concepts of the framework. In particular, we will:

  • create a new project from scratch and enable HealthKit
  • ask the user's permission to access their health-related data
  • read the user's birth date
  • write a weight sample to HealthKit
  • write a workout to HealthKit

1. Setting Up the Project

Launch Xcode and select File> New> Project... From the iOS > Application section, select the Tabbed Application template and click Next.

Creating new project - Selecting template

Enter HealthBasics as the project's Product Name and click Next. Select where you want to save the project and click Create.

Creating new project - final step

2. Enabling HealthKit

In the Project Navigator on the left, click the project, select the HealthBasics target, and open the Capabilities tab at the top. Scroll down to the HealthKit section and enable HealthKit toggling the switch on the right. Behind the scenes, Xcode will do the necessary for you to enable HealthKit.

Enabling HealthKit

3. Creating the User Interface

For this project, we won't be using size classes. Because size classes are enabled by default, we need to manually disable them in Xcode. In the Project Navigator on the left, select Main.storyboard. Open the File Inspector on the right and uncheck the checkbox labeled Use Size Classes.

Xcode will show you a warning dialog. Dismiss it by clicking Disable Size Classes, but make to keep size class data for iPhone as shown below.

Xcode - Disabling Size Classes

Remove the two labels in the First View Controller. Next, drag a label and a switch from the Object Library on the right onto the First View Controller. Change the label's text to Health integration and set the state of the switch to off.

First tab UI - part 1

Add two more labels and a button to the First View Controller. Change the first label's text to User's age:, change the second label's text to ??, and align them horizontally as shown in the below screenshot. Finally, change the button's title to Read and position it to the right of the second label. The first scene should now look like this:

First tab UI - part 2

We're not done yet. Add one more label, a text field, and a button to the First View Controller, aligning them horizontally as shown below. Change the label's text to User's weight: and change the button's title to Write.

Select the text field you've just added and, in the Attributes Inspector, change its Keyboard Type to Numbers and Punctuation. That's it. The first scene should now look like this:

First tab UI - part 3

4. Creating the HealthKit Manager

We are going to keep HealthKit-related code in a separate class, the GSHealthKitManager class. Let's create that class now.

In the Project Navigator, right-click the HealthBasics group and select New File.... Make sure Cocoa Touch Class is selected from the list of templates and click Next. Name the class GSHealthKitManager and click Next.

Creating the GSHealthKitManager class

Open the header file of the GSHealthKitManager class and replace the file's contents with the following code. Later, we will call these methods from the FirstViewController class.

Next, ope the implementation file of the GSHealthKitManager class and replace its contents with the following:

While most of the HealthKit-related code is easy enough to understand, let's go over each method to make sure we're on the same page.

  • sharedManager is a class method that creates the singleton object the first time it is called, and returns that instance each time the method is invoked. The dispatch_once function is a GCD (Grand Central Dispatch) function that guarantees that the block passed to it is called only once, even if the sharedManager method would get called from multiple threads at the same time.
  • requestAuthorization is a method that asks the HealthKit store for permissions to read and/or write the specific data that we need. You need to call this method before you use any of the writing/reading APIs of the HKHealthStore class. In case the user denies some (or all) permissions, HealthKit won't inform you about that. The fact that the user doesn't want to share some types of data is information in itself. That's how much Apple cares about privacy.
  • The readBirthDate method returns the user's birth date. It return nil if there was an error or if the user hasn't entered a birth date.
  • writeWeightSample: saves a weight measurement to HealthKit. I've commented the code so you should have a general idea of what's going on in the method. Once we have the HKQuantitySample object, we save it to the HKHealthStore instance, using its saveObject:withCompletion: method. This method is used for every type of health data and we will also use it in the second part of this tutorial when saving workouts.

In this step, you encountered a number of HealthKit classes. You can read more about each class in the HealthKit Framework Reference, but I'll give you a brief summary of each class.

  • HKHealthStore This is your window to HealthKit data. Apple recommends using just one instance of this class in your app and that lends itself to the singleton pattern really well. You use it for asking the user for permissions, saving samples and/or workouts to HealthKit, and querying the stored data. These are just a few of the tasks of the HKHealthStore class.
  • HKUnit Instances of this class can represent either basic units, such as meters, seconds, and grams, or complex units that are created by combining basic units, such as km/h or or g/m³. Complex units can be conveniently created from strings.
  • HKQuantity Instances of this class store a value (represented by double) for a given unit (represented by HKUnit). You can use the doubleValueForUnit: method to convert the quantity's value to the unit that's passed in. An example of such a conversion would be creating distance quantity with unit of meters and asking for its value in feet.
  • HKQuantityType HealthKit uses quantity types to create samples that store a numerical value. It is recommended to use quantityTypeForIdentifier: when creating quantity types. A few examples of quantity types are cycling distance, energy burned, steps, and flights climbed.
  • HKQuantitySample An instance of this class represents a sample that has a quantity type (represented by HKQuantityType), a quantity (represented by HKQuantity), and a start and end date. In case the sample doesn't span over a period of time, the end date can be the same as the start date.

We can now use the GSHealthKitManager singleton from anywhere in our application to work with HealthKit.

Conclusion

In this tutorial, you learned about the basics of the HealthKit framework. I've introduced you to the framework and pointed out some of the caveats to watch out for. We've also built the foundation of the sample app and implemented the GSHealthKitManager class, which we'll use to interact with HealthKit.

In the second part of this series, we'll continue building the sample app and further integrate HealthKit. You can find the source files for this tutorial on GitHub.

2015-09-14T16:45:21.000Z2015-09-14T16:45:21.000ZLukas Petr

Getting Started With HealthKit: Part 2

$
0
0

In the first part of this tutorial, I introduced you to the HealthKit framework. Based on my own experience of integrating HealthKit in one of my apps, I've pointed out a few things that are important to keep in mind. We've also started working on our sample app, HealthBasics, which will explain the basic concepts of working with HealthKit.

In the first part, we implemented the GSHealthKitManager class, which we'll use to interact with HealthKit. Let's now use the GSHealthKitManager class to implement the functionality of the first view controller of the sample app.

1. Implementing the First View Controller

In the Project Navigator, open FirstViewController.m and replace its contents with the following:

If you have some iOS development experience, then the implementation shouldn't be difficult to understand. In the first view controller, we respond to the user toggling the switch and tapping one of the buttons. Each of these interactions triggers a method of the GSHealthKitManager class.

There's a reason why I've chosen to use a switch to ask the user's permission to access their HealthKit data. Once you understand the implementation, you'll understand that it's a much better solution.

It's easy for the user to understand that, when the switch is on, the app integrates with HealthKit. When it's off, it doesn't. In addition to that, turning this switch on for the first time will prompt the user to grant access to the health data types the app will use. This, again, is a good user experience, because the user understands why she is prompted and what benefits she gets by permitting access.

2. Connecting the User Interface

In the Project Navigator, open Main.storyboard. In the first scene, select the switch. In the Utilities pane on the right, open the Connections Inspector and, in the Sent Events section, drag from Value Changed to the First View controller in the Document Outline. From the pop-up menu that lists the actions of the view controller, select healthIntegrationButtonSwitched:. This ensures the healthIntegrationButtonSwitched: method is called whenever the switch is toggled.

User interface - connecting outlets 1

The steps to connect the Read and Write buttons are almost identical. Click the Read button, only this time, drag from the Touch Up Inside event to the First View Controller. Select the readAgeButtonPressed: action from the pop-up menu.

Click the Write button and drag from the Touch Up Inside event to the First View Controller, select the writeWeightButtonPressed: method from the pop-up menu.

We now need to connect the outlets we declared to the user interface elements. Press Control and drag from First View Controller to the label with the two question marks. From the pop-up menu titled Outlets, click on ageLabel. This will connect the outlet to the label.

User interface - connecting outlets 2

Repeat these steps for the text field, connecting it to the weightTextField outlet of the view controller.

User interface - connecting outlets 3

3. Build and Run

The first scene should now be fully functional. Launch the app and turn the switch on. You should be prompted with the following HealthKit permissions user interface:

Health Access UI

Make sure to turn on both switches before tapping Done, otherwise your app won't have access to the data we need in the sample app.

You can now try tapping the Read button. If you are running the app in the iOS Simulator, probably nothing will happen, because you haven't set a birth date. You can head over to the Health app in the iOS Simulator and set it.

  • Open the Health app.
  • Select Health Data tab.
  • Tap Me.
  • Tap Edit.
  • Tap Birthdate and set a date. Tap Done.

You can now go back to our HealthBasics app and tap the Read button again. This time your age should be displayed.

You can also test the weight sharing. Select the weight text field and enter a value in kilograms. After you tap Write, head back to the Health app and, in the Health Data tab, select Body Measurements and Weight. The sample you just added should be visible.

HealthKit Weight sample

So far, you've learned the basics of working with HealthKit.

  • how to ask the user for permission
  • how to read and write basic data
  • how to encapsulate HealthKit-related code in a separated class

4. Adding a Workout

In the second part of our sample app, I will show you how to write a workout to HealthKit. This is useful if you are building any kind of workout (running, cycling, walking, etc.) app. Most of the building blocks are similar.

Step 1: Extending the GSHealthKitManager Class

We start by extending the GSHealthKitManager class. Add the following method declaration to GSHealthKitManager.h:

Add a new share type to the requestAuthorizationToShareTypes:readTypes:completion: method by adding the workout type to the writeTypes array.

Finally, add the writeWorkoutDataFromModelObject: method at bottom of the GSHealthKitManager class.

In my own app, Routie, I've used the approach of passing a model object to the writeWorkoutDataFromModelObject: method, delegating the heavy lifting to the manager class. The latter pulls the required data from the model object and passes the information to the HKHealthStore instance. I believe it's a good approach to keep the HealthKit-related code confined in the manager class.

The implementation of the writeWorkoutDataFromModelObject: method is pretty straightforward. There are just three steps:

  1. We first prepare the data. In this example, we are making the numbers up.
  2. We then create a HKWorkout object by invoking one of the convenience initializers of the class.
  3. Finally, we save the HKWorkout object to the HKHealthStore instance.

This is the first time we've worked with the HKWorkout class so let me briefly introduce this class. The HealthKit framework uses the HKWorkout class to track activities. Workouts are mostly immutable, so you have to provide the values of the workout during initialization.

When initializing a workout, you are required to provide an activity type, a start date, and and end date. You can optionally pass in total distance, total energy burned, and metadata. The metadata can be used to assign additional information to the workout. This is really useful when you want to share more information about a workout with a different application that you also created.

Step 2: Implementing the writeWorkoutButtonPressed: Action

Open SecondViewController.m and add the following import to the top of the file:

Next, implement the writeWorkoutButtonPressed: method as shown below.

Step 3: Creating the Workout User Interface

We will just add a single button to the second scene of the app to write the workout. Open Main.storyboard and focus on the second scene. Delete the labels that are currently in the Second View Controller.

Add a button in the center of the view controller's view and set its title to Write Workout. Connect its Touch Up Inside event to the writeWorkoutButtonPressed: action we implemented in the previous step.

5. Testing

Build and run the application, and set the Health integration switch to on. The Health Access screen will be presented with the newly requested workout type switched off. Switch it on and tap Done. This is only needed, because we added the workout share type to the list of share types. This means that we need to ask the user for permission before we use it.

HealthKit Health Access UI

Open the second tab at the bottom and tap Write Workout. If everything went right, you should see the following message in Xcode's Console:

Now you can switch to the Health app and go to Health Data> Fitness> Workouts. There you should see the workout that was just added.

HealthKit - Workout Sample

Conclusion

In this tutorial, I've showed you how you can write a workout to HealthKit. I've also shown you how to separate HealthKit-related code by passing a model object to the method that writes the workout to HealthKit.

I hope you've enjoyed this tutorial and that you've learnt all the basics you need to go out there and integrate your own app with HealthKit. I also hope that I've convinced you to give HealthKit a try.

Let me know in the comments how you liked this tutorial or if anything was unclear. You can also find me on Twitter.

Links

The list below includes a number of relevant links so you can quickly jump to what you need:

2015-09-16T16:15:16.000Z2015-09-16T16:15:16.000ZLukas Petr

Getting Started With HealthKit: Part 2

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-24484

In the first part of this tutorial, I introduced you to the HealthKit framework. Based on my own experience of integrating HealthKit in one of my apps, I've pointed out a few things that are important to keep in mind. We've also started working on our sample app, HealthBasics, which will explain the basic concepts of working with HealthKit.

In the first part, we implemented the GSHealthKitManager class, which we'll use to interact with HealthKit. Let's now use the GSHealthKitManager class to implement the functionality of the first view controller of the sample app.

1. Implementing the First View Controller

In the Project Navigator, open FirstViewController.m and replace its contents with the following:

If you have some iOS development experience, then the implementation shouldn't be difficult to understand. In the first view controller, we respond to the user toggling the switch and tapping one of the buttons. Each of these interactions triggers a method of the GSHealthKitManager class.

There's a reason why I've chosen to use a switch to ask the user's permission to access their HealthKit data. Once you understand the implementation, you'll understand that it's a much better solution.

It's easy for the user to understand that, when the switch is on, the app integrates with HealthKit. When it's off, it doesn't. In addition to that, turning this switch on for the first time will prompt the user to grant access to the health data types the app will use. This, again, is a good user experience, because the user understands why she is prompted and what benefits she gets by permitting access.

2. Connecting the User Interface

In the Project Navigator, open Main.storyboard. In the first scene, select the switch. In the Utilities pane on the right, open the Connections Inspector and, in the Sent Events section, drag from Value Changed to the First View controller in the Document Outline. From the pop-up menu that lists the actions of the view controller, select healthIntegrationButtonSwitched:. This ensures the healthIntegrationButtonSwitched: method is called whenever the switch is toggled.

User interface - connecting outlets 1

The steps to connect the Read and Write buttons are almost identical. Click the Read button, only this time, drag from the Touch Up Inside event to the First View Controller. Select the readAgeButtonPressed: action from the pop-up menu.

Click the Write button and drag from the Touch Up Inside event to the First View Controller, select the writeWeightButtonPressed: method from the pop-up menu.

We now need to connect the outlets we declared to the user interface elements. Press Control and drag from First View Controller to the label with the two question marks. From the pop-up menu titled Outlets, click on ageLabel. This will connect the outlet to the label.

User interface - connecting outlets 2

Repeat these steps for the text field, connecting it to the weightTextField outlet of the view controller.

User interface - connecting outlets 3

3. Build and Run

The first scene should now be fully functional. Launch the app and turn the switch on. You should be prompted with the following HealthKit permissions user interface:

Health Access UI

Make sure to turn on both switches before tapping Done, otherwise your app won't have access to the data we need in the sample app.

You can now try tapping the Read button. If you are running the app in the iOS Simulator, probably nothing will happen, because you haven't set a birth date. You can head over to the Health app in the iOS Simulator and set it.

  • Open the Health app.
  • Select Health Data tab.
  • Tap Me.
  • Tap Edit.
  • Tap Birthdate and set a date. Tap Done.

You can now go back to our HealthBasics app and tap the Read button again. This time your age should be displayed.

You can also test the weight sharing. Select the weight text field and enter a value in kilograms. After you tap Write, head back to the Health app and, in the Health Data tab, select Body Measurements and Weight. The sample you just added should be visible.

HealthKit Weight sample

So far, you've learned the basics of working with HealthKit.

  • how to ask the user for permission
  • how to read and write basic data
  • how to encapsulate HealthKit-related code in a separated class

4. Adding a Workout

In the second part of our sample app, I will show you how to write a workout to HealthKit. This is useful if you are building any kind of workout (running, cycling, walking, etc.) app. Most of the building blocks are similar.

Step 1: Extending the GSHealthKitManager Class

We start by extending the GSHealthKitManager class. Add the following method declaration to GSHealthKitManager.h:

Add a new share type to the requestAuthorizationToShareTypes:readTypes:completion: method by adding the workout type to the writeTypes array.

Finally, add the writeWorkoutDataFromModelObject: method at bottom of the GSHealthKitManager class.

In my own app, Routie, I've used the approach of passing a model object to the writeWorkoutDataFromModelObject: method, delegating the heavy lifting to the manager class. The latter pulls the required data from the model object and passes the information to the HKHealthStore instance. I believe it's a good approach to keep the HealthKit-related code confined in the manager class.

The implementation of the writeWorkoutDataFromModelObject: method is pretty straightforward. There are just three steps:

  1. We first prepare the data. In this example, we are making the numbers up.
  2. We then create a HKWorkout object by invoking one of the convenience initializers of the class.
  3. Finally, we save the HKWorkout object to the HKHealthStore instance.

This is the first time we've worked with the HKWorkout class so let me briefly introduce this class. The HealthKit framework uses the HKWorkout class to track activities. Workouts are mostly immutable, so you have to provide the values of the workout during initialization.

When initializing a workout, you are required to provide an activity type, a start date, and and end date. You can optionally pass in total distance, total energy burned, and metadata. The metadata can be used to assign additional information to the workout. This is really useful when you want to share more information about a workout with a different application that you also created.

Step 2: Implementing the writeWorkoutButtonPressed: Action

Open SecondViewController.m and add the following import to the top of the file:

Next, implement the writeWorkoutButtonPressed: method as shown below.

Step 3: Creating the Workout User Interface

We will just add a single button to the second scene of the app to write the workout. Open Main.storyboard and focus on the second scene. Delete the labels that are currently in the Second View Controller.

Add a button in the center of the view controller's view and set its title to Write Workout. Connect its Touch Up Inside event to the writeWorkoutButtonPressed: action we implemented in the previous step.

5. Testing

Build and run the application, and set the Health integration switch to on. The Health Access screen will be presented with the newly requested workout type switched off. Switch it on and tap Done. This is only needed, because we added the workout share type to the list of share types. This means that we need to ask the user for permission before we use it.

HealthKit Health Access UI

Open the second tab at the bottom and tap Write Workout. If everything went right, you should see the following message in Xcode's Console:

Now you can switch to the Health app and go to Health Data> Fitness> Workouts. There you should see the workout that was just added.

HealthKit - Workout Sample

Conclusion

In this tutorial, I've showed you how you can write a workout to HealthKit. I've also shown you how to separate HealthKit-related code by passing a model object to the method that writes the workout to HealthKit.

I hope you've enjoyed this tutorial and that you've learnt all the basics you need to go out there and integrate your own app with HealthKit. I also hope that I've convinced you to give HealthKit a try.

Let me know in the comments how you liked this tutorial or if anything was unclear. You can also find me on Twitter.

Links

The list below includes a number of relevant links so you can quickly jump to what you need:

2015-09-16T16:15:16.000Z2015-09-16T16:15:16.000ZLukas Petr

A Fast, Accurate Way to Test Internet Explorer on iOS, Mac OS X, and Android

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-24192

Earlier this year, the Microsoft team launched a new tool to make it easier to test sites in IE regardless of which platform you’re on; seriously! It’s part of their work on Microsoft Edge and its new rendering engine and new user-agent string, which is a fork of Trident that’s far more interoperable with the mobile Web.

In this tutorial, I want to demonstrate what this looks like in Chrome on my MacBook and how to set it up.

tl;dr? Here are some Vines to show you it in action:

The tool is called RemoteIE and is designed to offer a virtualized version of the latest version of IE. This allows you to test out the latest version of IE without having to have a virtual machine installed. And if you want to test for past versions of IE, you can always use the free virtual machines on http://dev.modern.ie by starting here.

Getting It All Set Up

I ran through the steps to use the tool myself and wanted to document everything in case you run into any hiccups.

First, head on over to RemoteIE which will take you to this page:

modernie signin page

You’ll need a Microsoft account to use the service since it needs to associate the service to that account.

Application permissions page

If you have a Live.com or Outlook.com account you can use that, or you can register for a new one. No, you don’t need to use those services for anything else if you don’t want to, but they’ve actually gotten way better and might be worth a look.

Next, you’ll want to select which server is closest to you so you have the best possible performance:

Select a server location

At this point you’ll be asked to download the Microsoft Remote Desktop app for whichever platform you want. This could be for

  • Mac OS X
  • iPhone or iPad
  • Android
  • Windows x86 or x64
  • Windows RT
Download page

As you can see, I was serious when I said this would be available cross-platform. On your Mac, download the app from the Apple App Store. Clicking on the Mac link will direct you to the online Apple store site.

Microsoft Remote Desktop app in Apple App Store

Click on the View in Mac App Store button so that you can launch the App Store app on your Mac. You’ll be presented by a confirmation notice from Chrome (or your favorite OS X browser) to launch the external app:

Chrome confirmation page

And after you confirm it you’ll be in the App Store entry:

Microsoft Remote Desktop App Store page

In my case, I already had the app installed which is why it shows “Open”. If you don’t have it installed, go ahead and do so. Once you've installed it, look for it in Finder:

Microsoft Remote Desktop in Finder

Or if you’re like me, use the awesome Alfred to find it:

Typing Microsoft remote d in Alfred

Now, the next step is why I wanted to create this tutorial, since it isn’t immediately obvious once you run Remote Desktop what to do. When you launch the app, if you take a look at the header, you’ll see an entry called Microsoft RemoteApp. That’s what you’ll want to click:

Microsoft RemoteApp button

From there, you’ll now be asked for your Microsoft account information to determine what app subscriptions you have available:

Enter email address
Loading subscriptions

Now that it’s figured out that you’re legit, you’ll see a dialog showing what your app subscriptions are:

Subscriptions list

Again, I want to help you avoid confusion here since the UX at this specific point is a little off. When you click on the checkbox for “Internet Explorer (email: iewebeco@microsoft.com)”, an entry for “Internet Explorer->IE Technical Preview” will be added to the main Microsoft Remote Desktop app BUT the dialog with the checkbox I just mentioned doesn’t disappear. See here:

Subscription box checked

So heads up. Once you see the entry in the main app that says IE Technical Preview, you can close the dialog box with the checkbox. You can see in the previous image how I highlighted the close dialog icon.

We’re almost done. Next, go ahead and double-click on IE Technical Preview to launch your virtualized version of IE. It’ll take just a minute to spin everything up so be patient:

Please wait for the User Profile Service page

And once it’s up, you have a full-blown version of IE 11 Technical Preview ready for you. Notice in the following image how the F12 Developer Tools are there for you:

the F12 Developer Tools are there for you

More Testing Tools

This is a great new tool, and it’ll definitely lower the friction to testing on the latest version of IE, but there are some limitations that should be noted, including the inability to access the local file system. It would be great if that were possible, but VMs can be tricky to deal with, especially from a security perspective.

Of course, there are other free tools that can help you test for IE:

If you want more details, you can check out the Remote.IE announcement on the IE Blog. So now that you’ve got this all set up, let us know if it’s helping you spend less time testing.

This article is part of the web dev tech series from Microsoft. We’re excited to share Microsoft Edge and the new EdgeHTML rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device @ http://dev.modern.ie/.

2015-09-21T07:28:14.000Z2015-09-21T07:28:14.000ZRey Bango

Getting Started With Google Maps for Android: Basics

$
0
0

Introduction

Without a doubt, maps are one of the most useful tools for users when included in an app. This tutorial is the first in a series going over Google Maps v2 for Android. It will cover setting up the Google Maps API through the Google Developer Console, including a map fragment in your applications, displaying the user's location, adding markers, drawing on the map, and some general methods that will add utility to your app. All code for this tutorial can be found onGitHub.

1. Setting Up the Developer Console

In order to use the Google Maps API, you must register your application on the Google Developer Console and enable the API. To do this, start by going to the Google Developer Console. If you already have a project created, you can skip the next section. If not, you can follow along and create a new project for your maps application.

Step 1: Creating a Project

To create a new project, click on the blue Create Project button in the top left corner of the screen. If you don't see a Create Project button, then look for a button labeled Create an empty project.

Create a project button

This presents you with a dialog that asks for a project name. For this tutorial, I have created a project called TutsPlusMaps. There are some restrictions on what you can name your project as only letters, numbers, quotes, hyphens, spaces, and exclamation points are allowed characters.

Creating a project dialog window

Once you hit Create, a dialog appears in the lower right corner of the page with a loading indicator while the project is being created.

Step 2: Enabling the Maps API

When the project has been created, or you have selected an existing project, you are taken to the project Overview screen. From here you will want to expand the APIs & auth item in the left navigation panel and click on APIs.

APIs  Auth location in nav

While there's a search box on this screen, you'll notice that Google placed the Maps API items at the top of the center column for developers to access. For this tutorial, click on the item titled Google Maps Android API under the Google Maps APIs heading.

Google Maps API item

This takes you to a screen where you can click on the blue Enable API button in order to enable the Maps API for your project.

Enable API button

Step 3: Creating an Android API Key

After you've enabled the Maps API, click on the Credentials item under APIs & auth in the side navigation to get a key to access the Maps API in your application. When you are presented with the Credentials dialog, press the blue Add Credentials button and select API Key.

Dialog for selecting the type of credentials to create

Since this is an Android application, you need to select Android Key in the next dialog. If you were to create the same application using maps on different platforms, you could create a key for each platform.

Dialog for selecting the type of key to generate

On the next screen, click Add package name and fingerprint. This provides two fields, one for adding a package name and another for adding the SHA1 from your application signing key.

For this tutorial, I will use the package name com.tutsplus.mapsdemo. To get the SHA1 signature, you need to open a terminal or command prompt and navigate to the location of your application's signing key. This can be either your release key or debug.keystore. You can generate the SHA1 with the following command:

Screenshot of a terminal output when getting an SHA1 key from a keystore

After you have created your SHA1 key and entered it into the text field, click on the blue Create button. You are then presented with a dialog containing the API key that you need to add to your Android app to access the Maps API.

Dialog presenting your Google API key

2. Setting Up the Android Project

At this point, you can create the initial Android project with the same package name that you used for creating the API key. Once your project is created, open the build.gradle file. You need to import the Play Services library for maps. In this example, you also need to import the locations Play Services library in order to set an initial position for your map. Place the following lines into the dependencies node of the build.gradle file.

Once you have your libraries imported, you can close build.gradle and open your AndroidManifest.xml file. Above the application node, you need to declare that the application uses OpenGL ES 2.0 and define the permissions needed by your application.

Note that the ACCESS_FINE_LOCATION permission is only required for this demo in order to get the user's location for defining where the map should initially display. If you have a known location in your own app, there's no need to use the user's location.

Within the application node, you need to add two pieces of metadata. The first informs the application that Play Services are used and the second binds the Maps API key with your application. In the following code snippet, @string/google_api_key is a string reference to the key from the Google Developer Console.

Once you've finished updating AndroidManifest.xml, go ahead and close the file. Next, you need to create a new Java class, called MapFragment, which extends SupportMapFragment. SupportMapFragment is used here rather than com.google.android.gms.maps.MapFragment in order to add backwards compatibility before API 12.

If your app does not need to support devices running older versions of Android, then it is fine to use com.google.android.gms.maps.MapFragment. Once you have the base fragment created, you need to implement the six interfaces that we will use for this demo.

  • ConnectionCallbacks and OnConnectionFailedListener are designed to monitor the state of the GoogleApiClient, which is used in this application for getting the user's current location.
  • OnInfoWindowClickListener is triggered when the user clicks on the info window that pops up over a marker on the map.
  • OnMapLongClickListener and OnMapClickListener are triggered when the user either taps or holds down on a portion of the map.
  • OnMarkerClickListener is called when the user clicks on a marker on the map, which typically also displays the info window for that marker.

When prompted, click on the red lightbulb that appears next to the class name to add the methods required for these interfaces.

Once you have the initial fragment built, you need to let MainActivity know that it should use this fragment. Open activity_main.xml from your resources folder and change it so that it includes the fragment as a view.

After updating your activity layout, you should be able to run your application and view a map of Earth that is fully zoomed out and focused on latitude 0, longitude 0.

What your screen should look like when Google Maps is initially set up correctly

3. Initializing the Map

Step 1: Declaring Map Types

Returning to our MapFragment class, you need to define some global values at the top of the class for use in your application.

Here mGoogleApiClient and mCurrentLocation are used for getting the user's location for initializing the map camera. MAP_TYPES and curMapTypeIndex are used in the sample code for switching between different map display types. Each of the map types serves a different purpose, so one or more may be suitable for your own applications.

GoogleMap.MAP_TYPE_SATELLITE displays a satellite view of the area without street names or labels.

Example of the Satellite map type

GoogleMap.MAP_TYPE_NORMAL shows a generic map with street names and labels.

Example of the Normal map type

GoogleMap.MAP_TYPE_HYBRID combines satellite and normal mode, displaying satellite images of an area with all labels.

Example of the Hybrid map type

GoogleMap.MAP_TYPE_TERRAIN is similar to a normal map, but textures are added to display changes in elevation in the environment. These textures are most visible when the map is angled with a two-finger drag.

Example of the Terrain map type

GoogleMap.MAP_TYPE_NONE is similar to a normal map, but doesn't display any labels or coloration for the type of environment in an area. It does allow for displaying traffic and other overlays on the map.

Example of the None map type

Step 2: Creating the API Client

Next, you need to create your GoogleApiClient and initiate LocationServices in order to get your user's current location. As I mentioned before, if you have a set location that you want to display rather than focusing on the user, you can skip using LocationServices.

The initListeners method binds the interfaces that you declared at the top of the class with the GoogleMap object associated with SupportMapFragment. This is what the implementation looks like:

You may have noticed that the GoogleApiClient and listeners are created and bound from onViewCreated rather than the typical onCreate. This is because the GoogleMap object has not been initialized when onCreate is called, so we need to wait until the view is fully created before trying to call getMap in order to avoid a NullPointerException.

Step 3: Configuring the Map

Since you will set up the map camera after the user's location has been found through Play Services, we will use the Play Services lifecycle to drive initializing our map. You can connect the GoogleApiClient in onStart. When the client has connected, you can grab the user's most recently retrieved location and use that for aiming the map camera.

In the initCamera method, you initialize the camera and some basic map properties. You start by creating a CameraPosition object through the CameraPosition.Builder, with a target set for the latitude and longitude of your user and a set zoom level.

Tilt and bearing are used here at their default values to illustrate that they are available options. Once you have a CameraPosition object, you can animate the map camera to that position using the CameraUpdateFactory.

At the end of this method, you'll notice the last four lines set some properties for the map. You set the map type, as described earlier in this tutorial, and enable live traffic flow overlays in the first two lines. setMyLocationEnabled adds a button to the top right corner of the MapFragment that automatically moves the camera to your user's location when pressed.

Finally calling setZoomControlsEnabled adds + and - buttons in the lower right corner, allowing the user to change the map zoom level without having to use gestures. There's a few more interesting things that you can set using UiSettings, such as adding a compass or disabling gestures, which you can find in the Android reference documentation.

4. Marking Locations

One of the most used map features involves indicating locations with markers. Since a latitude and longitude are needed for adding a marker, you need to use the OnMapClickListener to allow the user to pick a spot on the map to place a Marker object.

This method creates a generic red marker where the user has tapped. Additional options, such as setting a marker as draggable, can be set through the MarkerOptions object. You can find additional attributes in the official Android reference documentation. If you want to change the color of the marker, you can call BitmapDescriptorFactory.defaultMarker when adding an icon to the MarkerOptions. The defaultMarker method accepts a float value that defines the hue. The hue can either be set manually or as a predefined static value from BitmapDescriptorFactory. It should be noted that addMarker returns a Marker object, which can be stored for manually removing specific markers if needed.

Generic markers placed on the map

If you want to avoid using the generic colored pins for your location markers, you can set a bitmap as the icon on the MarkerOptions object. To demonstrate this, you override the onMapLongClick method so that it uses the app icon from the resources folder as a Marker when your user long-presses the map.

You've probably noticed that the getAddressFromLatLng method is being used in both click methods. This is a helper method that takes a LatLng and runs it through a Geocoder to get a street address. In the last two examples, we are using this method to display a street address when a marker is tapped.

Example of images used as markers

5. Drawing on the Map

The GoogleMap object has a set of methods that make it easy to draw shapes and place images onto the map. To draw a simple circle, you only need to create a CircleOptions object, set a radius and center location, and define the stroke/fill colors and size.

Once you have a CircleOptions object, you can call addCircle to draw the defined circle on top of the map. Just like when placing markers, objects that are drawn on the map return an object of the drawn item type so it can be referenced later if needed.

Illustration of a circle drawn programmatically on the map

To draw a different closed-off shape, you can take multiple LatLng points and create a PolygonOptions object. As you can see below, PolygonOptions are created in a similar fashion to CircleOptions. Instead of using a center and radius method, you use add with a list of points. You can then call addPolygon to draw the shape. For this example, you simply draw a triangle onto the map.

Example of a polygon drawn on the map

The final type of drawing you will learn about is adding an image as an overlay on the map. Overlays can be handy if you have a drawn map for an area that you want to display on top of a normal map type. This can be achieved by creating a GroundOverlayOptions with a set location, width and height, and the image that you want to use as a BitmapDescriptor.

In the following method, you draw the launcher icon for the app as an overlay on the map tiles.

Conclusion

In this tutorial, you have learned how to create an API key and enable Google Maps for Android. You also learned about the MapFragment class and some of the basic features you can activate for a map.

You've learned how to place markers, listen for interactions with the map, and how to draw on the map to display additional information.

In the next tutorial of this series, you will learn how to overlay a View over the MapFragment, how to interact with indoor level maps, and how to show a street view to your users.

2015-09-23T15:45:37.000Z2015-09-23T15:45:37.000ZPaul Trebilcox-Ruiz

How to Use FontAwesome in an Android App

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-24167

In this tutorial, I will show you how to use the FontAwesome icon pack in an Android project. FontAwesome is a great timesaver for several reasons.

First, you don't have to worry about different screen densities on different smartphones. If you want to use PNG files, you have to include in your package at least four different versions of every icon. Not only that, on some ultra-dense HD displays, your icons might look grainy. This is something you certainly want to avoid. With FontAwesome, however, you just have to include a single TTF file.

Second, you can rely on one of the most rich and complete icon sets available for free. By now, users are accustomed to the style of FontAwesome, because it's widely used on the web. You don't have to waste time looking for a set of icons that is beautiful, comprehensive, and free for commercial use. I'm not saying that these sets don't exist, because they they do, but they are quite rare.

1. How FontAwesome Works

Let's take a moment to understand how FontAwesome works. The idea behind the FontAwesome icon pack is simple, icons are treated as characters. You may have noticed that some exotic characters are treated as text. For example, you can easily copy and paste this β character or this  character. You can even do this in a simple text editor. It's also possible to change their size and color. That's because the browser—and the text editor—sees these characters as text.

FontAwesome expands upon this concept by including a wide range of icons. You can compare it to a dictionary that matches Unicode characters that cannot be typed—and that aren't used—with a specific icon.

Take a look at FontAwesome's cheatsheet to see what I'm talking about. You choose an icon from the list, take note of its Unicode character, and use it in a TextView, telling Android to render it using the FontAwesome font.

2. Import the Font File

Let's take a look at an example. Download and import the FontAwesome TrueType file into your project. You can download the FontAwesome assets from GitHub.

When you download FontAwesome, you end up with an archive that includes a number of files and folders. Most of these are useful for web projects. We are only interested in fontawesome-webfont.ttf, which is located in the fonts folder.

In your Android project, navigate to app > src > main. The main directory should include a folder named assets. If there isn't one, then create it. In the assets directory, create another folder, fonts, and add fontawesome-webfont.ttf to this folder.

Note that the fonts directory is not required. You can add the FontAwesome font file in the assets directory, but it's convenient to have files of the same type in a dedicated directory. As long as the FontAwesome font file is located in the assets directory, or a subdirectory thereof, you're good to go.

3. Create a Helper Class

Now that you've successfully included the FontAwesome font file in your Android project, it's time to use it. We will be creating a helper class to make this easier. The class we are going to use is android.graphics.Typeface. The Typeface class specifies the typeface and intrinsic style of a font. This is used to specify how text appears when drawn (and measured).

Let's start by creating the helper class. Create a new Java class and name it FontManager:

If you want to use other typefaces in your project, it's easy to add other fonts to the helper class. The idea is similar:

This is all we need to do, but we can do better. Let's push it a little bit further. Using the above method, we need to create a variable for each TextView we want to use as an icon. That's fine. But, as programmers, we are lazy. Right?

Icons are often contained in a single ViewGroup, such as a RelativeLayout or a LinearLayout. We can write a method that climbs the tree of a given XML parent and recursively overrides the typeface of each TextView it finds.

Let's assume that your layout file looks something like this:

To mark the three TextView instances as icons, we override the onCreate method and add the following code snippet:

4. Use the Icons You Want

Now comes the fun part. Visit FontAwesome's GitHub page and browse the available icons. Choose three icons you like. I'm going to pick three charts, the area chart icon, the pie chart icon, and the line chart icon.

In your project, navigate to the values folder and create a new file, icons.xml. This file will serve as a dictionary, that is, it will match the Unicode character associated with a specific icon to a human-readable name. This means that we need to create an entry for each icon. This is how it works.

You can find the code in the FontAwesome cheatsheet or on the detail page of the icon you're interested in.

The next step is to reference the string entries in the TextView instances of your layout. This is what the final result looks like:

If you open the layout editor of Android Studio, you'll see that it cannot render the icons. This isn't normal. Build and launch your application. You should now see the icons correctly rendered:

FontAwesome - First render

They're small, aren't they? It's very easy to change the size of the icons. All you need to do is change the textSize attribute. Changing the color of the icon is just as easy. Edit the textColor attribute and you're done.

FontAwesome - changed color and size

As you can see, the icons are sharp and crisp. That's because FontAwesome icons are rendered at runtime. They are vector instead of raster files.

Conclusion

In this quick tip, I showed you how to use the FontAwesome icon set in an Android project. FontAwesome is widely known, very rich, and free. The result is sharp and crisp icons, even on high resolution displays. As an added bonus, changing an icon's size or color is as simple as changing an XML attribute.

2015-09-21T15:45:54.000Z2015-09-21T15:45:54.000ZGianluca Segato

Getting Started With Google Maps for Android: Basics

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-24635

Introduction

Without a doubt, maps are one of the most useful tools for users when included in an app. This tutorial is the first in a series going over Google Maps v2 for Android. It will cover setting up the Google Maps API through the Google Developer Console, including a map fragment in your applications, displaying the user's location, adding markers, drawing on the map, and some general methods that will add utility to your app. All code for this tutorial can be found onGitHub.

1. Setting Up the Developer Console

In order to use the Google Maps API, you must register your application on the Google Developer Console and enable the API. To do this, start by going to the Google Developer Console. If you already have a project created, you can skip the next section. If not, you can follow along and create a new project for your maps application.

Step 1: Creating a Project

To create a new project, click on the blue Create Project button in the top left corner of the screen. If you don't see a Create Project button, then look for a button labeled Create an empty project.

Create a project button

This presents you with a dialog that asks for a project name. For this tutorial, I have created a project called TutsPlusMaps. There are some restrictions on what you can name your project as only letters, numbers, quotes, hyphens, spaces, and exclamation points are allowed characters.

Creating a project dialog window

Once you hit Create, a dialog appears in the lower right corner of the page with a loading indicator while the project is being created.

Step 2: Enabling the Maps API

When the project has been created, or you have selected an existing project, you are taken to the project Overview screen. From here you will want to expand the APIs & auth item in the left navigation panel and click on APIs.

APIs  Auth location in nav

While there's a search box on this screen, you'll notice that Google placed the Maps API items at the top of the center column for developers to access. For this tutorial, click on the item titled Google Maps Android API under the Google Maps APIs heading.

Google Maps API item

This takes you to a screen where you can click on the blue Enable API button in order to enable the Maps API for your project.

Enable API button

Step 3: Creating an Android API Key

After you've enabled the Maps API, click on the Credentials item under APIs & auth in the side navigation to get a key to access the Maps API in your application. When you are presented with the Credentials dialog, press the blue Add Credentials button and select API Key.

Dialog for selecting the type of credentials to create

Since this is an Android application, you need to select Android Key in the next dialog. If you were to create the same application using maps on different platforms, you could create a key for each platform.

Dialog for selecting the type of key to generate

On the next screen, click Add package name and fingerprint. This provides two fields, one for adding a package name and another for adding the SHA1 from your application signing key.

For this tutorial, I will use the package name com.tutsplus.mapsdemo. To get the SHA1 signature, you need to open a terminal or command prompt and navigate to the location of your application's signing key. This can be either your release key or debug.keystore. You can generate the SHA1 with the following command:

Screenshot of a terminal output when getting an SHA1 key from a keystore

After you have created your SHA1 key and entered it into the text field, click on the blue Create button. You are then presented with a dialog containing the API key that you need to add to your Android app to access the Maps API.

Dialog presenting your Google API key

2. Setting Up the Android Project

At this point, you can create the initial Android project with the same package name that you used for creating the API key. Once your project is created, open the build.gradle file. You need to import the Play Services library for maps. In this example, you also need to import the locations Play Services library in order to set an initial position for your map. Place the following lines into the dependencies node of the build.gradle file.

Once you have your libraries imported, you can close build.gradle and open your AndroidManifest.xml file. Above the application node, you need to declare that the application uses OpenGL ES 2.0 and define the permissions needed by your application.

Note that the ACCESS_FINE_LOCATION permission is only required for this demo in order to get the user's location for defining where the map should initially display. If you have a known location in your own app, there's no need to use the user's location.

Within the application node, you need to add two pieces of metadata. The first informs the application that Play Services are used and the second binds the Maps API key with your application. In the following code snippet, @string/google_api_key is a string reference to the key from the Google Developer Console.

Once you've finished updating AndroidManifest.xml, go ahead and close the file. Next, you need to create a new Java class, called MapFragment, which extends SupportMapFragment. SupportMapFragment is used here rather than com.google.android.gms.maps.MapFragment in order to add backwards compatibility before API 12.

If your app does not need to support devices running older versions of Android, then it is fine to use com.google.android.gms.maps.MapFragment. Once you have the base fragment created, you need to implement the six interfaces that we will use for this demo.

  • ConnectionCallbacks and OnConnectionFailedListener are designed to monitor the state of the GoogleApiClient, which is used in this application for getting the user's current location.
  • OnInfoWindowClickListener is triggered when the user clicks on the info window that pops up over a marker on the map.
  • OnMapLongClickListener and OnMapClickListener are triggered when the user either taps or holds down on a portion of the map.
  • OnMarkerClickListener is called when the user clicks on a marker on the map, which typically also displays the info window for that marker.

When prompted, click on the red lightbulb that appears next to the class name to add the methods required for these interfaces.

Once you have the initial fragment built, you need to let MainActivity know that it should use this fragment. Open activity_main.xml from your resources folder and change it so that it includes the fragment as a view.

After updating your activity layout, you should be able to run your application and view a map of Earth that is fully zoomed out and focused on latitude 0, longitude 0.

What your screen should look like when Google Maps is initially set up correctly

3. Initializing the Map

Step 1: Declaring Map Types

Returning to our MapFragment class, you need to define some global values at the top of the class for use in your application.

Here mGoogleApiClient and mCurrentLocation are used for getting the user's location for initializing the map camera. MAP_TYPES and curMapTypeIndex are used in the sample code for switching between different map display types. Each of the map types serves a different purpose, so one or more may be suitable for your own applications.

GoogleMap.MAP_TYPE_SATELLITE displays a satellite view of the area without street names or labels.

Example of the Satellite map type

GoogleMap.MAP_TYPE_NORMAL shows a generic map with street names and labels.

Example of the Normal map type

GoogleMap.MAP_TYPE_HYBRID combines satellite and normal mode, displaying satellite images of an area with all labels.

Example of the Hybrid map type

GoogleMap.MAP_TYPE_TERRAIN is similar to a normal map, but textures are added to display changes in elevation in the environment. These textures are most visible when the map is angled with a two-finger drag.

Example of the Terrain map type

GoogleMap.MAP_TYPE_NONE is similar to a normal map, but doesn't display any labels or coloration for the type of environment in an area. It does allow for displaying traffic and other overlays on the map.

Example of the None map type

Step 2: Creating the API Client

Next, you need to create your GoogleApiClient and initiate LocationServices in order to get your user's current location. As I mentioned before, if you have a set location that you want to display rather than focusing on the user, you can skip using LocationServices.

The initListeners method binds the interfaces that you declared at the top of the class with the GoogleMap object associated with SupportMapFragment. This is what the implementation looks like:

You may have noticed that the GoogleApiClient and listeners are created and bound from onViewCreated rather than the typical onCreate. This is because the GoogleMap object has not been initialized when onCreate is called, so we need to wait until the view is fully created before trying to call getMap in order to avoid a NullPointerException.

Step 3: Configuring the Map

Since you will set up the map camera after the user's location has been found through Play Services, we will use the Play Services lifecycle to drive initializing our map. You can connect the GoogleApiClient in onStart. When the client has connected, you can grab the user's most recently retrieved location and use that for aiming the map camera.

In the initCamera method, you initialize the camera and some basic map properties. You start by creating a CameraPosition object through the CameraPosition.Builder, with a target set for the latitude and longitude of your user and a set zoom level.

Tilt and bearing are used here at their default values to illustrate that they are available options. Once you have a CameraPosition object, you can animate the map camera to that position using the CameraUpdateFactory.

At the end of this method, you'll notice the last four lines set some properties for the map. You set the map type, as described earlier in this tutorial, and enable live traffic flow overlays in the first two lines. setMyLocationEnabled adds a button to the top right corner of the MapFragment that automatically moves the camera to your user's location when pressed.

Finally calling setZoomControlsEnabled adds + and - buttons in the lower right corner, allowing the user to change the map zoom level without having to use gestures. There's a few more interesting things that you can set using UiSettings, such as adding a compass or disabling gestures, which you can find in the Android reference documentation.

4. Marking Locations

One of the most used map features involves indicating locations with markers. Since a latitude and longitude are needed for adding a marker, you need to use the OnMapClickListener to allow the user to pick a spot on the map to place a Marker object.

This method creates a generic red marker where the user has tapped. Additional options, such as setting a marker as draggable, can be set through the MarkerOptions object. You can find additional attributes in the official Android reference documentation. If you want to change the color of the marker, you can call BitmapDescriptorFactory.defaultMarker when adding an icon to the MarkerOptions. The defaultMarker method accepts a float value that defines the hue. The hue can either be set manually or as a predefined static value from BitmapDescriptorFactory. It should be noted that addMarker returns a Marker object, which can be stored for manually removing specific markers if needed.

Generic markers placed on the map

If you want to avoid using the generic colored pins for your location markers, you can set a bitmap as the icon on the MarkerOptions object. To demonstrate this, you override the onMapLongClick method so that it uses the app icon from the resources folder as a Marker when your user long-presses the map.

You've probably noticed that the getAddressFromLatLng method is being used in both click methods. This is a helper method that takes a LatLng and runs it through a Geocoder to get a street address. In the last two examples, we are using this method to display a street address when a marker is tapped.

Example of images used as markers

5. Drawing on the Map

The GoogleMap object has a set of methods that make it easy to draw shapes and place images onto the map. To draw a simple circle, you only need to create a CircleOptions object, set a radius and center location, and define the stroke/fill colors and size.

Once you have a CircleOptions object, you can call addCircle to draw the defined circle on top of the map. Just like when placing markers, objects that are drawn on the map return an object of the drawn item type so it can be referenced later if needed.

Illustration of a circle drawn programmatically on the map

To draw a different closed-off shape, you can take multiple LatLng points and create a PolygonOptions object. As you can see below, PolygonOptions are created in a similar fashion to CircleOptions. Instead of using a center and radius method, you use add with a list of points. You can then call addPolygon to draw the shape. For this example, you simply draw a triangle onto the map.

Example of a polygon drawn on the map

The final type of drawing you will learn about is adding an image as an overlay on the map. Overlays can be handy if you have a drawn map for an area that you want to display on top of a normal map type. This can be achieved by creating a GroundOverlayOptions with a set location, width and height, and the image that you want to use as a BitmapDescriptor.

In the following method, you draw the launcher icon for the app as an overlay on the map tiles.

Conclusion

In this tutorial, you have learned how to create an API key and enable Google Maps for Android. You also learned about the MapFragment class and some of the basic features you can activate for a map.

You've learned how to place markers, listen for interactions with the map, and how to draw on the map to display additional information.

In the next tutorial of this series, you will learn how to overlay a View over the MapFragment, how to interact with indoor level maps, and how to show a street view to your users.

2015-09-23T15:45:37.000Z2015-09-23T15:45:37.000ZPaul Trebilcox-Ruiz

An Introduction to tvOS Development

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-24848

Introduction

At their annual September event for 2015, in addition to new iPhone and iPad models, Apple announced their long-awaited update to the Apple TV set-top box. This new, fourth generation Apple TV includes a powerful A8 processor, a Siri-enabled remote, a revamped user interface and, most importantly, a brand new platform for third party applications and games, which Apple has named tvOS.

In this tutorial, I am going to introduce you to tvOS development by creating a basic tvOS application. This tutorial requires that you are running Xcode 7.1 or later, which includes support for tvOS. I am also assuming that you are already familiar with iOS development.

1. Project Setup

Open up Xcode and create a new project. You'll immediately notice that the list of templates includes a section for tvOS applications. From the available templates, choose tvOS > Application > Single View Application.

Project Template

Click Next and configure the project as shown below. I have opted for Swift as the project's language, but you can also use Objective-C to develop tvOS applications.

Project Settings

To finish setting up the project, tell Xcode where you'd like to save the project. The first thing you'll notice is that the project is structured almost identically to a regular iOS application. In the below screenshot, you can see that we have AppDelegate.swiftViewController.swift, and Main.storyboard.

tvOS App Structure

2. Building the Interface

The first major difference you will notice when working with tvOS is building the user interface of your app. When you open Main.storyboard, you will see a large, blank Apple TV screen. If you can't see the entire screen in the editor, then press Command-- to zoom out.

Blank Apple TV Interface

This screen is significantly larger because of the way tvOS apps are scaled. In modern iOS development, interface layout is handled by the use of points rather than pixels in order to make development easier on devices with Retina Displays.

For example, the iPhone 6 and iPhone 6s have a screen resolution of 1334x750, but only a screen size, in points, of 667x375. This means that all apps on the device run at a 2x scale. All of Apple's iOS devices that have a Retina Display run at a 2x scale, except for the iPhone 6 Plus and iPhone 6s Plus, which run at a 3x scale.

The new Apple TV, however, runs apps at a standard 1920x1080 resolution at a 1x scale. This means that, when building tvOS apps, the screen size, in points, that you must use when building your interface is also 1920x1080.

Now that you know how tvOS apps are scaled and displayed on the screen, we can start building our first interface. From the Object Library on the right, drag in a Button to the right hand side of your blank screen. With the button selected, at the bottom of your storyboard editor, click the Pin button and add the following constraints.

Pin Button
Button constraints

Next, drag in a Table View to the left of the button and add the following constraints. Also make sure that the Update Frames option down the bottom is set to All Frames in Container. Take a look at the below screenshot for clarification.

Table View Constraints

Select your table view, open the Size Inspector, and set the Row Height property to 88 as shown below.

Row Height

Next, drag in a Table View Cell from the Object Library and add it to the table view. With the table view cell selected, open the Attributes Inspector and change the Style property to Subtitle.

Cell Style

Finally, press Control on your keyboard and drag from your table view to your view controller to set the view controller as the table view's data source and delegate. You can also do this using the Connections inspector on the right.

Data Source and Delegate

By building this tvOS interface, you will see that it is almost identical to building an iOS interface with the major difference being the significantly larger scale of items.

3. Understanding Focus

Let's now focus on some code. Open ViewController.swift and replace the implementation of the ViewController class with the following.

If you are familiar with iOS development, then the above implementation should look very familiar. You are now ready to run your very first tvOS application. Press Command-R or click the run button in the top left. Make sure that your test device is set to Apple TV 1080p.

Target Device

Once the Apple TV Simulator has booted up and your application is launched, you should see the following screen:

tvOS Application

Congratulations! You now have your very first tvOS app up and running. In order to control the app, you need to use the new Apple TV remote. To bring up the remote in the simulator, select Hardware > Show Apple TV Remote from the menu or press ⌘Command+Shift+R.

Show Apple TV Remote

A small remote window should open up next to your simulator window. Play around with the remote by holding the Option button on your keyboard and moving your mouse cursor over the remote. You will see that, as you move your mouse cursor up and down, the selection in the table view changes.

Table item selected

Likewise, when you swipe to the right, the button on the right becomes selected.

Button selected

In tvOS development, this is called changing the current focus item. Unlike iOS apps where users can tap anywhere on the screen at any given time, tvOS apps use a point-and-click style of interaction.

You do not need to do any extra work as a developer in order to have your interface elements be focusable in a logical order. The focus engine built into the UIKit framework on tvOS looks at the layout of your interface and handles all of the work in moving the focus from one item to another.

There are, however, many new methods and properties made available to you to programmatically control the way focus is handled within your app. Many of these are defined by the UIFocusEnvironment protocol, which the UIViewControllerUIViewUIWindow, and UIPresentationController classes automatically conform to. There are also multiple methods contained in the tvOS versions of the UITableViewDelegate and UICollectionViewDelegate protocols that can be used to control the focus within your app.

As an example, we are going to make the button on the right the default focus item. If you run the app now, you will see that the first item of the table is initially in focus. We are also going to disable the second item in the table view from being focusable. Add the following code snippet to the implementation of the ViewController class:

We first override the preferredFocusedView property and return the first subview, which currently is the button on the right. The preferredFocusedView property is read-only and can only be set by overriding its implementation as we have done. When the view controller is loaded, the focus engine will find the view returned by this property and automatically puts it in focus.

We have also implemented the tableView(_:canFocusRowAtIndexPath:) method and return false when the indexPath.row is equal to 1. Otherwise we return true. As you would expect, this delegate method determines whether or not a specific row can be in focus.

When you build and run your app again, you will see that the button on the right automatically receives focus at launch. If the button on the right doesn't automatically receive focus, then your app's view hierarchy may be slightly different, that is, the first subview of the view controller's view isn't equal to the button on the right.

You will also notice that when you try to navigate the rows of the table view, the middle row is skipped as dictated by the implementation of the tableView(_:canFocusRowAtIndexPath:) method.

4. tvOS App Components and Limitations

While we won't be creating any images in this tutorial, it is important that you understand the different components that are required for tvOS apps as well as some of the limitations.

App Icons

Every tvOS app must provide two app icons:

  • Large: 1280px x 768px
  • Small: 400px x 240px

The main difference with iOS is that tvOS app icons can be composed of up to three layers. This is so that a parallax effect can be achieved on the home screen and anywhere else your app icon appears. If you want to see this effect for yourself, go to the Apple TV Simulator, press the Home button on the remote (the small TV icon). Focus the Settings app icon and hold the Option key while moving the mouse cursor around a little bit on the remote. You will see that the app icon responds to your movement and the different layers of the icon produce a nice effect.

Launch Image

Just like a regular iOS application, you must provide a static image to be displayed once your app has been opened and is loading. The main difference is that you only need to provide a single 1920px x 1080px image.

Top Shelf Images

If your app has been placed in the Top Shelf by a user, when focussed, you can display content right on the home screen of the Apple TV. There are three main types of content you can display:

  • Static Image: This is just a 1920px x 720px image that you provide in your application bundle.
  • Dynamic Content Layouts: This is where you display a series of images in an interface similar to a collection view. These images can be selected by your app at any time and do not have to be included in the application bundle. The three image sizes you can use are 404px x 608px, 608px x 608px, and 908px x 512px. Any combination of these three sizes can be used.
  • Scrolling Banner: This is where you provide a set of wide aspect ratio images to display next to each other with one taking up the majority of the screen. This content type is similar to the home page of the iOS App Store. These images need to be 1940px x 624px in size.

Limitations

Despite the new Apple TV packing more storage than most iPhone devices with a minimum capacity of 32GB, there are some important limitations for tvOS applications. Firstly, apps can be no more than 200MB in size. Any content you need outside of this 200MB buffer will need to be downloaded using the On-Demand Resources API introduced with iOS 9 and now tvOS.

Another thing you also need to be aware of is that tvOS apps have no persistent local storage. This means that any data that you need to retain between app launches, such as game saves, photos and videos, will need to be stored in iCloud and retrieved when needed.

Conclusion

While we haven't written much code in this tutorial, I hope that it served as a good introduction to the tvOS platform. You now know the key similarities and differences between developing apps for iOS and tvOS as well as the limitations imposed on developers.

In future tutorials, we will be diving deeper into tvOS and discovering what is possible with tvOS and the new Apple TV.

As always, leave your comments and feedback in the comments below.

2015-09-25T15:15:57.000Z2015-09-25T15:15:57.000ZDavis Allie

Create a Mobile App Using Famo.us and Angular

$
0
0

I love high-performance JavaScript, and I love sharing what I believe is its true potential. In this tutorial, I want to focus on Famo.us, which can allow you to maintain a silky-smooth 60 frames per second while having fluid animations on screen. 

Famo.us does this by utilizing the CSS3 primitive -webkit-transform: matrix3d, which lets the framework compute the composite matrix and skip the browser’s renderer. No plug-in, no download, no hack. By appending this to each DIV, developers can render the composite matrix and go straight to the GPU.

I go more in-depth when discussing the ins and outs of Famo.us in this blogpost. Thanks to Zack Brown for all of his assistance with this! Let’s get started.

By the end of this project you will be able to:

  • understand how Angular works within the context of a Famo.us application
  • harness the true power of JavaScript and the good parts of HTML5
  • create smooth animations

My goal for this project is to illustrate how easily you can create HTML5 and JavaScript projects that work at near-native speeds on mobile applications.

Features

  • The mobile application runs on iOS and Android via Cordova.
  • The Windows 10 universal app runs natively on, well, Windows 10.
  • This project can also be run as a hosted website, although I have it scaled which is best for mobile devices.

Requirements

  • PC or Mac
  • Web server
  • Cross-platform test matrix (like a BrowserStack, IDE, or free virtual machines for EdgeHTML, the rendering engine for Microsoft Edge and hosted web app content on Windows 10)

Setup

  1. Download the source from GitHub.
  2. Download and install a web server (I use MAMP on OS X, or the built-in IIS server with Visual Studio on Windows).

Open the Project

  1. Start your web server.
  2. Navigate to famous-angular-Pokemon/app/.

The project is designed to work on mobile devices, so use the mobile emulator in your browser to get the correct view. Here's what it would look like on an iPhone 6 inside the emulator via the Chrome desktop browser (375x667):

Mobile app were creating displayed on iPhone 6 emulator

How It Works

Hitting the Database

I pull all of the information from the PokeAPI, which has a well-documented API, but it's missing images for each of the Pokémon. For the images, I just pull the name of the currently chosen Pokémon and append it to the end of this URL: http://img.pokemondb.net/artwork/. For example: http://img.pokemondb.net/artwork/venusaur.jpg will lead you to an image of Vanosaur. Nifty, right? Sadly, they do not have an API available.

Each time the user presses the Next button, a random number is generated between a min/max value that I've defined (say, 1 to 20), and it pulls a Pokémon from the database that matches that number. Here's what it looks like:

http://pokeapi.co/api/v1/pokemon/1/ returns a JSON object for Bulbasaur. You can play with their API.

Looping Through the Data

I then loop through that JSON object and set the properties I find to variables in Angular, using the $Scope object.

Here's an example:

You may notice that I also have a few other functions here, such as capitalizeFirstLetter, which does exactly that. I wanted the abilities and type (e.g. poison, grass, flying) to have the first letter capitalized, since they come back from the database in all lowercase characters.

I also loop through the abilities and push them to an ability object, which looks like this:

The database also returns multiple types for certain Pokémon, such as Charizard, who is flying as well as fire. To keep things simple, though, I only wanted to return one from the database.

Drawing It to the Screen

Famo.us has two waves of drawing content to the screen by creating surfaces, which are the elements that contain your text, images, etc.:

  • JavaScript
  • FA-Directives (HTML)

I didn't use JavaScript to draw the surfaces in this app. Instead I chose to use only FA (Famous-Angular) Directives, such as:

This is for the name above the Pokémon on the front screen.

You'll notice that the surface is wrapped by a fa-modifier. You can read about those in the Famo.us documentation, but they essentially adjust the properties of a surface, such as alignment, size, and origin. It took me a while to wrap my head around the difference between alignment and origin, so here's how I came to understand it.

Origin 

This is the reference point on any surface. If I want to draw a rectangle and move it around the screen, I need to decide which point on that rectangle will be my starting point. The Famo.us docs explain it well. The values are laid out as follows:

Alignment

This is a surface's location on the screen. When you make changes to the alignment, it is using the origin as the reference point to start from.

Where Angular Finally Comes In

Now here's where you can put all of your Angular skills and data binding to work with the Angular implementation. If you're already experienced with Angular, then it's not radically different here.

This button appears on the first screen and simply pulls another Pokémon from the database. All of the ng (Angular) directives you are familiar with are here, such as ng-click. I have multiple functions here. Notice that they are not comma-separated.

I am also binding the value of $scope.nextBtn to {{nextBTn}} in HTML.

To allow Famo.us and Angular to work together, we need to include $Famo.us at the top of our JavaScript file. Here's how you do it:

Animations

What would a high-performance app be without animations? Famo.us is packed with them, which makes it easy to get started. Here's one for animating the image on the front.

There are several curve types you can use here. Checkout the docs for more info. I'm also using a callback function, returnToOrigSize, to have the image grow and then shrink back to the original size.

Points of Frustration

I ran into a few issues along the way.

FA-Directives Have Their Properties Set as Strings

If you have a spelling error, the app will just use the default values for that property. This snagged me several times, which is why you see I set all of my properties as an object, such as align.frontName, to make it easier to read.

Adding Classes

In FA-Directives you add multiple classes as strings and they are not comma-separated.

If you try to add classes by creating surfaces in JavaScript, you pass in an array of strings.

It took me a while to understand that, as I only found the solution in thisthread.

Famo.us + Angular Seems to Be Deprecated (For Now)

Midway through this project, I saw that Famo.us was working on an improved version of the framework that includes Mixed Mode. Famo.us + Angular doesn't take advantage of these additions (yet) at least. That doesn't mean FA is going anywhere, as it works perfectly fine—it's just that you won't be getting the latest features.

Resources

More Hands-On With JavaScript

This article is part of the web development series from Microsoft tech evangelists on practical JavaScript learning, open-source projects, and interoperability best practices, including Microsoft Edge browser and the new EdgeHTML rendering engine

We encourage you to test across browsers and devices including Microsoft Edge—the default browser for Windows 10—with free tools on dev.modern.IE:

In-depth tech learning on Microsoft Edge and the Web Platform from our engineers and evangelists:

More free cross-platform tools and resources for the web platform:

2015-09-25T16:15:50.000Z2015-09-25T16:15:50.000ZDavid Voyles

Create a Mobile App Using Famo.us and Angular

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-24721

I love high-performance JavaScript, and I love sharing what I believe is its true potential. In this tutorial, I want to focus on Famo.us, which can allow you to maintain a silky-smooth 60 frames per second while having fluid animations on screen. 

Famo.us does this by utilizing the CSS3 primitive -webkit-transform: matrix3d, which lets the framework compute the composite matrix and skip the browser’s renderer. No plug-in, no download, no hack. By appending this to each DIV, developers can render the composite matrix and go straight to the GPU.

I go more in-depth when discussing the ins and outs of Famo.us in this blogpost. Thanks to Zack Brown for all of his assistance with this! Let’s get started.

By the end of this project you will be able to:

  • understand how Angular works within the context of a Famo.us application
  • harness the true power of JavaScript and the good parts of HTML5
  • create smooth animations

My goal for this project is to illustrate how easily you can create HTML5 and JavaScript projects that work at near-native speeds on mobile applications.

Features

  • The mobile application runs on iOS and Android via Cordova.
  • The Windows 10 universal app runs natively on, well, Windows 10.
  • This project can also be run as a hosted website, although I have it scaled which is best for mobile devices.

Requirements

  • PC or Mac
  • Web server
  • Cross-platform test matrix (like a BrowserStack, IDE, or free virtual machines for EdgeHTML, the rendering engine for Microsoft Edge and hosted web app content on Windows 10)

Setup

  1. Download the source from GitHub.
  2. Download and install a web server (I use MAMP on OS X, or the built-in IIS server with Visual Studio on Windows).

Open the Project

  1. Start your web server.
  2. Navigate to famous-angular-Pokemon/app/.

The project is designed to work on mobile devices, so use the mobile emulator in your browser to get the correct view. Here's what it would look like on an iPhone 6 inside the emulator via the Chrome desktop browser (375x667):

Mobile app were creating displayed on iPhone 6 emulator

How It Works

Hitting the Database

I pull all of the information from the PokeAPI, which has a well-documented API, but it's missing images for each of the Pokémon. For the images, I just pull the name of the currently chosen Pokémon and append it to the end of this URL: http://img.pokemondb.net/artwork/. For example: http://img.pokemondb.net/artwork/venusaur.jpg will lead you to an image of Vanosaur. Nifty, right? Sadly, they do not have an API available.

Each time the user presses the Next button, a random number is generated between a min/max value that I've defined (say, 1 to 20), and it pulls a Pokémon from the database that matches that number. Here's what it looks like:

http://pokeapi.co/api/v1/pokemon/1/ returns a JSON object for Bulbasaur. You can play with their API.

Looping Through the Data

I then loop through that JSON object and set the properties I find to variables in Angular, using the $Scope object.

Here's an example:

You may notice that I also have a few other functions here, such as capitalizeFirstLetter, which does exactly that. I wanted the abilities and type (e.g. poison, grass, flying) to have the first letter capitalized, since they come back from the database in all lowercase characters.

I also loop through the abilities and push them to an ability object, which looks like this:

The database also returns multiple types for certain Pokémon, such as Charizard, who is flying as well as fire. To keep things simple, though, I only wanted to return one from the database.

Drawing It to the Screen

Famo.us has two waves of drawing content to the screen by creating surfaces, which are the elements that contain your text, images, etc.:

  • JavaScript
  • FA-Directives (HTML)

I didn't use JavaScript to draw the surfaces in this app. Instead I chose to use only FA (Famous-Angular) Directives, such as:

This is for the name above the Pokémon on the front screen.

You'll notice that the surface is wrapped by a fa-modifier. You can read about those in the Famo.us documentation, but they essentially adjust the properties of a surface, such as alignment, size, and origin. It took me a while to wrap my head around the difference between alignment and origin, so here's how I came to understand it.

Origin 

This is the reference point on any surface. If I want to draw a rectangle and move it around the screen, I need to decide which point on that rectangle will be my starting point. The Famo.us docs explain it well. The values are laid out as follows:

Alignment

This is a surface's location on the screen. When you make changes to the alignment, it is using the origin as the reference point to start from.

Where Angular Finally Comes In

Now here's where you can put all of your Angular skills and data binding to work with the Angular implementation. If you're already experienced with Angular, then it's not radically different here.

This button appears on the first screen and simply pulls another Pokémon from the database. All of the ng (Angular) directives you are familiar with are here, such as ng-click. I have multiple functions here. Notice that they are not comma-separated.

I am also binding the value of $scope.nextBtn to {{nextBTn}} in HTML.

To allow Famo.us and Angular to work together, we need to include $Famo.us at the top of our JavaScript file. Here's how you do it:

Animations

What would a high-performance app be without animations? Famo.us is packed with them, which makes it easy to get started. Here's one for animating the image on the front.

There are several curve types you can use here. Checkout the docs for more info. I'm also using a callback function, returnToOrigSize, to have the image grow and then shrink back to the original size.

Points of Frustration

I ran into a few issues along the way.

FA-Directives Have Their Properties Set as Strings

If you have a spelling error, the app will just use the default values for that property. This snagged me several times, which is why you see I set all of my properties as an object, such as align.frontName, to make it easier to read.

Adding Classes

In FA-Directives you add multiple classes as strings and they are not comma-separated.

If you try to add classes by creating surfaces in JavaScript, you pass in an array of strings.

It took me a while to understand that, as I only found the solution in thisthread.

Famo.us + Angular Seems to Be Deprecated (For Now)

Midway through this project, I saw that Famo.us was working on an improved version of the framework that includes Mixed Mode. Famo.us + Angular doesn't take advantage of these additions (yet) at least. That doesn't mean FA is going anywhere, as it works perfectly fine—it's just that you won't be getting the latest features.

Resources

More Hands-On With JavaScript

This article is part of the web development series from Microsoft tech evangelists on practical JavaScript learning, open-source projects, and interoperability best practices, including Microsoft Edge browser and the new EdgeHTML rendering engine

We encourage you to test across browsers and devices including Microsoft Edge—the default browser for Windows 10—with free tools on dev.modern.IE:

In-depth tech learning on Microsoft Edge and the Web Platform from our engineers and evangelists:

More free cross-platform tools and resources for the web platform:

2015-09-25T16:15:50.000Z2015-09-25T16:15:50.000ZDavid Voyles

Reading QR Codes Using the Mobile Vision API

$
0
0

Introduction

QR codes have become ubiquitous in recent years. I am sure you’ve seen one in a newspaper advertisement or on a billboard. In layman’s terms, QR codes, like all other barcodes, are images that are designed to be read by machines. Usually, they represent a small string, such as a shortened URL or a phone number. Here is a sample QR code that contains the URL of the Tuts+ homepage:

Tuts+ URL as a QR code

Unlike traditional barcodes, which need specialized hardware, QR codes can be read accurately by any smartphone with a decent camera.

The latest release of the Google Play services SDK includes the mobile vision API which, among other things, makes it very easy for Android developers to create apps capable of detecting and reading QR codes in real time. In this tutorial, I am going to help you get started with it.

Prerequisites

To follow this tutorial, you will need:

1. Installing the Google Play Services SDK

Before you use the mobile vision API in your app, you should add the Google Play services SDK 7.8 as a compile dependency in your app module’s build.gradle.

When you press the Sync Now button, you will see an error that looks like this:

Install repository error

Click the Install repository and sync project link to install the SDK.

2. Editing the App Manifest

Add the following line to your app’s AndroidManifest.xml to automatically install the barcode detection libraries on the devices that try to run your app:

Additionally, as you will be using the device’s camera to capture the QR codes, you should request the android.permission.CAMERA permission.

3. Reading a QR Code From a Photo

Let’s now write some code that can read a QR code from a photo stored in your app’s assets folder. I’m going to name the photo myqrcode.jpg. If you don’t have any photos containing QR codes handy, you can get some from Flickr.

Step 1: Convert the Photo Into a Bitmap

Because the mobile vision API needs a Bitmap as its input, you should first convert your photo into a Bitmap. To do so, open the photo using the open method of the AssetManager class and pass the InputStream returned to the decodeStream method of BitmapFactory. To keep it simple, do it inside the onCreate method of your Activity.

Step 2: Create a Barcode Detector

To detect QR codes(and other types of barcodes), you should use an instance of the BarcodeDetector class. The following code shows you how to create one using BarcodeDetector.Builder:

Note that the detector will, by default, detect barcodes of all supported formats. I have used the setBarcodeFormats method to explicitly specify that the detector should only detect QR codes.

Step 3: Read the QR Code

Use Frame.Builder to create a Frame using the Bitmap you created earlier.

Call the detect method of the BarcodeDetector to generate a SparseArray containing all the QR codes the BarcodeDetector detected in your photo.

Each item of the SparseArray contains a Barcode object. To fetch the raw contents of the QR code, you can use the Barcode object’s rawValue field. However, I suggest you use the easier to read displayValue field instead. Here’s some code that prints the contents of the first QR code the API detected:

If you run your Activity now, you should be able to see the message contained in your photo’s QR code.

4. Reading a QR Code Using the Camera

The mobile vision API also makes it very easy for you to detect and read barcodes using your device’s camera in real time. Let’s create a new Activity that does just that.

Step 1: Define the Layout

Create a new layout XML file called activity_main.xml. The layout should have a SurfaceView in order to display the preview frames captured by the camera. If you want, you can also add a TextView to display the contents of the QR codes the API detects.

After using a RelativeLayout to position both widgets, the layout XML file should look something like this:

Step 2: Create the Activity

Create a new Java class called MainActivity.java. Make it a subclass of Activity and override its onCreate method. Inside the onCreate method, call setContentView to apply the layout you created in the previous step. Next, use findViewById to get references to the widgets defined in the layout.

To fetch a stream of images from the device’s camera and display them in the SurfaceView, create a new instance of the CameraSource class using CameraSource.Builder. Because the CameraSource needs a BarcodeDetector, create one using the BarcodeDetector.Builder class. If you want, you can adjust the dimensions of the camera preview using the setRequestedPreviewSize method.

Next, add a callback to the SurfaceHolder of the SurfaceView so that you know when you can start drawing the preview frames. The callback should implement the SurfaceHolder.Callback interface.

Inside the surfaceCreated method, call the start method of the CameraSource to start drawing the preview frames. Because the start method expects you to handle an IOException, you should call it from inside a try...catch block.

Similarly, inside the surfaceDestroyed method, call the stop method of the CameraSource to stop drawing the preview frames.

Your Activity is almost ready. However, you still need to tell the BarcodeDetector what it should do when it detects a QR code. Create an instance of a class that implements the Detector.Processor interface and pass it to the setProcessor method of the BarcodeDetector. Android Studio will automatically generate stubs for the methods of the interface.

Inside the receiveDetections method, get the SparseArray of Barcode objects by calling the getDetectedItems method of the Detector.Detections class. You can now write the code to do something with the detected QR codes, because I have already shown you how to work with SpareArray objects earlier in this tutorial.

Here’s how you can display the QR code’s displayValue in the TextView:

Note that you should embed the call to the setText method inside a call to the post method of the TextView, because receiveDetections does not run on the UI thread. Failing to do so will lead to a runtime error.

You can now compile and run your app. Point your device’s camera to a QR code and you should be able to see the QR code’s contents immediately.

Real time detection

Conclusion

In this tutorial, you learned how to use the mobile vision API to read QR codes from static images as well as from live camera streams. Even though we only worked with QR codes in this tutorial, you can also use the API to read other popular barcode formats such as UPC-A and EAN-13.

To learn more about the mobile vision API, I recommend visiting the API’s documentation.

2015-09-28T16:45:01.000Z2015-09-28T16:45:01.000ZAshraff Hathibelagal

Reading QR Codes Using the Mobile Vision API

$
0
0
tag:code.tutsplus.com,2005:PostPresenter/cms-24680

Introduction

QR codes have become ubiquitous in recent years. I am sure you’ve seen one in a newspaper advertisement or on a billboard. In layman’s terms, QR codes, like all other barcodes, are images that are designed to be read by machines. Usually, they represent a small string, such as a shortened URL or a phone number. Here is a sample QR code that contains the URL of the Tuts+ homepage:

Tuts+ URL as a QR code

Unlike traditional barcodes, which need specialized hardware, QR codes can be read accurately by any smartphone with a decent camera.

The latest release of the Google Play services SDK includes the mobile vision API which, among other things, makes it very easy for Android developers to create apps capable of detecting and reading QR codes in real time. In this tutorial, I am going to help you get started with it.

Prerequisites

To follow this tutorial, you will need:

1. Installing the Google Play Services SDK

Before you use the mobile vision API in your app, you should add the Google Play services SDK 7.8 as a compile dependency in your app module’s build.gradle.

When you press the Sync Now button, you will see an error that looks like this:

Install repository error

Click the Install repository and sync project link to install the SDK.

2. Editing the App Manifest

Add the following line to your app’s AndroidManifest.xml to automatically install the barcode detection libraries on the devices that try to run your app:

Additionally, as you will be using the device’s camera to capture the QR codes, you should request the android.permission.CAMERA permission.

3. Reading a QR Code From a Photo

Let’s now write some code that can read a QR code from a photo stored in your app’s assets folder. I’m going to name the photo myqrcode.jpg. If you don’t have any photos containing QR codes handy, you can get some from Flickr.

Step 1: Convert the Photo Into a Bitmap

Because the mobile vision API needs a Bitmap as its input, you should first convert your photo into a Bitmap. To do so, open the photo using the open method of the AssetManager class and pass the InputStream returned to the decodeStream method of BitmapFactory. To keep it simple, do it inside the onCreate method of your Activity.

Step 2: Create a Barcode Detector

To detect QR codes(and other types of barcodes), you should use an instance of the BarcodeDetector class. The following code shows you how to create one using BarcodeDetector.Builder:

Note that the detector will, by default, detect barcodes of all supported formats. I have used the setBarcodeFormats method to explicitly specify that the detector should only detect QR codes.

Step 3: Read the QR Code

Use Frame.Builder to create a Frame using the Bitmap you created earlier.

Call the detect method of the BarcodeDetector to generate a SparseArray containing all the QR codes the BarcodeDetector detected in your photo.

Each item of the SparseArray contains a Barcode object. To fetch the raw contents of the QR code, you can use the Barcode object’s rawValue field. However, I suggest you use the easier to read displayValue field instead. Here’s some code that prints the contents of the first QR code the API detected:

If you run your Activity now, you should be able to see the message contained in your photo’s QR code.

4. Reading a QR Code Using the Camera

The mobile vision API also makes it very easy for you to detect and read barcodes using your device’s camera in real time. Let’s create a new Activity that does just that.

Step 1: Define the Layout

Create a new layout XML file called activity_main.xml. The layout should have a SurfaceView in order to display the preview frames captured by the camera. If you want, you can also add a TextView to display the contents of the QR codes the API detects.

After using a RelativeLayout to position both widgets, the layout XML file should look something like this:

Step 2: Create the Activity

Create a new Java class called MainActivity.java. Make it a subclass of Activity and override its onCreate method. Inside the onCreate method, call setContentView to apply the layout you created in the previous step. Next, use findViewById to get references to the widgets defined in the layout.

To fetch a stream of images from the device’s camera and display them in the SurfaceView, create a new instance of the CameraSource class using CameraSource.Builder. Because the CameraSource needs a BarcodeDetector, create one using the BarcodeDetector.Builder class. If you want, you can adjust the dimensions of the camera preview using the setRequestedPreviewSize method.

Next, add a callback to the SurfaceHolder of the SurfaceView so that you know when you can start drawing the preview frames. The callback should implement the SurfaceHolder.Callback interface.

Inside the surfaceCreated method, call the start method of the CameraSource to start drawing the preview frames. Because the start method expects you to handle an IOException, you should call it from inside a try...catch block.

Similarly, inside the surfaceDestroyed method, call the stop method of the CameraSource to stop drawing the preview frames.

Your Activity is almost ready. However, you still need to tell the BarcodeDetector what it should do when it detects a QR code. Create an instance of a class that implements the Detector.Processor interface and pass it to the setProcessor method of the BarcodeDetector. Android Studio will automatically generate stubs for the methods of the interface.

Inside the receiveDetections method, get the SparseArray of Barcode objects by calling the getDetectedItems method of the Detector.Detections class. You can now write the code to do something with the detected QR codes, because I have already shown you how to work with SpareArray objects earlier in this tutorial.

Here’s how you can display the QR code’s displayValue in the TextView:

Note that you should embed the call to the setText method inside a call to the post method of the TextView, because receiveDetections does not run on the UI thread. Failing to do so will lead to a runtime error.

You can now compile and run your app. Point your device’s camera to a QR code and you should be able to see the QR code’s contents immediately.

Real time detection

Conclusion

In this tutorial, you learned how to use the mobile vision API to read QR codes from static images as well as from live camera streams. Even though we only worked with QR codes in this tutorial, you can also use the API to read other popular barcode formats such as UPC-A and EAN-13.

To learn more about the mobile vision API, I recommend visiting the API’s documentation.

2015-09-28T16:45:01.000Z2015-09-28T16:45:01.000ZAshraff Hathibelagal
Viewing all 1836 articles
Browse latest View live