Explore Free Android App Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Sat, 25 Feb 2023 21:14:34 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://gamedevacademy.org/wp-content/uploads/2015/09/cropped-GDA_logofinal_2015-h70-32x32.png Explore Free Android App Tutorials – GameDev Academy https://gamedevacademy.org 32 32 Running Kotlin Projects on an Emulator https://gamedevacademy.org/kotlin-emulator-tutorial/ Fri, 15 May 2020 15:00:15 +0000 https://androidkennel.org/?p=1867 Read more]]>

You can access the full course here: Kotlin for Beginners

 

In this lesson, we’re going to run our code on the Android Studio emulator.

First, as an exercise, extract the strings we used in code from our last lesson to the “strings.xml” file as shown below:

Extract string resource option from popup menu in Android studio

Running our app

To run our app, you can either press the run button in your top-right menu or click on “Run” in the top-left menu bar and then “Run app“.

If you have already set your device up in Android Studio, it’ll be visible under “Connected Devices” and you can proceed normally to run it in your phone. Otherwise, we can run our code on an emulator by creating a virtual device:

Select Deployment Target window in Android Studio

There will be a lot of options (all Google ones), but you can also import hardware profiles for other popular devices.

Let’s go ahead and select Pixel3 for this lesson:

Pixel 3 selected for device definition for Android emulation

Now, we have to choose an operating system. Let’s choose Pie. Android will then download all the needed files, so make sure you have available space on your computer for that. Once it’s done, select it and click Next:

Pie release selected for Android emulation system image

You can give your emulated device a specific name (to differentiate from other emulated devices you may have already tried before) and/or orientation mode. For now, we’re just going to go with the default choices:

Verify Configuration in Android Studio

Now, we select our new device on the list of “Available Virtual Devices” and click Ok. We notice that the phone displayed looks exactly like a Pixel3.

Let’s see if our code is running correctly:

Android emulation with blue typed into Kotlin text input

Independently of our use of upper and lower case letters, as we always convert the answer to lower case before checking which color was entered, it works just fine.

Let’s test the “else” case:

Android emulation for Kotlin project involving colors

And, as expected, we got “You like COLORS”.

In the next lesson, we’ll run our code on a physical device.

 

Transcript

Note that this has other warnings here and these warnings are saying hey, this should be a string literal, so you should use an Android resources. Again it’s recommending that you export this as a string resource and you could do that by going through and selecting extract string resource. Now I’m not gonna do that here but you could certainly do that and again, that’s best practice and so, you get a sense that Android Studio’s really prompting you to code with best practices in mind.

Let’s go ahead and turn this by coming up here and selecting the run app. We can press the button here or you can select Run and choose Run App in the menu. If you have a device connected and you’ve set it up for development, then it’ll show up here and you can click OK and it’ll run on your device. Or if you don’t have a device and you want to run it on an emulator, you can create a virtual device.

Here I’ve created a few but let me show you how that works and so, if I go ahead and choose Create New Virtual Device, you have an option to select from a variety of different devices. These are going to be Google-specific ones. You can also import hardware profiles for other popular devices. If you have a Samsung or some other manufacturer, you can download their hardware profile and then it’ll show up in Android Studio and it’ll look like the device and behave in the same way. For our purposes, I’m gonna select Pixel 3 and choose Next.

Then what we’ll need to do is download an operating system and in our case, I wanna select Pie, so I’m gonna download for Android Pie. And in this case, it’s going to download and it’s a large download, so make sure that you have room on your hard drive or your computer in order to do that but I’ll skip ahead as soon as this is done.

Once that has finished, go ahead and choose Finish and now we will select the operating system image that we’ve downloaded and choose Next. From here you can give this a name, if you wanna have multiple versions of the same device. You can also set what is called the startup orientation and some other advanced features if needed. You can always come in and change this later but for now let’s go ahead and choose Finish. We can go ahead and select that and choose OK.  So, here we have the emulator and it looks like a Pixel 3 device and here we have the app running.

So, if I go ahead and select this, I can say Blue and notice how I kind of capitalized a couple of different letters but go ahead and choose Submit. It says hey, You like BLUE and notice again because we said toLowerCase, regardless of how I capitalized it, the text is working, so let’s go ahead and change that. Let’s say yellow and we Submit. You like YELLOW. Of course it’s a little hard to see but you get the idea. What about purple. We’ll go ahead and choose Submit. Now check this out, it says You like COLORS.

Now I happen to have known that that particular RGB value was purple but because it was not recognized, we went to the else statement and from the else statement, we had our own defined color and we said You like COLORS and then we set it to purple. Same thing if I had said I want, say I’d set this to white, it’s going to say the same thing. If I go back here, let’s try black. And it says You like BLACK.

Interested in continuing? Check out the full Kotlin for Beginners course, which is part of our Mobile App Development Mini-Degree.

]]>
Setting up Firebase for Android Apps https://gamedevacademy.org/google-firebase-tutorial/ Fri, 18 Oct 2019 15:00:12 +0000 https://androidkennel.org/?p=1745 Read more]]>

You can access the full course here: The Complete Firebase Course with Kotlin

Before we can start working with Firebase, we have to create an Android project first. Open up Android Studio, hit “Create a new project” and select a Basic Activity to be the first created Activity.

Android Studio choose your project screen

Make Kotlin be the default language. Select “Use androidx artifacts”. Depending on the Android Studio version, you might have this already selected and greyed out.

Android Studio configure your project screen

With the Android project created, let’s also create the Firebase project – these two will be connected. Open up a new tab in a browser at the link https://console.firebase.google.com and click “Add Project”.

Your Firebase projects screen

The user interface of the project creation process changes quite frequently. The basic options should remain unchanged though. Give your project a name and choose whether or not you want to enable Google Analytics. This choice will not change anything regarding this course.

Project creation for Google Firebase

I will choose to enable analytics, you don’t have to.

Google Analytics setup option for Firebase project

Accept all conditions and create the Firebase project.

Google Analytics configuration options for Firebase project

Once you are in the console window for the just created project, select an option to set it up for Android development. We will connect it with our Android project.

Firebase course connection setup to Android

You now have to input the package name of the Android app. If you’ve forgotten the package name, you can find it from Android Studio in the build.gradle for the app module as the applicationId value.

