Below is my quick post showing how you can create your own Hello World Android app using the new Kotlin language on OSX. More will be added to this blog post over time.
What is Kotlin
Kotlin is a statically-typed programming language that runs on Java Virtual Machines (the syntax is not compatible with Java but interoperates with it). Kotlin is Google’s default language for developing Android Android Apps. Kotlin is now the official language supported by Google for Android development. Kotlin v JAVA: http://androiddeveloper.galileo.edu/2017/10/16/kotlin-vs-java-what-is-the-difference/
The official Kotlin language page can be found here: https://kotlinlang.org/ (Wikipedia has a page here).
Kotlin has a “Try Kotlin” page here ( https://try.kotlinlang.org/ ) where you can the language out in a browser. Android Studio 3 is the latest IDE from Google that allows you to develop apps in JAVA pr Kotlin for Android.
Learn Kotkin: Hello World Demo
Kotlin Hello World Code:
/** * We declare a package-level function main which returns Unit and takes * an Array of strings as a parameter. Note that semicolons are optional. */ fun main(args: Array<String>) { println("Hello, world!") }
fyi: Other Kotlin Code Examples:
- Reading a name from the command line
- Multi-Language Hello World
- Object-Oriented Hello World
- Using a For Loop
- Using a While Loop
- Sum
- Strings
- Data Classes
- Properties
- Etc
Kotlin Language Reference: http://kotlinlang.org/docs/reference/
Tutorials: http://kotlinlang.org/docs/tutorials/
Books: http://kotlinlang.org/docs/books.html
More Resources: http://kotlinlang.org/docs/resources.html
Installing Android Studio on OSX
You will need to install the latest Android Studio 3 IDE from the link below. This will allow you to download the latest Android SDK, Android Emulator, tools and Documentation from Google.
Download Android Studio from here: https://developer.android.com/studio/index.html?utm_source=android-studio
You should now have a 750MB (or there about’s) file (called something like android-studio-ide-171.4408382-mac.dmg )
You are now ready to run the setup dmg and install the app.
“Replace” Earlier Versions (if you had 1.x or 2.x installed)
You may be asked to choose the default Android emulator ram size
Congratulations, Android Studio 3 should now be installed
Congratulations you now have the Android Studio 3 IDE Installed.
Android Studio Tips and Tricks: https://medium.com/@mmbialas/50-android-studio-tips-tricks-resources-you-should-be-familiar-with-as-an-android-developer-af86e7cf56d2
Android Studio 3 User Guide: https://developer.android.com/studio/intro/index.html
Official getting started guide: https://developer.android.com/training/basics/firstapp/index.html
Setting Android Studio Defaults
Don’t forget to download updates and set auto updates “to enabled” in the Android Studio preferences screen.
Goto the “SDK Manager” menu item under the “Tools” then “Android” menu.
You can Download additional Android SDK versions, updates and emulator environments. I would recommend you pre-download the Android 3.x to 8.x environments.
You can also download and create Emulated Android Devices in the Android Virtual Device (AVD) Manager menu.
You can choose an existing Android Device (emulated)
Create Your Own Virtual Device
You can also create your own Android virtual device (Emulated) for testing.
I have a physical Huawei Mate 9 device (for physical testing), I will set up a similar virtual device (but stick with 2GB ram instead of 4GB as my development Mac only has 8GB total ram).
You can choose an emulators device skin if you so desire. Many phone skins can be found online (e.g here, here and here). Samsung Developer page has a skins page here. Managing AVD user guide here: https://developer.android.com/studio/run/managing-avds.html. I don’t use emulator device skins as this uses much-needed memory and screen real estate.
When you are done configuring your virtual device image you may be prompted to download missing images (e.g in my case I need to download API 27/ Android 7.1.1).
Physical Device Setup (Enable Developer Mode)
You should always code on physical devices where possible (emulators are ok but have a handful of physical devices on hand to test on). I find the emulator crashes a lot on me.
How to enable developer mode on a physical Android device: https://developer.android.com/studio/debug/dev-options.html. When you have enabled developer mode you can enable advanced developer options (I like these options).
When you have a physical Android device setup and connected, you can choose to run the app on the physical device.
Creating Your first Hello World Kotlin Project
By now you will have Android Studio 3 installed, Configured Updates, Configured an Emulator device and hopefully a real test device. Now you can open Android Studio and select.
1. “Start a New Android Studio Project”
2. Name your project (e.g “My Kotlin Test App 001”)
3. Ensure your company name is unique (e.g “com.fearby.testgithub001android”
4. Tick “Include Kotlin Support” (not ticked by default).
5. Click “Next“.
6.You will need to choose the minimum API and Android version to support. If you choose a new API you may limit the potential users that can run your app and if choose an old API you will limit the potential features. In my case, I will choose 7.0 for my test project (but will choose 4.1 in public apps). Click “Help me choose” to see the percentage of users and features in each API version.
7. Clik “Next”
8. Choose “Empty Activity” and click “Next“.
9. Take note of Activity name of “MainActivity” and Layout Name of “activity_main” and click “Finish“.
Now that you have a new project you can start Emulatorkator (Tools, Android, AVD Manager then press Play next to your emulator of choice).
10. Now click Run and choose the Emulator to start.
Before we add a button to the test app, let’s add a Anko dependency to the project ( https://github.com/Kotlin/anko ) to make coding easier.
11. Open your “app/Gradle Scripts/build.gradle (Module: app)” node in the Android Project treeview.
12. View add the following line to the dependencies section (refer to https://github.com/Kotlin/anko and replace “0.10.2” with the version listed at thGitHubub site). Then click “Sync Now”.
// Anko Commons compile "org.jetbrains.anko:anko-commons:0.10.2"
13. Goto “app/res/layout/activity_main.xml” (1) and add a button to the layout (2) and name the button (3)
14. Goto “app/java/%projectname%/MainActivity” (1) and add the following two lines (2)(3) below.
Add the following at the top of “MainActivity”
import org.jetbrains.anko.toast
Add the following in the “onCreate” function (ensure your button name is the same as you called it).
buttonhello.setOnClickListener { toast ("Hello World (www.fearby.com)") }
15. You can now build and deploy the app to a device (or emulator, real devices are faster).
Add a Button to change activity screens
The official documentation on changing activity screens can be found here.
1. Rename the button from above from”Button” to ‘Hello World”
2. Add a new button can call it “buttonnextscreen” (set constraints if you wish to match the hello world button left and width).
3. Now you can add and a new target activity screen ( e.g Open your project in the treeview (1), select “New” (2), select “Activity” (3) and then choose the activity type you want (e.g “Empty Activity” (2) ).
4. Name the “Activity Name” and “Layout Name” and click “Next“.
More info on Kotlin fragments: https://www.raywenderlich.com/169885/android-fragments-tutorial-introduction-2
5. In “MainActivity.kx” I edited the following (time to use Anko Intents and not just Anko toast )
//import org.jetbrains.anko.toast import org.jetbrains.anko.*
I also wired up the new “Next Activity” Button
buttonnextscreen.setOnClickListener { startActivity(intentFor<NextActivity>().singleTop()) }
Now you have wired up a button to change Activity Screens. The Android back button will fire the previous screen so there is no need to wire up a returning button (like on iOS).
This is the Next Activity screen that was called from a button (exciting eh).
Set and Read Textbox
After adding a textbox and button this is how I set and red text in a textbox control.
textbox.setText("Sample Text") buttongettext.setOnClickListener{ toast(textbox.text.toString()) }
Create, Set and Read Local Class
I added a button (ID) called “buttoncreateclass” and setup a “setOnClickListener” (in onCreate) to create a class, fill it then output the data from the class to three textboxes (“textfirstname”, “textsurname” and “textage”)
class Person(val Firstname: String, val Surname: String, var Age: Int) {} buttoncreateclass.setOnClickListener { var cbob = Person("Bob", Surname = "Smith", Age = 41) // Read textfirstname.setText("Firstname: " + cbob.Firstname.toString()) textsurname.setText( "Surnmae: " + cbob.Surname.toString()) textage.setText("Age: " + cbob.Age.toString()) }
Adding Application Icons.
Read the official guidelines here: https://developer.android.com/studio/write/image-asset-studio.html
I use the free cions generator here: https://romannurik.github.io/AndroidAssetStudio/
Ensure you replace the following files (with your project closed)..
- res/mipmap-hdpi/ic_launcher_round.png (72 x 72 px)
- res/mipmap-hdpi/ic_launcher.png (72 x 72 px)
- res/mipmap-hdpi/ic_launcher_round.png (72 x 72 px)
- res/mipmap-hdpi/ic_launcher.png (72 x 72 px)
- res/mipmap-xhdpi/ic_launcher_round.png (96 x 96 px)
- res/mipmap-xhdpi/ic_launcher.png (96 x 96 px)
- res/mipmap-xxhdpi/ic_launcher_round.png (144 x 144 px)
- res/mipmap-xxhdpi/ic_launcher.png (144 x 144 px)
- res/mipmap-xxxhdpi/ic_launcher_round.png (192 x 192 px)
- res/mipmap-xxxhdpi/ic_launcher.png (192 x 192 px)
You may also need to remove the res/drawable XML files to prevents the automatically genrated im,ages from loading.
- DELETE: “res/drawable/ic_launcher_background.xls”
- DELETE: “res/drawable/ic_launcher_foreground.xls”
You may need to force a delete (Right Click then “Delete” then “OK” then “Delete Anyway“).
I had a number of errors related to removing references to the automatically generated images.
File “anydpi-v26/ic_launcher.xml” and “anydpi-v26/ic_launcher_round.xml” had this contents.
<?xml version="1.0" encoding="utf-8"?> <adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> <background android:drawable="@drawable/ic_launcher_background"/> <foreground android:drawable="@drawable/ic_launcher_foreground"/> </adaptive-icon>
I replaced the contents of the file “anydpi-v26/ic_launcher.xml” and “anydpi-v26/ic_launcher_round.xml” with
<?xml version="1.0" encoding="utf-8"?> <application> android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" </application>
Then you will need to click the “Build” menu then “Clean Project” to remove references to the files.
“Build“, “Clean” results.
Executing tasks: [:app:assembleDebug] Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead. :app:preBuild UP-TO-DATE :app:preDebugBuild UP-TO-DATE :app:compileDebugAidl UP-TO-DATE :app:compileDebugRenderscript UP-TO-DATE :app:checkDebugManifest UP-TO-DATE :app:generateDebugBuildConfig UP-TO-DATE :app:generateDebugResValues UP-TO-DATE :app:generateDebugResources UP-TO-DATE :app:mergeDebugResources UP-TO-DATE :app:createDebugCompatibleScreenManifests UP-TO-DATE :app:processDebugManifest UP-TO-DATE :app:splitsDiscoveryTaskDebug UP-TO-DATE :app:processDebugResources UP-TO-DATE :app:compileDebugKotlin UP-TO-DATE :app:prepareLintJar UP-TO-DATE :app:generateDebugSources UP-TO-DATE :app:javaPreCompileDebug UP-TO-DATE :app:compileDebugJavaWithJavac UP-TO-DATE :app:compileDebugNdk NO-SOURCE :app:compileDebugSources UP-TO-DATE :app:mergeDebugShaders UP-TO-DATE :app:compileDebugShaders UP-TO-DATE :app:generateDebugAssets UP-TO-DATE :app:mergeDebugAssets UP-TO-DATE :app:transformClassesWithDexBuilderForDebug UP-TO-DATE :app:transformDexArchiveWithExternalLibsDexMergerForDebug UP-TO-DATE :app:transformDexArchiveWithDexMergerForDebug UP-TO-DATE :app:mergeDebugJniLibFolders UP-TO-DATE :app:transformNativeLibsWithMergeJniLibsForDebug UP-TO-DATE :app:processDebugJavaRes NO-SOURCE :app:transformResourcesWithMergeJavaResForDebug UP-TO-DATE :app:validateSigningDebug :app:packageDebug UP-TO-DATE :app:assembleDebug UP-TO-DATE BUILD SUCCESSFUL in 1s 26 actionable tasks: 1 executed, 25 up-to-date
Now you can build an APK with static icons (yes, that’s my face).
Read move on “realtime generated/adaptive” v “image” icons here: https://medium.com/@ianhlake/vectordrawable-adaptive-icons-3fed3d3205b5
Official guide on Adaptive Icons: https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive.html
Displaying Alerts
Displaying a hard-coded option with Anko
alert("Coffee?", "Would you like another coffee?") { yesButton { toast("OK, go and get a coffee.") } noButton { toast("OK, go and get a glasss of water.") } }.show()
Displaying a list with options with Anko
val fruit = listOf("Apple", "Banana", "Mango") selector("Go..", fruit, { dialogInterface, i -> toast("Go: ${fruit[i]}.") })
Making Phone Calls, Sending Text, Browing the web and sending Emails
Anko has some cool helper methods to allow you to send and share content.
As long as you add the appropriate buttons, text fields you can add these button listeners.
override fun onCreate(savedInstanceState: Bundle?) { ... buttonmainscreen.setOnClickListener { startActivity(intentFor<MainActivity>().singleTop()) } buttonmakeacall.setOnClickListener { makeCall(textphonenumber.text.toString()) } buttonsendatext.setOnClickListener { sendSMS(phonenumber2.text.toString(), textsendthistext.text.toString()) } buttonbrowsetheweb.setOnClickListener { browse(texturl.text.toString()) } buttonsharesometext.setOnClickListener { share(textsharethis.text.toString(), textsharethis2.text.toString() ) } buttonsendanemail.setOnClickListener { email(textemail.text.toString(), textsubject.text.toString(), textbody.text.toString()) } }
Layout
Background Async Calls
You can call background calls and then invoke the UI thread when the call has returned.
buttondoasync.setOnClickListener { fun runLongTask(): String { Thread.sleep(3000) return "Waited 3 seconds" } doAsync { var result = runLongTask() uiThread { toast(result) } } }
App Manifest Permissions
Edit the file “app/src/mainAndroidManifest.xml” and add the following two lines above the “<applications” node
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET"/>
View all permission options here: https://developer.android.com/reference/android/Manifest.permission.html
By default your app will not ask for permissions (unless you set them).
Downloading data from the Internet (API Endpoint)
Add the following to a button to make a anetwork call.
buttoncallapiinthebackground.setOnClickListener { doAsync { val result = URL("https://www.yoursite.com/api/yourappname/v1").readText() uiThread { longToast("Request performed: " + result) } } }
Example Result:
Request performed: {"API Status": "OK"]
Updating your Android Studio IDE (do this often)
Don’t forget to download updates (and enable auto-updates) in the Android Studio IDE. At the start of this draft blog post, I installed Android Studio 3.0 (Four hours later a large 1.3 GB sized update was available), I had to download many smaller updates too.
This is a frequent update that would not go away for me.
Copying the app to an Android Device.
Once you have enabled debug mode you can copy apps to and from the physical device. You can build an APK by going to the “Build” then “Build APK’s” menu and build the file to your project folder (e.g “/Users/simon/AndroidStudioProjects/MyKotlinTestApp001/app/build/outputs/apk/debug/app-debug.apk“). You can then copy this file to your Android device (via the Android File Transfer app) and you can now run the app anytime you want away from your Mac.
Also before you copy and unsigned apps to your test device tyoiu will need to enable developer mode then enable the running of apps from “unknown sources“.
If you have any security apps instaled like Sophos you will be told that yiour app has a low rating.
APK living on your device 🙂
The Android Studio also has a real device debugger.
Monitor output from a show stats from a real device
Android Security 101 (you need to know this)
You can define network configuration per these instructions: https://developer.android.com/training/articles/security-config.html
Coming from developing iOS and desktop apps I decided on researching the current state of Android Security. I would strongly suggest you watch this video from Marcos Placona ( https://twitter.com/marcos_placona Developer Evangelist @ Twilio).
Takeaway’s from this video
- Use Certificate Pinning with the library – http://square.github.io/okhttp/ in Android for network calls. Read my post on Beyond SSL with Content Security Policy, Public Key Pinning etc to set it up on a Vultr Server.
- Your app will be decompiled (with tools like Apktool) so don’t store passwords
- Use encryption for in-app strings.
- Read: https://androidsecurity.info/
- Storing your secure information in the NDK
- Check if your app is running on an emulator (is it being decompiled?)
- Check if your app is debuggable (has the manifests been changes)
- Never trust devices
- Check your apps certificate (has in been disassembled and recompiled)
- Consider using DexGuard Pro
- Use the Google SafetyNet API
- Test your devices with the Compatibility Test Suite from Google.
- Use environment variables or config files too laod API tokens etc.
- Monitor miss-use (attacks, break-ins or API hits) early.
My Suggestions
- Secure your Ubuntu server (info here and here).
- Use an HTTPS SSL Certificate
- Use Certificate Pinning
- Ask for app token/keys from your server and keep in memory.
- Use OAuth 2 to secure sessions
- Use short timeouts (or expire on use) on tokens with sensitive data.
- Call upstream objects form API to prevents client-side attacks.
Deploying your app to the Android/Google Play store
To publish an app to the Google Play store you will need to create a Google Play Developer Account, pay $25 USD and you are free to publish an app on the Google Play store. Read more here: https://play.google.com/apps/publish/
Publishing an app is as simple as filling in the blanks in the publish app screen.
Troubleshooting
- You will need a fast system with at least 8MB of ram (16GB is ideal).
- Apple XCode users will find Android Studio 3 slow and unstable (so backup your project often).
- Building apps take a long time so be prepared to wait for build and deploys to devices.
- Update warnings are aplenty, get used to them.
Read More
Kotlin Community: http://kotlinlang.org/community/
Android Studio ~ Android Central Blog: https://www.androidcentral.com/tag/android-studio
Huawei Developer Page: http://developer.huawei.com/en/
Samsung tips on using Android Studio: http://developer.samsung.com/galaxy/emulator-skin/guide#tips
Create a custom emulator skin https://developer.android.com/studio/run/managing-avds.html#skins
Follow Android Dev on Twitter: https://www.twitter.com/AndroidDev
Read: https://androidsecurity.info/
An Introduction to Kotlin: https://code.tutsplus.com/tutorials/an-introduction-to-kotlin–cms-24051
Reddit: https://www.reddit.com/r/androiddev/
Create Non XML based layouts (with ANKO):
Kotlin v JAVA: http://androiddeveloper.galileo.edu/2017/10/16/kotlin-vs-java-what-is-the-difference/
Read more about Android Studio 3: http://www.technoblogpost.com/android-studio-3-0/
Jetbrains Android Studio Guidelines: https://www.jetbrains.com/help/idea/2016.2/general-guidelines.html
Donate and make this blog better
Ask a question or recommend an article
[contact-form-7 id=”30″ title=”Ask a Question”]
v1.57 added Async calls, app icon, misc screenshots, Anko alert, email, sms, share code, permissions, network download etc.