Our
new Apps, Games & Insights podcast is for app and game
enthusiasts—whether you play them or build them. We’ll talk to experts
from across the industry about topics ranging from privacy and
accessibility, to responsible growth and player engagement. Here are
eight things you’ll learn from the series:
1. Diversity creates better games
In
episode 1, we hear from Sarah Fuchs, VP, Covet Fashion and Judy Chen,
Director of PM at Crowdstar on why it’s important for the diversity of
their company to reflect their players. The team who designs one of
their games, Covet Fashion, is
60 percent women. In their words, “If you want to create an environment
that will attract women or attract probably more diversity, you need to
create an environment and model the behavior that it's OK to have a
life. And if you have a life and you enjoy your life, you will be better
at your job.”
2. Mergers and acquisitions are like a marriage
Zynga has deployed more than $1 billion in mergers and acquisitions over the last 10 years, including the acquisitions of Gram Games and Small Giant Games.
In episode 2, we’ll hear from Chris Petrovic, SVP at Zynga, who says
that it’s about building a partnership that brings together the best of
both businesses.
3. Streaming sports wasn’t easy until now
When planning the launch of their service and mobile app, DAZN gave
themselves just a year to get all the technology in place. This was
challenging because it was unthinkable to miss the start of the football
season. In episode 3, hear how DAZN brought together some of the best
players in subscription management and payment solutions, and how
they’ve grown the business.
4. Investors take sustainable businesses and products seriously
When
venture capitalists look at a business, it’s not just about whether the
business has a hot product or service, it’s as much about the founders,
their team, and their business processes. Venture capitalists are
always looking for a solid foundation on which to build—learn more in
episode 4 of the podcast.
5. Privacy matters more than ever
As
more countries and territories introduce strict laws on consumer
privacy, episode 5 explores why it’s increasingly important to ensure
that apps and games are privacy-friendly for businesses and consumers.
It’s not just about staying on the right side of the law—one security
breach can easily destroy trust in your app, and winning back that trust
isn’t easy.
6. The best games put players first
According to Jagex Games Studio,
over 270 million people have played one of their RuneScape games. In
episode 6, Ben Clarke, Senior Global Marketing Director at Jagex, talks
about their approach to launching and testing, and keeping players
engaged every day. For example, when adding a new feature, they open a
polling booth within the game where players vote on the feature.
7. Accessibility debt is a real thing, and it matters
According
to the World Bank, there are over 1 billion people worldwide with a
disability. As a public broadcaster, a central part of the mission at
the BBC is to be accessible and inclusive. This mission is as much a priority for their apps, such as iPlayer and Sounds,
as it is within their traditional broadcast channels. In episode 7,
find out how the BBC tracks this by what they call “accessibility debt,”
and why it should be important to everyone.
8. Mobile games aren’t always on mobile
Many
of your favorite Android games are now available on more devices than
just your smartphone. Mobile game developers want you to have every
opportunity to play your favorite game, regardless of the gaming
platform. Gameloft has
embraced a multi-platform approach. In episode 8, listen to Maximiliano
Rodriguez, Platforms Operations Director at Gameloft, talk about how
Gameloft considers games for ChromeOS and Android TV platforms as soon
as they start developing a game for mobile.
Join us for all eight episodes to find out more about these topics and the apps and games industry. Listen to the latest episodes on your favorite podcast channel including Spotify, Apple, and Google Podcasts.
Advanced Protection
safeguards the personal or business Google Accounts of anyone at risk
of targeted attacks—like political campaign teams, journalists,
activists and business leaders. It’s Google's strongest security for
those who need it most, and is available across desktops, laptops,
smartphones and tablets.
One of the many benefits of Advanced
Protection is that it constantly evolves to defend against emerging
threats, automatically protecting your personal information from
potential attackers. Today we're announcing new ways that Advanced
Protection is defending you from malware on Android devices.
Play Protect app scanning is automatically turned on
Google Play Protect
is Google's built-in malware protection for Android. It scans and
verifies 100 billion apps each day to keep your device, data and apps
safe. Backed by Google's machine learning algorithms, it’s constantly
evolving to match changing threats. To ensure that people enrolled in
our Advanced Protection Program benefit from the added security that
Google Play Protect provides, we’re now automatically turning it on for
all devices with a Google Account enrolled in Advanced Protection and
will require that it remain enabled.
Limiting apps from outside the Play Store
Advanced Protection is
committed to keeping harmful apps off of enrolled users’ devices. All
apps on the Google Play Store undergo rigorous testing, but apps outside
of Google Play can potentially pose a risk to users’ devices. As an
added protection, we’re now blocking the majority of these non-Play apps
from being installed on any devices with a Google Account enrolled in
Advanced Protection. You can still install non-Play apps through app
stores that were pre-installed by the device manufacturer and through Android Debug Bridge. Any apps that you’ve already installed from sources outside of Google Play will not be removed and can still be updated.
G
Suite users enrolled in the Advanced Protection Program will not get
these new Android protections for now; however, equivalent protections
are available as part of endpoint management. See this help center article for a full list of Android device policies, specifically: “Verify apps,” which prevent users from turning off Google Play Protect, and “Unknown apps,” which prevent users from installing apps from outside the Play Store.
When will these changes roll out?
Starting today, these
changes for Android will gradually roll out for Google Accounts that are
enrolled in Advanced Protection. We’ll also be rolling out new malware
protections for Chrome later this year, building upon the risky download protections we announced in 2019.
You can learn more about Advanced Protection on Android here, and to enroll in Google's Advanced Protection, visit g.co/advancedprotection.
There are more than 3.5
billion people who use smartphones, but that’s only 45 percent of the
world’s population. We created Android (Go edition) to bring more
affordable, high-quality smartphones to people around the world. Thanks
to our partners who have made more than 1,600 device models available in
180+ countries, there are now more than 100 million active Android (Go
edition) devices around the world. Here are some updates on Go edition’s
progress and where we’re going next.
Powering universal access to information
In partnership with Safaricom,
Kenya’s largest telecom provider, we brought more than 900,000 Android
(Go edition) smartphones to people in Kenya—53 percent of whom were
women—through their “Life is Digital” campaign. This is especially
important because there is a significant gender gap in mobile internet usage in Sub-Saharan Africa.
With the help of the
suite of Google apps designed for Go edition, people are connecting with
new opportunities and making gains in their daily lives. For example,
Google Go
has helped connect millions of people to information by providing a
lightweight search engine that works on unstable connections. And with
Lens in Google Go, people can quickly translate, hear and search text
they see in the real world using their phone camera—helping them
understand words on street signs, medicine labels, documents, and more.
Across
the Google apps designed for Android (Go edition), we’ve introduced a
number of user privacy features to protect the next billion people
coming online for the first time. For example, a new mode within Google Go lets people search without their searches being saved to their account, and Gallery Go leverages on-device machine learning to help people organize photos without ever sending data to the cloud.
Bringing a beautiful, fast camera experience to affordable devices
Your
phone’s camera gives you the power to capture memories that you’ll want
to share with those around you. But on many smartphones, camera apps
are often slow or complex to use, and your phone can quickly run out of
storage.
The new Camera Go app
from Google helps you take beautiful photos without worrying about speed
or storage. It has features like Portrait Mode to give your photos a
professional look by focusing on your subject. It’s built for people
using smartphones for the first time, so it has a clean and simple
interface. And, most importantly, Camera Go tracks how much photo and
video storage space you have left, and then it helps you clear up space
so you never miss a shot.
Camera Go will be available on Nokia 1.3 and more Android (Go edition) devices soon.
Every year, GDC is a
moment to celebrate our successes and learn from one another. Although
we won’t be gathering in person this year, we’re bringing you the latest
updates at our Google for Games Developer Summit, where developers can
watch the announcements and virtually attend sessions for free at g.co/gamedevsummit.
We
also realize this may have been a big sacrifice for your teams. For
some, GDC is a major opportunity for annual business development and
marketing strategies. That’s why we’ve partnered with WINGS and the GDC Relief Fund to support teams in continuing to do what they do best: build world-class games.
Now
more than ever, games are helping players around the globe feel more
connected. To ensure you have access to the tools you need to deliver
the best possible game experiences, our teams have been building solutions to help you tackle your biggest challenges and set you up for long-term success. You can check out the highlights below:
Build games and reach a wider audience with Android and Google Play
We’re making it easier for you to build and optimize games on Android. Learn about new tools
to help your development process, provide greater insights into your
game’s performance, and access a wider player base. Once you’re ready to
publish, review our updated guidance to ensure your game is
high-quality and leverages various features and services for a
successful go-to-market with Google Play.
Grow your business with Google Ads and AdMob
The
best game developers think about their players first—both when creating
experiences people love and building sustainable businesses. Google Ads
and AdMob are introducing new ways to analyze and utilize player insights to help you grow your games and earn the revenue you need to improve them over time.
Simply scale your global game with Google Cloud Game Servers
Hosting
and scaling a global game can be challenging and requires that you
either build costly solutions, or turn to pre-packaged ones that limit
choice and control. To offer you more choices and time to dedicate to
core elements of producing games, the Google Cloud team is introducing a
simplified, convenient way for managing game server clusters.
Build and publish the next generation of games with Stadia
New
game platforms present new challenges and opportunities for game
creators and Google is here to help. For developers of all sizes looking
to bring their games to Stadia, the team is unveiling Stadia Makers, a new program to support the independent development community.
We’re
excited to see this community continue to delight players around the
world, and we look forward to building what’s next, together. From all
of us, thank you for keeping this community thriving.
Over 150 years ago, the invention of braille was revolutionary in making reading and writing accessible to blind people. Today, braille displays
make typing accessible on most phones and computers through a physical
braille keyboard. But it can be time-consuming to connect an external
device each time you want to type something quickly on your phone.
TalkBack
braille keyboard is a new virtual braille keyboard integrated directly
into Android. It’s a fast, convenient way to type on your phone without
any additional hardware, whether you’re posting on social media,
responding to a text, or writing a brief email. As part of our mission
to make the world’s information universally accessible, we hope this
keyboard can broadly expand braille literacy and exposure among blind
and low vision people.
Our team
collaborated with braille developers and users throughout the
development of this feature, so it’ll be familiar to anyone who has
typed using braille before. It uses a standard 6-key layout and each key
represents one of 6 braille dots which, when tapped, make any letter or
symbol. To type an “A” you would press dot 1 and to type a “B,” dots 1
and 2 together.
The keyboard can be
used anywhere you would normally type and allows you to delete letters
and words, add lines, and submit text. You can turn the keyboard on and
off as simply as switching between international keyboards. (Note:
TalkBack gestures are not supported when the keyboard is on.)
To use the braille keyboard, turn on TalkBack in the Accessibility section within Settings, and follow these instructions
to set it up. Once you set up the keyboard, use three fingers to swipe
up on your screen and try practicing with the gestures tutorial.
Talkback
braille keyboard is rolling out to Android devices running version 6.0
or later, starting today. It works across all apps on your Android
device, supports braille grade 1 and grade 2 and is available initially
in English.
Across the world,
governments and health authorities are working together to find
solutions to the COVID-19 pandemic, to protect people and get society
back up and running. Software developers are contributing by crafting
technical tools to help combat the virus and save lives. In this spirit
of collaboration, Google and Apple are announcing a joint effort to
enable the use of Bluetooth technology to help governments and health
agencies reduce the spread of the virus, with user privacy and security
central to the design.
Since COVID-19 can be transmitted through
close proximity to affected individuals, public health organizations
have identified contact tracing as a valuable tool to help contain its
spread. A number of leading public health authorities, universities, and
NGOs around the world have been doing important work to develop opt-in
contact tracing technology. To further this cause, Apple and Google will
be launching a comprehensive solution that includes application
programming interfaces (APIs) and operating system-level technology to
assist in enabling contact tracing. Given the urgent need, the plan is
to implement this solution in two steps while maintaining strong
protections around user privacy.
First, in May, both companies
will release APIs that enable interoperability between Android and iOS
devices using apps from public health authorities. These official apps
will be available for users to download via their respective app
stores.
Second, in the coming months, Apple and Google will work
to enable a broader Bluetooth-based contact tracing platform by building
this functionality into the underlying platforms. This is a more robust
solution than an API and would allow more individuals to participate,
if they choose to opt in, as well as enable interaction with a broader
ecosystem of apps and government health authorities. Privacy,
transparency, and consent are of utmost importance in this effort, and
we look forward to building this functionality in consultation with
interested stakeholders. We will openly publish information about our
work for others to analyze.
All of us at Apple and Google believe
there has never been a more important moment to work together to solve
one of the world’s most pressing problems. Through close cooperation and
collaboration with developers, governments and public health providers,
we hope to harness the power of technology to help countries around the
world slow the spread of COVID-19 and accelerate the return of everyday
life.
Bluetooth headphones
help us take calls, listen to music while working out, and use our
phones anywhere without getting tangled up in wires. And though pairing
Bluetooth accessories is an increasingly common activity, it can be a
frustrating process for many people.
Fast Pair makes Bluetooth pairing easier on Android 6.0+ phones (learn how to check your Android version).
When you turn on your Fast Pair-enabled accessory, it automatically
detects and pairs with your Android phone in a single tap. So far, there
have been over three million Fast pairings between Bluetooth
accessories, like speakers and earbuds, and Android phones. Here are
some new capabilities to make Fast Pair experience even easier.
Easily find your lost accessory
It
can be frustrating when you put your Bluetooth headphones down and
immediately forget where you placed them. If they’re connected to your
phone, you can locate your headphones by ringing them. If you have true
wireless earbuds (earbuds that aren’t attached by cables or wires), you
can choose to ring only the left or right bud. And, when you misplace
your headphones, in the coming months, you can check their last known
location in the Find My Device app if you have Location History turned
on.
Know when to charge your true wireless earbuds
Upon
opening the case of your true wireless earbuds, you’ll receive a phone
notification about the battery level of each component (right bud, left
bud, and the case itself if supported). You’ll also receive a
notification when your earbuds and the case battery is running low, so
you know when to charge them.
Manage and personalize your accessory easily
To
personalize your headset or speakers, your accessory name will include
your first name after it successfully pairs with Bluetooth. For example,
Pixel Buds will be renamed “Alex’s Pixel Buds.”
On phones running
Android 10, you can also adjust headphone settings, like linking it to
Google Assistant and accessing Find My Device, right from the device
details page. The setting varies depending on your headphone model.
Harman Kardon FLY and the new Google Pixel Buds
will be the first true wireless earbuds to enjoy all of these new
features, with many others to come. We’ll continue to work with our
partners to bring Fast Pair to more headset models. Learn about how to connect your Fast Pair accessory here.
In October, we introduced
the all-new Google Pixel Buds—with high-quality sound, an unobtrusive
design that fits securely and comfortably in your ear and helpful AI
features. We wanted to make sure whether you're streaming content while
working out or sitting in a noisy room talking on a conference call, you
have the best possible audio experience. Today, Pixel Buds are available for $179 in Clearly White in the U.S.
We
sat down with some of the team behind Pixel Buds to learn more about
what’s new, and also to hear how they’ve been using them.
Get started easily with Fast Pair
“I
always used to use wired headphones because I had concerns about the
reliability of Bluetooth® connectivity, as lots of other earbuds have
pairing problems, including the original Pixel Buds. With the new Pixel
Buds, we focused on improving Fast Pair to eliminate these pain points
and easily connect to your phone.” - Ethan Grabau, Product Manager
Clear calls with special mics and sensor
“To
give you clear calls, even in noisy and windy environments, Pixel Buds
combine signals from beamforming mics and a special sensor that detects
when your jaw is moving. This helps so you don't have to look for a
quiet place to take a call. It’s come in particularly handy these past
few weeks for me working from home with two young daughters.” - Jae Lee, Audio Systems Engineer
Adaptive Sound for better audio
“Adaptive
Sound is perfect for those moments like when you’re steaming milk for a
latte, or when you're washing your hands or the dishes. Those noises
can eclipse your audio experience for a bit, until the latte, or your
dishes are done.” - Basheer Tome, Senior Hardware Interface Designer
“To
help, Adaptive Sound temporarily and subtly adjusts your volume to
accommodate for the new noise in your environment, and goes back to
normal after it’s dissipated. It works kind of like auto-brightness on
your phone screen: It momentarily adjusts to the world around you to
make the experience of using your device a little simpler.” - Frank Li, UX Engineer
Hands-free help with Google Assistant
"When
I’m working in the yard and wearing gloves, I can use ’Hey, Google’ on
my Pixel Buds and easily control my music. I can also hear my
notifications, and reply to a text message with just my voice and Google
Assistant.
And when I'm taking my dog on our daily walk and
using my Pixel Buds, I use Google Assistant to navigate and check my
fitness progress hands-free while juggling a leash and bag of dog
treats. The Pixel Buds are slim enough they fit snag-free under a hat or
hoodie, too." - Max Ohlendorf, Technology Manager
Real-time translations with conversation mode
“We
set out to see how we could use Google Translate on Pixel Buds to
reduce language barriers. Making the conversation as natural as possible
even with the use of the phone was important, so we decided to create
the split screen UI to show exactly what was being said, and translating
it in real time on the screen with conversation mode. Any exposure to a
different language is also an opportunity to learn, so we wanted to
make the feature is not only as helpful as possible for things like
being in a different country, but also as simple as being able to help
bilingual households across generations connect through language.” - Tricia Fu, Product Manager
Peace of mind with Find My Device
“The
fear of losing expensive wireless earbuds is real, and in many cases a
reason why people are afraid of trying them. We tried to reduce that
fear a bit with Find My Device. If an earbud falls out when you’re
walking or running, you know right away. But you may be less aware when
you return home and absentmindedly put them down somewhere. So we built
the ability to let you ring your earbuds from your phone. We also wanted
to make sure we were thoughtful in what that experience is like. You
can ring one earbud at a time, to focus on finding either the left or
right earbud. The moment your hands touch the lost earbud, the ringing
will stop. We hope people won’t need to use this feature often, but if
they do, they can find misplaced earbuds more easily.” - Alex Yee, Interaction Designer
Like Pixel phones and
other Google devices, Pixel Buds will get better over time with new
features, including an update to Find My Device which will show the last
known location of your earbuds. Check out more cool features on Pixel Buds and see which features will work with your device.
Pixel Buds are available through the Google Store and retailers including AT&T, Best Buy, Target (coming early May), T-Mobile, U.S. Cellular, Verizon and Walmart. Other colors—Almost Black, Quite Mint and Oh So Orange—will be available in the coming months. Pixel Buds will come to more countries in the coming months as well.
Our goal in this series is to learn about Android SDK development. So far we explored the development tools, looked at the structure of an Android app project, started to create a user interface, and responded to user interaction. In this tutorial, we will look at the basic structures and concepts in Java that you need to know in order to start developing apps for Android.
Introduction
If you are already familiar with Java you can ignore this section. If you have limited or no familiarity with the language, then this tutorial will indicate what you need to learn in order to go any further with Android. This tutorial is not enough in itself to teach you Java from scratch, but will act as a primer to get you started. You should follow the tutorial with additional Java learning as necessary. We won't spend too long going over the details in this tutorial, but if you are struggling with any of the concepts check out the Oracle Java Tutorials. This is an extensive guide to the language that is accessible to beginners. Don't be too alarmed if you feel a little overwhelmed by what we cover in this tutorial at first, it will make a lot more sense once you start implementing the structures in Android projects.
1. Java Syntax
Step 1
You already saw a little Java syntax in our Android project, but for clarity, let's start another project. Rather than an Android project, this time we will use a Java one, so that you can easily see the structures we use. Open Eclipse. Click the "New" button. In the wizard that appears, scroll down to the Java folder and expand it. Select "Java Project" and click "Next". Enter "MyJavaProject" as the project name and click "Finish". Eclipse then creates your new project in the workspace. In the Package Explorer, expand the new project folder. Right-click on "src" and select "New" then "Class". Enter "MyMainClass" in the Name field. Check the checkbox with "public static void main" next to it and click "Finish". Eclipse creates your class and opens it in the editor. Don't pay much attention to the structure of the project or the existing content of the class because your Android projects will be differently structured. You can use this project to work on your Java coding skills, it's easier to run and test the code you write here than with an Android app, and you can focus on the Java syntax. The "public static void main" line you see in the class file is the main method. Whatever is inside this method executes when the application runs. The content of the method is what appears between the curly brackets after "public static void main(String[] args)". Eclipse may have generated a "to do" line - just ignore it. Create a new line after it and we will add our code there.
Step 2
In Java, a variable can store a data value such as a text string or number. When you create, or "declare" a variable in Java, you have to specify the type of the data within it and give it a name. Enter the following:
intmyNum;
This line declares an integer variable. We can declare a variable and assign a value to it by extending the line:
intmyNum = 5;
We can now refer to this variable using its name. Add the following line next, writing the variable value to the output console:
System.out.println(myNum);
You will not typically write to the system output like this in your Android apps, but will use the LogCat view instead. However, writing to the output in this way is a convenient way to test your Java code.
Step 3
Let's run the application. The process is slightly different for Android apps, but we'll get to that later in the series. Select "Run" then "Run Configurations". Select "Java Application" in the list on the left and click the "New launch configuration" button above it. Eclipse automatically selects your new Java application if it is the only one you have. Otherwise, select it using the "Browse" button. Click "Run" to run your application. You should see the number five written out to the Console view beneath the editor. You can use this technique to test your Java code as you learn it. You can run the project you ran last at any time using the "Run" button in the toolbar.
Step 4
You'll use the same syntax whenever you declare a variable in Java. To assign a different value to the variable later in the program, you can refer to it by name:
myNum = 3;
This overwrites the existing value. In Java there are many different variable types. The int is referred to as a primitive type, along with a few other number types, char for character values and boolean, which stores either a true or false value. There are also Object types; we will explore Objects later. An essential Object type to familiarize yourself with is String, which stores a text string:
String myName = "Sue";
Text string values are enclosed in quotes. You can include these directly in some cases, for example:
System.out.println("number: "+ myNum);
Add this code and run it, the console will display: "number: " followed by the variable value.
Step 5
Above we saw the assignment operator "=" - here are a few of the other common operators:
//add
myNum = 5+6;
//subtract
myNum = 7-3;
//multiply
myNum = 3*2;
//divide
myNum = 10/5;
//remainder
myNum = 10%6;
//increment (add one)
myNum++;
//decrement (subtract one)
myNum--;
The operators can be used on variables as well as hard-coded numbers (as above):
intmyNum = 5;
intmyOtherNum = 4;
inttotal = myNum+myOtherNum;//9
Step 6
One other Java structure that is essential to Android is the comment. You can add a comment in two ways:
//this is a single line comment
/* This is a multiline comment
* stretching across lines
* to give more information
*/
It is vital to get into the habit of commenting your code as you write it, for your own benefit as well as anyone else who reads the code.
2. Control Structures
Step 1
The code we added to the main method executes when the Java application runs. When the Android application we created runs, whatever is in the onCreate method of the main Activity is what runs. Each line inside these methods is executed after the previous line, but the flow of execution is not always linear. There are many control structures involved in Java, so let's look at some of the most common, starting with conditionals. Conditional statements involve carrying out tests to determine the flow of execution. The simplest conditional structure in Java is the if statement:
if(myNum>3)
System.out.println("number is greater than 3");
This tests determines whether the value of the variable is greater than three. If it is, the string will be written to output. If not, then nothing will be written out and processing simply moves to the next line in the program. We say that a conditional test "returns" a true or false value. True and false are boolean values. We can add an else, which only executes if the if returned false:
if(myNum>3)
System.out.println("number is greater than 3");
else
System.out.println("number is not greater than 3");
The else executes if the value is three or less. Try the code with different values for the integer variable to see the results of the conditional tests. We can also chain multiple tests:
if(myNum>10)
System.out.println("number is greater than 10");
elseif(myNum>7)
System.out.println("number is greater than 7");
elseif(myNum>3)
System.out.println("number is greater than 3");
else
System.out.println("number is 3 or less");
Each test performs only if all previous tests in the chain returned false. So for any number, only one string is output. You can chain as many else if statements together as you need. You can also use if statements chained with one or more else if blocks without a final else. We tested for one number being greater than another. Try the following variations:
if(myNum<10)
System.out.println("number less than 10");
if(myNum==10)
System.out.println("number equals 10");
if(myNum!=10)
System.out.println("number is not equal to 10");
if(myNum>=10)
System.out.println("number either greater than or equal to 10");
if(myNum<=10)
System.out.println("number either less than or equal to 10");
You can carry out similar tests on other variable types including strings. To carry out multiple tests at once, use the following syntax:
if(myNum>=10&& myNum<=50)
System.out.println("number is between 10 and 50");
The "&&", known as the "and" operator, means that the whole statement will only return true if both tests return true. The "or" operator will return true if either test returns true:
if(myNum<0|| myNum!=-1)
System.out.println("number is less than 0 or not equal to -1");
To group code into a block, we can use curly brackets - all of the code between the brackets executes if this test returns true:
if(myNum<10)
{
System.out.println("number less than 10");
myNum=10;
}
Such brackets group code in loops, methods, and classes.
Step 2
Let's look at loops now. The following for loop iterates ten times, meaning its content executes ten times:
for(inti=0; i<10; i++){
System.out.println(i);
}
The first expression in the for outline initializes a counter integer variable to zero. The second expression is a conditional test, checking that the variable is less than ten. If this returns true, the content of the loop executes, if not the loop will end. Once the content of the loop has executed, the third expression executes, incrementing the counter. The while loop uses slightly different syntax. The following example has the same effect as the for loop:
inti=0;
while(i<10){
System.out.println(i);
i++;
}
Loops can contain multiple lines of code, including other loops.
Step 3
We have already encountered the main method and the Android onCreate method. Let's look at creating your own methods. Place the following method after the closing bracket for your main method:
publicstaticvoiddoSomething(){
System.out.println("something");
}
This method is defined as public, meaning any class in the project can call on its processing. If it was "private" it's only accessible inside the class (this is "visibility"). You will not typically have to include the "static" modifier in your first Android apps, so ignore it. The "void" represents the return type. In this case the method returns nothing. To execute the method, add a call to it back in your main method:
doSomething();
Run your application to see this function. Alter the method to return a value:
publicstaticintdoSomething(){
return5;
}
Alter the method call and run again:
System.out.println(doSomething());
The returned value is written out. Methods can also receive parameters:
When calling the method, you must pass parameters of the correct type and number:
System.out.println(doSomething(3, 5));
Methods can split application processing into logical chunks. They are particularly useful if you need to carry out the same tasks more than once; you simply define them in the method then call it whenever you need it. If you change the process, you only need to change it in the method code.
3. Classes and Objects
Step 1
We've seen how methods can be used to reuse code and to split it into logical sections. Classes and objects do this on a larger scale. You can divide the tasks in an application up between objects, with each object having a set of responsibilities defined by its class. This is similar to a method being responsible for a particular area of functionality, but an object can have multiple methods and also store data values. Imagine you are creating a game - you can create a class dedicated to handling the details of the user. Select your application package, in "src", in the Package Explorer. Right-click and choose "New" then "Class". Enter "GameUser" as the class name, make sure the main method stub checkbox is unchecked this time and click "Finish". Eclipse then opens the class file, which initially only has the class declaration outline in it:
publicclassGameUser {
//class content
}
Everything you add is between these brackets (unless you add import statements, which are listed above this section). Your Android apps notice that the class files lists the package name at the top. It isn't listed here because we used the default package.
Step 2
Inside the class, add a couple of variables:
privateString playerName;
privateintscore;
These are called "instance variables" because they are defined for each instance of the class we create. Add a constructor method after these. This is what executes when an object of the class is created:
publicGameUser(String userName, intuserScore){
playerName=userName;
score=userScore;
}
The constructor always has the same name as the class and may or may not require parameters. The constructor should typically assign values to the instance variables, often using the parameters.
Step 3
The class can also define methods. Add the following typical set after the constructor:
These are known as get and set methods, or getters and setters, because they provide code external to the class with the ability to retrieve and set the values of the instance variables. Have a look at the Outline view in Eclipse to see how it can help to navigate class content.
Step 4
Save your new class file. Back in your main class, create an object of the new class in the main method:
GameUser aUser = newGameUser("Jim", 0);
We pass the parameters listed in the constructor - the "new" keyword will make the constructor execute. We can now use this instance of the class to access the data values in it by calling its methods:
System.out.println(aUser.getScore());
aUser.setScore(5);
System.out.println(aUser.getScore());
Run the program to see how the value changes after calling the public methods on the object. You can create multiple instances of the object which will be managed separately:
GameUser anotherUser = newGameUser("Jane", 5);
4. Inheritance & Interfaces
Step 1
We've seen how a class defines the sets of responsibilities you can make use of by creating object instances. This applies not only to classes you create yourself, but also to existing Java and Android classes which you can also make use of. As well as creating instances of these platform classes, you can extend them using inheritance. With inheritance, you can create a class which inherits the functionality of an existing class while also providing its own processing. We saw an example of this in the first Android project we created, with the main Activity class. Open the class now. In the opening line of the class declaration you will see "extends Activity". This means that the class is a subclass of the Android Activity class. Using the Activity class lets Android handle the details of presenting a screen to the user, with methods for when the screen is in various states (created, paused, destroyed, etc). This lets you focus on the unique aspects of the app, by adding code to the methods defined within the Android Activity class declaration and additional methods of your own if necessary. This is a pattern you will often use on Android, extending defined classes for common aspects of apps. You can complement these with your own classes where appropriate.
Step 2
Look again at your Activity class opening line. Remember that we added "implements OnClickListener" to handle clicks on a button in the UI. This is referred to as implementing an Interface. An Interface is similar to a class you inherit from using "extends" except that the Interface declaration simply lists method outlines. You have to provide the method implementation for each of them. So when we implemented OnClickListener we committed the class to providing an onClick method, which we did. An Interface is therefore like a contract. With inheritance, extending classes inherits the method implementations provided in the class declaration for their superclass (the class being extended). You can override these implementations if you need to.
Conclusion
In this tutorial we outlined some of the essential features of Java syntax you need to understand. There are more structures and concepts to become familiar with. If you don't have Java experience and want to make sure you know enough to develop effectively for Android, use the Oracle Java Tutorials. Topics to consider learning about include arrays and switch statements. Later in the series we will look at some of the most common Android classes you are likely to use. In the next part, we will explore the resources in an Android app project.