Gradle Scripts options

Fill out the fields on the screen. Since we want our users to be able to sign in using their Google account, we also have to add the debug signing certificate.

Android package name and certificate to connect project for Firebase

When you upload an app to Google Play, you sign it with your own key from a keystore to prevent any unauthorized people from uploading some possibly malicious updated versions of the app without your knowledge. While you’re still developing an app though, it’s signed with a debug key which is the same for all the apps developed on your device. Certain functionality, such as Google Sign-In requires to know about all the certificates – for now, the debug one will be enough. Once you want to release the app, you can easily add the actual production certificate through the console.

To get hold of the debug certificate, go to this site: https://developers.google.com/android/guides/client-auth

Copy the terminal command for your platform. If you’re on Windows, make sure that you format the command to only a single line and remove the backslash “\”.

Command Prompt commands to get debug certificate fingerprint

After pasting that command formatted into a single line to a terminal, enter the default debug password which is android. Copy the SHA-1 certificate fingerprint.

Command Prompt screen for getting certificate

Paste it into the appropriate field in the Firebase Console project setup and register the app.

Debug signing certificate for Firebase registration

Transcript

The first thing which we need to do is to create a new Android project and then also to pair it up with Firebase. So let’s open up Android Studio. I’m using the version 3.4.1, but this should work with any subsequent versions as well.

We wanna click here, start a new Android Studio Project and we wanna select Basic Activity to be our main activity. So select this Basic, just make sure it’s selected. And let’s call it Firebase Course. Language should be Kotlin and we are going to use AndroidX artifacts, so make sure you tick this bottom most check box. And once I’ve changed the location, we’re going to say Finish.

Once everything is properly configured because we have selected the blank activity template as we were creating this project, we are going to have three files which we are interested in – and those are inside res, layout, we have content_main, but also activity_main which contains a floating action button which we will use to add new pets later one and then also we have the MainActivity Kotlin class itself. But let’s not bother with these Android classes and layouts for now because we also have to set up a Firebase project in addition to an Android project.

When you go to firebase.google.com (and link is also in the lesson summaries), we wanna go to Console, so that URL is console.firebase.google.com and let’s add a new project, so let’s call it Zenva Firebase Course. Let’s leave analytics location to be United States. I accept all the terms and conditions obviously, make sure you read them though and we’re going to say Create project. It’s gonna take some time, so let’s just wait for a while.

Awesome, once this project is created, we wanna go over to it. It’s actually gonna take us there automatically and immediately we are prompted with the fact that we should add our app to the Firebase project, actually link our app with Firebase, so we are operating with Android. So, let’s select this Android icon and now we have to input our data.

The first thing which we should add here is Android package name. This is the one which you have selected as you were creating the project. If you do not know your package name for some reason, you can find it over inside Gradle Scrips, then build.gradle for the module app and over here is applicationId, so we wanna copy this. This is where we want to paste this Android package name. Then the app nickname here is only optional, so we can leave it blank.

What we want to add though is this debug signing certificate SHA-1. It also writes here that it’s optional but if you want to use Google Sign In, you need to provide this debug signing certificate.

But what is actually this signing certificate? Every Android app needs to be signed with a KeyStore. When you upload an app onto Google Play, you sign it with your own KeyStore with your own password. If you’re only debugging your app, so you are only running them from within Android Studio by clicking on this run icon, you are not applying your own KeyStore, you’re only signing this app with a temporary so to say debug signing certificate and certain services.

For example, Google Auth is one of them, require that you provide this debug signing certificate because they use it somehow to check whether or not the user who is trying to sign in with their Google account is actually using an app which is authorized by the Google Authentication to use it, right?

Long story short, to add the debug signing certificate, let’s click on this question mark here and press See this page which will take us to Android Developer documentation or Google Developers documentation and over here. We can see how to get the debug certificate fingerprint because we are not going to release an app in this course, we are only going to be debugging it, so if you’re on a Mac or Linux or Windows, copy your own appropriate path here or command.

So let’s just copy it and, actually, I do not know why but this is in the wrong format because this slash should not be here. It should be without this slash and without a new line, so let’s just copy it from here and paste it somewhere. For example, inside the URL bar in your browser – and just delete this slash and now copy it one more time without that slash and now go over to command line, if you’re on Windows, command prompt and we are going to right-click, at least on Windows to paste in here and now run this command.

The keystore password for the debugger certificate is android and now we are presented with certificate fingerprints and we wanna get SHA1, so let’s just copy this. As usual Control + C and now we are going to paste this SHA-1 over here as the debug signing certificate, so now we are good to go and we wanna register the app.

Interested in continuing? Check out the full The Complete Firebase Course with Kotlin course, which is part of our Android Development Mini-Degree.

]]>
Creating and Presenting Dialogs https://gamedevacademy.org/creating-and-presenting-dialogs/ Wed, 04 Sep 2019 15:00:26 +0000 https://androidkennel.org/?p=1513 Read more]]> In this post, we’re going to learn how to build and post dialogs to the user. Our app will create two dialogs. One of them will be a plain dialog with two actions, and another will be a more complicated dialog to ask what you want to order for breakfast using a list of checkboxes. We’ll learn how to create those, as well as how to implement a listener so we can get callbacks to our main Activity.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Let’s get started! Create a new Android Studio project called DialogDemo and use Android 6.0 Marshmallow. We can create an empty Activity with the default settings. Regarding the view, let’s keep it simple and have two buttons that will display our different dialogs. These buttons will be centered on the screen, right under each other.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.deshpande.dialogdemo.MainActivity">

    <Button
        android:id="@+id/button_redButtonDialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="RedButtonDialog"
        android:onClick="showRedButtonDialog"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button_redButtonDialog"
        android:layout_centerHorizontal="true"
        android:text="BreakfastDialog"
        android:onClick="showBreakfastDialog"/>

</RelativeLayout>

We’ll also need to create just some small method stubs for the onClick placeholders.

public void showRedButtonDialog(View view) {
    // TODO
}

public void showBreakfastDialog(View view) {
    // TODO
}

Now we need to create a separate class for our dialogs. We’ll create the RedButtonDialog first. Right-click on the main Java package and create a new class called RedButtonDialog. After it’s created, it needs to extend AppCompatDialogFragment. In Android 6.0, all dialogs are treated as fragments. In order to set up our dialog, we need to override the onCreateDialog(…)  method. Inside, we can create an Alert dialog using the Builder pattern and set the message and the buttons using anonymous inner classes. Note that for the negative dialog button, we can just dismiss the dialog. Finally, we can return the new dialog by calling builder.create() .

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage("Push the red button?")
            .setPositiveButton("Push", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    // TODO
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });

    return builder.create();
}

We need to populate the event listener for when the red button is pushed, but our issue is that the dialog might not have the necessary information to do anything when the positive button is pressed. This is in line with Java’s principle of encapsulation. We want to compartmentalize components as much as possible. In our case, we don’t want the dialog to know the inner workings of our app; the dialog just needs to know how to be a dialog. To remedy this, we can create a callback to the Activity that created the dialog using interfaces as types. First, let’s define an interface and a listener variable at the class level.

public interface OnRedButtonPushListener {
    void onButtonPush();
}

private OnRedButtonPushListener listener;

Now, in our positive button event listener, we can just call listener.onButtonPush(). Now we need to make the Activity implement the listener and set up the listener. We can do this through a setter, or, since we’re using fragments, we can do this when the Dialog is attached to the Activity in onAttach(). We need to make sure that the Activity we’re attaching to implements the listener interface. We can do this by attempting to cast the Activity to the interface.

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        listener = (OnRedButtonPushListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() +
                " needs to implement onButtonPushListener");
    }
}

This will force the Activity creating the dialog to implement the callback listener interface. Let’s go back to our MainActivity and have it implement RedButtonDialog.OnRedButtonPushListener. In the method, we can just have the app tell the user that the button has been pushed. We can also implement our method that shows the dialog. To show a dialog, we need to create a new object and call show(…) on it. We pass in the SupportFragmentManager and a unique String tag to identify the dialog to the system.

public void showRedButtonDialog(View view) {
    RedButtonDialog redButtonDialog = new RedButtonDialog();
    redButtonDialog.show(getSupportFragmentManager(), "RedButtonDialog");
}
...
@Override
public void onButtonPush() {
    Toast.makeText(this, "Pushing the red button...", Toast.LENGTH_SHORT).show();
}

Now we can run the app and see the results of pressing the button!

Dialogs Android app with "Push the red buttons?" pop-up

Dialogs Android app with two buttons on screen

Now that we’re done with the first dialog, we can create a new class for the second, more complicated dialog. It also needs to implement DialogFragment and override the onCreateDialog(…) method. We can also create a listener for it in the same fashion as the first dialog. We first need to define an interface and a listener instance variable.

public interface OnBreakfastSubmitListener {
    void submitBreakfast(ArrayList<String> food);
}

private OnBreakfastSubmitListener listener;

Notice that our callback method provides MainActivity with an ArrayList of the selected food. In addition to this, we also need to override the onAttach(…) method exactly like the previous dialog.

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        listener = (OnBreakfastSubmitListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() +
                " needs to implement OnBreakfastSubmitListener");
    }
}

This forces any Activity that wants to create this dialog to also implement the callback method. For our list of checkboxes, we just need to supply the list items; we won’t actually have to create the checkboxes ourselves! We’ll need two more instance variables: one for the possible breakfast options and another to hold the options that the user chose.

private static String[] OPTIONS = { "Ham", "Eggs", "Pancakes", "Waffles", "Bacon" };
private ArrayList<String> breakfast;

Now we can get to the meat of the dialog: onCreateDialog(…). First, we need to create a new ArrayList and Builder for our dialog. Since our content is going to be populated with the list of checkboxes, we’ll need to provide our user with a title to our dialog so he or she knows what this dialog is for. To give our dialog checkboxes, we need to call setMultiChoiceItems(…) and pass the options and a listener for when an item is clicked. If an item is checked, then we can add it to the ArrayList, and, if it’s been clicked and it’s already in our ArrayList, we can remove it. For our positive button listener, we call the callback, passing our ArrayList as a parameter. For our negative button listener, we simply dismiss the dialog. Finally, we can return builder.create() to create our dialog.

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    breakfast = new ArrayList<>();
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    builder.setTitle("Choose your breakfast")
            .setMultiChoiceItems(OPTIONS, null, new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int which, boolean isChecked) {
                    if (isChecked) {
                        breakfast.add(OPTIONS[which]);
                    } else if (breakfast.contains(OPTIONS[which])) {
                        breakfast.remove(OPTIONS[which]);
                    }
                }
            })
            .setPositiveButton("Eat!", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    listener.submitBreakfast(breakfast);
                }
            })
            .setNegativeButton("Skip", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });

    return builder.create();

Now that this dialog is also implemented, we can go back to our MainActivity and make it implement BreakfastDialog.OnBreakfastSubmitListener and the callback method. For our callback method, we’ll just have the app display the user’s order. To make the output look a bit better, we’re going to style it by remove the surrounding brackets. Finally, we need to implement the Button’s onClick method to display the BreakfastDialog in the exact same fashion as the previous dialog.

public void showBreakfastDialog(View view) {
    BreakfastDialog breakfastDialog = new BreakfastDialog();
    breakfastDialog.show(getSupportFragmentManager(), "BreakfastDialog");
}
...
@Override
public void submitBreakfast(ArrayList<String> food) {
    Toast.makeText(this, "Ordered" + food.toString().replace('[', ' ').replace(']', ' '), Toast.LENGTH_SHORT).show();
}

Now we can click the second button! When we do, we can see the checkboxes dialog and select items. When we click ok, those data are transferred to MainActivity, which then displays the Toast message.

Dialogs Android app with breakfast options pop-up

Dialogs Android app showing what breakfast the user ordered

In this post, we learned how to create dialogs and display them to our user. We covered how to use AlertDialogs in dialogs. We learned how to use buttons and checkboxes to provide some interactivity with these dialogs. Finally, we learned how we can create callbacks to the Activity that created the Dialogs. Keep in mind that dialogs are a very disruptive operation, so use them sparingly!  Now, go create some new apps with your newfound skills!

]]>
Building a Mobile App with Flutter https://gamedevacademy.org/flutter-app-tutorial/ Fri, 05 Jul 2019 15:00:46 +0000 https://androidkennel.org/?p=1650 Read more]]>

You can access the full course here: The Complete Mobile App Development Course with Flutter

Part 1

Before creating apps in Flutter, you need to install it. To access the official guide, follow the link: https://flutter.dev/docs/get-started/install/windows

From there, download the latest version of Flutter SDK and extract the zip file into your desired location – it can be anywhere, but it’s not recommended to place it into Program Files.

Next, open the Windows search bar and input “env” in there to edit environment variables.

Windows search for env variables

You want to edit the Path variable to contain the Flutter bin folder location.

Path variable as seen in Windows environment variables

For example, if your Flutter folder is on the C drive, the path to the bin folder would look something like this – C:\*your_flutter_folder_location*\flutter\bin. Paste this location as a new path environment variable so that you can access the flutter command from anywhere in the system.

Edit screen for Windows Path environment variable

Now open a command line and you should be able to run flutter doctor command which should indicate that you have installed Flutter correctly. Don’t worry about some other errors which it may output, we are going to deal with them later by installing Android SDK.

Window Command Prompt with Flutter Doctor run

Part 2

Before creating apps in Flutter, you need to install it. To access the official guide, follow the link: https://flutter.dev/docs/get-started/install/macos

Download the Flutter SDK zip file and extract it anywhere. Then, proceed to add “flutter” to the bash profile – as explained in the linked docs or in the video. Once you’ve done that, open a terminal and run flutter doctor. This command will output the “health” of your Flutter installation. It should indicate that it is installed correctly.

You might get an error saying that Android Studio is not installed. Don’t worry about that, you are going to install it in the next lesson.

Part 3

First, download Android Studio from this link https://developer.android.com/studio

Even though you aren’t going to use Android Studio as your development environment in this course, it comes with Android SDK which is needed for Flutter development.

Flutter can create iOS apps too – all from a single codebasedeveloper.android.com/studio. However, because Android emulator can run both on Windows and MacOS, this course will deal with developing for Android. After you finish the Android app, you can run the same app on iOS very easily without changing a single line of code.

Proceed through the installation wizard as usual with the default settings. After opening Android Studio for the first time, you will be prompted to select an installation type. Choose “standard”.

Continue by installing and/or updating certain Android SDK components by clicking on Configure -> SDK Manager.

Android Studio with SDK Manager selected

Install an SDK platform (the latest is recommended).

Android 9.0 selected for Android project SDK

Install SDK tools which you see in the following screenshot.

Selection of SDK Tools in Android Studio

Once you have that, hit the Apply button, open a command line and run flutter doctor again. This time, you should have a green checkmark next to the Android installation too.

 

Transcript 1

Hello and welcome to this course. First off, we’re going to start by installing Flutter SDK on Windows, and then there will be also a part about installing Flutter on Mac.

So first, let’s go to Flutter.dev, and once you are here at this URL, you want to click on get started. Now, we are going to select Windows, and we are going to actually follow along this Windows install guide. We can see that they have some system requirements. I think that probably every single one of you should fulfill these requirements, because they are pretty low. Flutter does not need the power horse of a PC to develop in.

And now we are getting to the interesting stuff, which is getting the Flutter SDK. You want to download this Flutter SDK by just clicking this button. It’s going to download a zip file, and you want to put it somewhere where you are later going to extract it. For me, that somewhere is a place called Flutter on local disk C, on the main drive. So there is a folder called Flutter, and over there, you want to download this zip file (I have already done that) Just wait until it downloads, and you’re going to be good to go.

Now the next step as it says here is that you want to extract the zip file and place the contained Flutter in the desired location for the Flutter SDK. And since we have already downloaded this zip file into a folder, which is created by us, not just into a classic download folder but into an actual folder where you want to put that SDK, you can extract it right inside that folder where you have downloaded it. And by the way, for zip files, I recommend 7zip. This zip file contains a single folder nested, and you want to take this folder and drag it out of here, wait until it extracts, and you are going to be left with a Flutter folder right here.

Now the next step here says that we want to locate flutter_console.bat and start it by double-clicking. We are actually not going to do that, because we are going to go to the next step, which is updating our path. And path is used so that we can call Flutter commands from anywhere in the system. So no matter in which folder you open your command prompt, you can still run Flutter commands, which is pretty important, because we are going to be creating projects- Flutter projects- all over the place and not just in this Flutter folder on the C drive.

To update the path, you want to Start search bar and type ‘env’ as it writes here, which stands for environment, so edit the system environment variables. Once you are here, you want to edit environment variables. And here is one important variable called Path. You want to edit that. And by the way, if you do not have a path, you want to create a new variable, call it Path, and then paste the value, which I am going to be placing in the editing of the path, right inside variable value here.

So, but if you have path (if you are a developer, you probably have path from other development environments and from other things), so we just want to edit it if you have it. I already have this C:\\Flutter\Flutter\bin. I am just going to delete it for demonstration purposes. And you want to create new. And the path is the path to the Flutter\bin folder. In our case, the Flutter\bin folder is located under C, Flutter, with capital F, flutter with lowercase F, and bin. So just copy this. And we’re going to paste it as a new path here. Now hit okay. And the path is saved.

By doing this, we can open up any old console, and we are gonna be able to run Flutter Doctor. Flutter Doctor is a tool which will tell you what you have or what you have not set up properly in order to Flutter to be able to run and build projects, which is a pretty cool feature of Flutter that it immediately tells you what you have wrong set up on your system.

So let’s go to CMB, and we are going to run Flutter Doctor. And we’re going to be left with an output saying that we have flutter channel stable version 1.2.1, and by the way, this course will work completely fine with any kind of Flutter version, because Flutter is now stable, so there will not be any breaking changes.

And then it says that we do have Android toolchain, which you will probably not have, because we have, if you are not already an Android developer, because we have not yet set up Android, so you will have a red cross here next to Android toolchain. You probably won’t have even Android Studio, unless you are an Android developer as I’ve already said. And you’re probably not going to have VS Code. But you should have this green check mark alongside Flutter Channel stable.

So now we know that the path is set up properly, because we can call Flutter Doctor from any kind of a place in our system. And let’s move on to setting up Android.

Transcript 2

Hey, everyone. This video’s going to show you how to install the Flutter SDK on your macOS device.

So the first thing you want to do is go to the Flutter website and navigate to the macOS install page. Here, you want to scroll down and click on the download link to download the zip. I’ve already downloaded it. When it does download, it’ll either be in a zip file or already unzipped. So if it is in a zip file, just unzip it. I’ve placed my Flutter folder over here in the documents. It doesn’t matter where you place it, you can place it wherever, but I find it just easier to put it in the documents.

Alright, the first thing you want to do is go to our Finder and navigate to our user drive here. What we want to do is figure out if we have the dot bash profile file, which contains all of our environmental variables. Now, to see that (it’s actually a hidden file), what we need to do is hold down shift, command, and full stop. This should then show all of the hidden folders and files. As you can see, we don’t have a .bash_profile file, so we’ll need to create it.

Alright, so we want to open up the Terminal, and we want to navigate to our home directory. To do that, we can just type cd space tilde and then a forward slash. This will change the directory to our home drive, and we can now start to create our bash profile. To do that, we can type touch and then .bash_profile, and this will create the profile inside of our home drive, as seen here.

Now with that done, we need to add our environmental variable for the Flutter SDK. To add these variables to the bash profile, we need to type nano ~/.bash_profile. Press enter and then it should open up in this kind of text editor here. What we want to type in is PATH=~/Documents /flutter/bin and then we want to do a :$PATH. Now to save it and exit, we can just go control x and then press enter. Now we should have our environmental variable added to the bash profile, and we’re ready to go.

All that’s left to do is first of all, actually run the bash profile so that the changes are saved. So for that, we can go source, and then just enter in the directory for the bash profile. Press enter and this will just run it behind the scenes and pretty much just assign those environmental variables for us to use. As you can see, if we open up our bash profile, we now have our path added to it.

Now, to get Flutter working, we just need to go back to the Terminal and type in Flutter Doctor, and this will just launch the set-up for the Flutter SDK. We have a welcome to Flutter message here and now the doctor summary (which is basically all of the stuff we have installed and don’t have installed) will be displayed to us now. So as you can see, we have this list of different items here. We have the Flutter, which is what we just installed. And that has a tick next to it.

The only other thing we need is the Android toolchain, which, if you’re not already an Android developer, you won’t have. But this will be explained in a future lesson. All we need to make sure is that we have Flutter installed, which, at the moment here, it is. So just make sure you have Flutter ticked and you should be good to go for the next lesson.

Transcript 3

Next on this page we have Android setup and this is, by the way, valid for both Windows and Mac because Android is cross-platform- and even the installation process is cross-platform.

So we wanna start up by downloading and installing Android Studio. So we are going to be taken to the developer.android.com/studio page and we wanna download Android Studio, the latest version which is currently 3.3.2. And by the way, we are not going to be using Android Studio as our development environment. But we need to have Android Studio fully setup so that we can utilize the Android Toolchain, because actually Flutter apps are not just running on Flutter itself. They’re running on Android or iOS or, in the future, they will even be able to run on the web with project Hummingbird. But as of speaking, they cannot run on the web, so let’s just focus on Android and iOS.

So let’s download Android Studio for Windows (and the same process that I already said applies to Mac). I also have a separate folder on local disk C for Android Studio versions, so let’s just download that file over there. It has almost one gigabyte, but the download is pretty fast here so that’s cool. In the meantime, we can return to the previous page which is the Flutter setup.

Okay, once the Android Studio setup is downloaded, we wanna open the folder where it is. Now download it and we wanna start it. By doing this, I will already have three Android Studio versions installed in my machine, but what am I not going to do for you guys. So we wanna just click on Next as always. Then we want to install both Android Studio and Android Virtual Device. Then you wanna select the location for the installation of Android Studio. I am going to choose the C folder, Android Studio. And under that, I wanna create a new folder which will be just flutter_course, because I really do not need a real Android Studio installation.

Oh, it did not save the folder name, so flutter_course here, Android Studio flutter_course. So let’s put that Android Studio installation there. Now just click on Next. We are going to create a shortcut, alright. And it’s going to be all nicely installed. So even though we are not gonna be using Android Studio as our development environment, we need it for Android SDK. We’re not gonna use it, because I feel that the VS Code, Visual Studio Code, is a much better development environment for Flutter, because it’s lightweight. It doesn’t take up like, it doesn’t stutter, and overall, the experience in VS Code is just much better.

But now, let’s click on Next and we wanna start Android Studio- this new installation. Otherwise, the Android Studio executable is right under the bin folder. And actually by installing Android Studio, you’ve also installed Android SDK. But just to make sure that SDK is configured properly, you wanna click on this configure button. Go to SDK Manager. And you’re going to be taken to Android SDK tab. And just make sure that you have at least one Android SDK setup here. So I have Android nine, Android P Preview, Android 8.0 Oreo. Just click on these check marks and then also SDK Tools. You wanna make sure that you have Android SDK Build Tools, Android Emulator, the latest version.

And actually, we can update these versions even now because I have some out of date versions. So Android Emulator, Android SDK Platform-Tools, Android SDK Tools, they’re really important. You wanna have them definitely along with the Build-Tools. And actually, we are going to fully setup Android Emulator later, just now make sure that you have this package downloaded here. And then you also want to install Intel x86 Emulator Accelerator so that the Emulators are actually much faster. And then you are probably good to go. You can just download Support Repository if you want to, and Google Play services, and hit Apply.

You are going to be prompted to allow the installation and accept licenses in case you have not yet accepted them. And it’s all going to be installed in your SDK path, which was set up while installing Android Studio. So actually, here, you do not need to set up your path manually as you have to with Flutter. Because Flutter setup was really just extracting a zip file. But here, Android Studio has a complete executable installer, so it takes care of everything for you. Now, you’re gonna be prompted to set up the minimum amount of RAM for the Intel HAXM Accelerators- so two gigabytes is fine if you have that preselected.

Once we have Android SDK successfully downloaded and setup, we can check if everything was successful by running the Flutter Doctor command. So let’s go to the command line and run Flutter Doctor once again. And now, even you should have Android Toolchain with a green check mark next to it, because now we actually have it installed unless you were previously an Android developer. You will also have a check mark next to Android Studio. And you will still not have VS Code because we are going to install it later on.

What we need to setup next is the Android Emulator.

Interested in continuing? Check out the full The Complete Mobile App Development Course with Flutter course, which is part of our Android Development Mini-Degree.

]]>
Free eBook – Android Development for Human Beings https://gamedevacademy.org/free-ebook-android-development-for-human-beings/ Thu, 16 Feb 2017 10:09:04 +0000 https://androidkennel.org/?p=1572 Read more]]> Grab our new ebook Android Development for Human Beings and learn to build impressive Android apps using Material Design. Book author Mohit Deshpande is an app developer (Android and iOS) and computer scientist who current does research in AI and computer vision at the Ohio State University.

This book includes 17 chapters that cover basic app creation using Android Studio, using UI elements and forms, data storage with SQLite, querying user location, and more advanced topics such as networking and the Async Task.

We hope you find this book helpful in your journey to becoming a professional Android app developer!

This book is provided at no cost in PDF format.

Download the ebook

 

]]>
Advanced Android App Development – From Padawan to Jedi https://gamedevacademy.org/advanced-android-app-development-from-padawan-to-jedi/ Wed, 25 May 2016 12:31:42 +0000 https://androidkennel.org/?p=1536 Read more]]> Save your most valuable asset – time! Learn how to completely design and develop an production ready Android app, start to finish. We will start at the beginning where all apps start, with an idea. We will design our app using Google’s Material Design. Material Design makes more liberal use of grid-based layouts, responsive animations and transitions, padding, and depth effects such as lighting and shadows.

Then we will realize our design using the more involved components such as RecyclerView to have a fully-functional app. By the end of this course, we’ll have a fully-finished, polished app that you can use as the basis for your own app ideas.

Access this course on Zenva Academy

]]>
The Complete Android Marshmallow Development Course https://gamedevacademy.org/the-complete-android-marshmallow-development-course/ Fri, 20 May 2016 03:32:24 +0000 https://androidkennel.org/?p=1540 Read more]]> Yes, you can learn to code in Java while making Android M phone and wearable apps.

Learn to create Android M (Marshmallow) apps from scratch using Java. Don’t know Java? No problem as the first module in this course is a Java introductory course for total beginners. Already know Java? Then use the module as a quick review or skip it and jump right in learning about Material Design, ListViews, Networking, Location, Databases and Android Wear Cards. The course includes 5 Real-World apps fully explained and built from the ground up + the Wearable API so that you can code your own smart watch apps.

Access this course on Zenva Academy

]]>
How to Use the Android Notification System https://gamedevacademy.org/how-to-use-the-android-notification-system/ Wed, 02 Mar 2016 06:15:53 +0000 https://androidkennel.org/?p=1506 Read more]]> In this post we’re going to learn how to use the Android notification system. Android notifications have evolved from the standard one-liner with an app icon to having actions, showing images, and expanding to show more information. Notifications are a critical part of the user experience. Instead of the user having to check your app for updates, your app will save the user the time and effort by notifying the user about important things. We’re going to learn how to use the notification system as well as the variety of styles that notifications come in.

You can download the source code for this post here.

Let’s get started! Create a new Android Studio project called NotificationDemo with Android 6.0. We just need an empty Activity with the default naming conventions. In addition to this primary Activity, we also need to create a second Activity so that the user will be directed to that when they tap on the notification. Android Studio has a shortcut that will allow us to create an Activity and corresponding XML layout file. Right-click on the primary package and select New->Android Activity-> Empty Activity. Then enter ResultActivity for the name of our new Activity. Android Studio will now create the corresponding Java and XML file.

Regarding the view of this Activity, we want to keep this simple by just having a large TextView centered on the screen so that we know our notification directed us to the appropriate Activity. Change the XML of ResultActivity to be the following:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.deshpande.notificationdemo.ResultActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Notification Worked"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Now that we’ve done that, we need to consider the view that will actually launch the notification that will get us to this Activity. In our case, since we just need to generate a notification, let’s have a simple button that will launch a notification when it is clicked. The XML layout file of MainActivity should now look like the following:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.deshpande.notificationdemo.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me!"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:onClick="createNotification" />
</RelativeLayout>

We’ve centered the Button on the screen and already assigned it a method to be called when the button is clicked. All of our notification content is going to go into that single method. Let’s open up MainActivity and add the method below onCreate(…)  as public void createNotification(View view). The reason we need that one View parameter is because that’s a part of the method signature required for our Button’s onClick attribute.

Now we can get started building the notification. First of all, the process of creating a notification follows the Builder design pattern. With this pattern, the only way to create a Notification object is to use the public inner class Notification.Builder. Then we can customize our notification, call build(), and our Notification object is created and ready to hand off to the system to post. Each setter method of the Builder also returns a Builder with that property set. This means that we can chain together the setters like the following:

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(android.R.drawable.ic_dialog_alert)
                .setContentTitle("Notification!")
                .setContentText("This is my first notification!");

Make sure to import the v4 NotificationCompat class, not the v7! The only argument the Builder requires is the Context. Note that on the left gutter of Android Studio’s main text pane, we can see a tiny thumbnail of the drawable icon. This gives us an idea of what the icon is going to look like.

After we’ve created this preliminary Builder object, we can then consider changing the style. You might have noticed that when you have multiple unread emails, the notification looks like a miniature ListView. This is the NotificationCompat.InboxStyle. If you get a notification with a single email, the notification becomes expandable and we can actually read the first few lines of the email. This is the NotificationCompat.BigTextStyle. Finally, when you take a screenshot, there’s always a follow-up notification that can be expanded into a picture of the screenshot. This is the NotificationCompat.BigPictureStyle. In fact, we can create our own custom styles by extending the NotificationCompat.Style abstract class.

For our purposes, we’re going to look at the BigTextStyle. Using styles is very straightforward. We just create a BigTextStyle object and call bigText(…)  on it to set the expanded content of the notification. In our case, we’re going to use a Lorem Ipsum generator so that we can generate some phony text to see how the notification is going to work. Finally, we need to set our builder object’s style to be the one we just created. All of this looks like the following in code:

NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
        "Etiam hendrerit risus ut congue feugiat. Donec rutrum tristique purus, at tempus ipsum pharetra eget. " +
        "Ut tristique aliquet elementum. Sed hendrerit quis sapien a mattis. " +
        "Pellentesque interdum neque a felis mattis finibus. ");

builder.setStyle(bigText);

Now that we’ve done this, we need to handle what happens when the user clicks on the notification. We can use the Intent system to launch an Activity. However, we need to wrap that Intent inside another kind of special Intent called a PendingIntent. By wrapping our Intent around a PendingIntent and passing that to the system, it becomes the systems responsibility to call the Intent when the notification is called. A PendingIntent is just what the name implies: it’s an Intent that has yet to be used. After we create this PendingIntent, we then tell our builder to use it. This is represented in code by the following:

Intent resultIntent = new Intent(this, ResultActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);

Notice that we don’t really care about the request code since this is the only PendingIntent our app launches. In addition, the last parameter of the getActivity(…)  method is any flags we want to give to this PendingIntent. In our case, we’re telling the system not to push out a new notification if any information changes, but to update this current one. This prevents the user from receiving a hundred notifications from our app!

Finally, we can build this Notification. We also want to set an additional flag so that the notification is dismissed when the user taps on it. We can do this by building our notification and setting the flags on the built notification as follows:

Notification notification = builder.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;

Now that we’ve finally built our notification, we can send it off to the system! We need to get a backwards-compatible reference to the system’s notification manager and simply call notify(…)  with our notification object.

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, notification);

Notice how we simply set the ID of the notification to be some arbitrary integer. However, if we wanted to cancel our notification programmatically for some reason, then we would need to keep track of the ID.

And that’s all it takes to create a highly-customizable notification! We can see the various stages of the notification in the screenshots below!

Notifications – 1

Notifications – 2

In this post, we learned how to create and customize a notification that can be sent programmatically. We learned about how the notification system uses the Builder pattern to create Notification objects. We also covered the three styles of notifications: InboxStyle, BigTextStyle, and BigPictureStyle. In addition to that, we learned what PendingIntents are and their uses. Finally, we saw how to formally post the notification to the Android systems. Notifications are a key part of an app’s interact with the user. A word of warning: only make notifications if it makes sense for your app to do so. Nothing is more annoying than receiving random notifications from a calculator app! Be smart about your notifications!

]]>
How to Use Android Sensors in Games https://gamedevacademy.org/android-sensors-game-tutorial/ Sun, 07 Feb 2016 13:02:47 +0000 https://androidkennel.org/?p=1482 Read more]]> In this post, we’re going to learn how to access just one of the multitude of sensors present on an Android device by building a very small game that uses the accelerometer on the device. This game will simply show a red ball on the screen whose motion is tied to the device’s accelerometer. For example, tilting the device will cause the ball to accelerate in the direction of the tilt.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Download the full source code here.

Let’s get started! Create an Android Studio project called SensorsDemo and we’ll leave the defaults as is (but create an Empty Activity). We can go ahead and delete the activity_main.xml file in the layout folder since we’ll be using a custom view that will fill our entire screen and setContentView(…)  has an overload where we can pass in a View object. Also, copy-and-paste the ball from the provided source code’s res/drawable directory to our res/drawable directory. If there isn’t a directory, create one. We’re going to create a custom view that will handle updating our ball.

However, we still have much to do before we can get to the custom View. As a placeholder, let’s just create our BallView private inner class inside MainActivity towards the end of the file like the following.

private class BallView extends View {
    public BallView(Context context) {
        super(context);
    }
}

We’ll populate it with the logic to move the ball, but we first need to declare some top-level members representing our ball’s position, acceleration, and velocity in the x and y directions. We’ll also need members to represent the maximum x and y so we define boundaries restricting the ball’s motion so it doesn’t roll off the screen! Of course, we’ll need a member to be the ball itself as a Bitmap object. Finally, we need a SensorManager object so that we can register and unregister the listener for the accelerometer sensor.

private float xPos, xAccel, xVel = 0.0f;
private float yPos, yAccel, yVel = 0.0f;
private float xMax, yMax;
private Bitmap ball;
private SensorManager sensorManager;

Now that we’ve done this, let’s complete our onCreate(…)  method. Since we’re using the accelerometer, it’s a good idea to keep our app in portrait mode so that the system doesn’t think we want to change orientations if we tilt a bit too much in one direction. We can do this to a call in setRequestedOrientation(…)  method. Then we can create our custom BallView and set the view of our Activity to be the new BallView object. Then we need to grab the our device’s size so that the ball doesn’t roll off of the screen. Finally, we need to instantiate our SensorManager object by grabbing a reference to the system’s sensor manager.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    BallView ballView = new BallView(this);
    setContentView(ballView);

    Point size = new Point();
    Display display = getWindowManager().getDefaultDisplay();
    display.getSize(size);
    xMax = (float) size.x - 100;
    yMax = (float) size.y - 100;

    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}

In onStart()  and onStop() , we need to register and unregister our SensorManager, respectively. This is a great place to do this because these Activity lifecycle methods are called before the screen is visible to the user and after the screen has disappeared off the screen, respectively. We need to specify that we need the accelerometer sensor and we’ll need to specify a refresh rate, SENSOR_DELAY_GAME, in our case. Note that we perform our method calls after the call to the superclass in onStart() , but, in onStop() , we perform method calls before the call to the superclass. This is because we’d like to unregister our listener before the system does it’s tasks to free up resources, for example.

@Override
protected void onStart() {
    super.onStart();
    sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
}

@Override
protected void onStop() {
    sensorManager.unregisterListener(this);
    super.onStop();
}

This will force us to implement the SensorEventListener2 interface, which will make us implement onSensorChanged(…) , onFlushCompleted(…) , and onAccuracyChanged(…) . We won’t have to do anything in the latter two methods, but the former is the most important since this is where we actually retrieve data from the accelerometer.  To gain a better understanding of why we have positive/negative values in our code, look at the following diagram of the orientation of the sensors with respect to the device.

(Source)

Also, according to the documentation, sensorEvent.values[i]  stores data on our accelerometer, where i is a value from 0 to 2 representing the acceleration in the x, y, and z directions. From the diagram, note that we have to negate our y value, else the ball will just move in one dimension! After we get their values, we need to update our ball’s location. This is a common practice in game development to update the location of all of the entities of the game per frame. In our case, our only entity is the ball, and, since that’s tied to the accelerometer, our “frame” depends on the refresh rate of the sensors, which is still very fast.

@Override
public void onSensorChanged(SensorEvent sensorEvent) {
    if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        xAccel = sensorEvent.values[0];
        yAccel = -sensorEvent.values[1];
        updateBall();
    }
}

Now in our updateBall()  method, we need to change our velocities and calculate how far our ball has moved in that time. Then we need to combine our ball’s current location with the displacement and we now have the ball’s new position! Notice that because of the coordinate axes on the device, we have to actually subtract the delta position from the current position! Feel free to play around with these calculation to make your ball game more or less difficult! We also need to handle the cases where it goes off the screen. We can set the position to be the min or the max depending on how it goes off the screen.

private void updateBall() {
    float frameTime = 0.666f;
    xVel += (xAccel * frameTime);
    yVel += (yAccel * frameTime);

    float xS = (xVel / 2) * frameTime;
    float yS = (yVel / 2) * frameTime;

    xPos -= xS;
    yPos -= yS;

    if (xPos > xMax) {
        xPos = xMax;
    } else if (xPos < 0) {
        xPos = 0;
    }

    if (yPos > yMax) {
        yPos = yMax;
    } else if (yPos < 0) {
        yPos = 0;
    }
}

Now we need to code our custom view to actually display the ball on the screen. Since our entire Activity is comprised of the BallView, we can just position the ball on the view and we’re sure that the ball will be on the screen. Note that we are forced to implement the constructor that calls the superclass’s constructor. In our constructor, we need to grab our Bitmap and resize it so it’s the appropriate size for our screen.

When we’re creating a custom view, we have to override a method called onDraw()  since that’s called to draw the view once. However, we don’t just want to draw our ball once, we want to keep refreshing it. We can call an instance method inside View called invalidate() . This will tell the view to call onDraw(…)  again sometime in the future.

private class BallView extends View {

    public BallView(Context context) {
        super(context);
        Bitmap ballSrc = BitmapFactory.decodeResource(getResources(), R.drawable.ball);
        final int dstWidth = 100;
        final int dstHeight = 100;
        ball = Bitmap.createScaledBitmap(ballSrc, dstWidth, dstHeight, true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(ball, xPos, yPos, null);
        invalidate();
    }
}

This should be all we need to get our app running and using the accelerometer! Here’s what our app looks like running on a physical device.

Sensors – 1

As we move the device, the ball accelerates in the appropriate direction! For those of you that might not have an Android device, we can still use the accelerometer. However, instead of having a physical device, we need to manually connect with the emulator’s console through a client called telnet. If you’re on a Mac or Linux computer, you already have this installed. However, if you’re on Windows, you’ll need to enable it by following this procedure. To simulate the accelerometer, we’ll need to start up our emulator and open up a terminal window. Note the 4-digit number at the top of the emulator’s window. That’s called the port number and we need it to log into the emulator. In the console, type telnet localhost #### with #### as your emulator’s port number. Now we should see something like Android Console: type ‘help’ for a list of commands in the console. Now we can type sensor status  to show the status of all of the emulator sensors. We know everything is good if we can see acceleration: enabled.  in the list of sensors. Now if we wanted to change the acceleration, we can run the following command to set the acceleration: sensor set acceleration 0:0:0 or sensor set acceleration 50:50:50 . We can use this to change the acceleration of the emulator and play our game!

Conclusion

In this post, we learned how to access the accelerometer on our device/emulator to build a game using it as well. We built a game that has a ball on the screen whose motion is tied to the accelerometer. When we move the accelerometer, we also move the ball. Even though we only covered the accelerometer, this same approach can be done with different types of sensors as well. Make sure to check out the documentation on how to use the other kinds of sensors!

]]>
Meet Elizaveta: International Space Station Engineer and Zenva Student https://gamedevacademy.org/meet-elizaveta-international-space-station-engineer-and-zenva-student/ Tue, 02 Feb 2016 03:33:25 +0000 https://androidkennel.org/?p=1520 Read more]]> Having previously worked on Energia (A Soviet Rocket!) Elizaveta currently works preparing technology for the International Space Station.

work1
Pictured: Elizaveta

Launched in 1998, ISS is the largest Artificial orbit that can be seen by the naked eye from Earth and is maintained by a series of Spacecrafts including Soyuz, a Spacecraft Elizaveta also works on.

ZENVA catches up with Elizaveta to ask a little about her line of work and what interested her in doing the Complete Android Marshmallow Course.’

So, you work for an International Space Station! Could you tell us a bit about your work and how you came to that position?

Korolev City: A perfect place for a Space enthusiast to grow up
Korolev City: A perfect place for a Space enthusiast to grow up

I always wanted to be an engineer and I’m lucky enough to live near the Korolev city. I graduated from the university in the direction of electronics and systems engineering and went to work on the rocket and space corporation “Energia”.

Right now my main job is to prepare tablets for the ISS and the Soyuz. It is necessary to provide for every possible failure, and very difficult to guess what the astronauts will be doing with the tablet. Also, the tablet must interact with other equipment on board (ISS).

I’m also responsible for the preparation of video cameras to film inside the Soyuz and the ISS and during spacewalks.

download (14)
Soyuz is a spacecraft designed for the Soviet space programme.

What interested you about our Android course?

Zenva courses are not like other similar courses, where learning was a huge headache. I liked that the Android course was divided into short fragments that allowed for rests in between. Also I liked how my progress could be saved so even if I missed a week the progress wouldn’t disappear.

What do you hope to do with the skills gathered from this course?

I hope this course will be the first step in me becoming a good Android developer.

zenva student android

What sort of apps are you looking to create? Have you got one in mind?

work2[1]I want to make Android apps that provided more specialized tasks for the ISS i,e, the flight trajectory, messages from Earth, task list and search for objects (wires, charging, batteries, hard drives, etc.).

I also want to try to write a reader specifically for Soyuz. It must be fast, have fields for data entry and open several books at the same time and switch on the links between them.

Was this course recommended by those around you or something you did of your own volition?

I found the course through Coursera.org and found Zenva to be more friendly and interesting than other sites I’d tried.

If you’re interested in learning how to develop apps for Android try the Complete Android Marshmallow Development course now!

]]>