Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Java & Android Java Fundamentals Madis Pink 2016 Tartu 1 Agenda » Brief background intro to Android » Android app basics: » Activities & Intents » Resources » GUI » Tools 2 Android » A Linux-based Operating System » Announced by Google & the Open Handset Alliance Nov 2007 » First device with Android 1.0 shipped in 2008 3 Android » The primary language for writing apps is actually Java » The standard library is mainly Java 6 with a lot of Android-specific classes on top » There are 25 API versions, most apps target Android 4.4 (API 19) or higher today 4 VMs on Android » Dalvik - all Android versions up to 4.4, just-intime compilation added in Android version 2.2 » ART - New runtime with ahead-of-time compilation, shipped with Android 5.0 and later » Both operate on DEX (Dalvik EXecutable) bytecode 5 Dex Bytecode » Design goals » Compilation target for .java sources » Code size » Interpreting performance » Bytecode instructions operate on registers » Many classes in a single .dex file 6 Dex Toolchain(s) » Dexer (dx) - transforms Java 7 bytecode (.class) to dex » Jack & Jill - Experimental direct Java compilation to dex, supports Java 8 7 Dex & Dalvik Example class Hello { public static void main(String[] args) { System.out.println("Hello world!"); } } 8 Dex & Dalvik Example $ javac Hello.java -target 1.7 -source 1.7 $ java Hello Hello world! 9 Dex & Dalvik Example $ javac Hello.java -target 1.7 -source 1.7 $ java Hello Hello world! $ dx --dex --output=out.dex Hello.class 10 Dex & Dalvik Example $ javac Hello.java -target 1.7 -source 1.7 $ java Hello Hello world! $ dx --dex --output=out.dex Hello.class $ adb push out.dex /data/local/tmp/out.dex 11 Dex & Dalvik Example $ javac Hello.java -target 1.7 -source 1.7 $ java Hello Hello world! $ dx --dex --output=out.dex Hello.class $ adb push out.dex /data/local/tmp/out.dex $ adb shell dalvikvm -cp /data/local/tmp/out.dex Hello Hello world! 12 Anatomy of an App Each app is an .apk file - a zip in disguise - with the following contents: » AndroidManifest.xml - the manifest, describes the app » classes.dex - the dex bytecode » resources.arsc - compiled Android resources » res/* - compiled layouts, PNG bitmaps, etc » assets/* - blob assets: databases, audio files, etc 13 Anatomy of an App » No main(String[]) » Components as entry points: » Activities » Services » Broadcast receivers » Content Providers » These are defined in the AndroidManifest.xml 14 Android Projects » Built with Gradle! » src/main/java - Java sources » src/main/res - Android resources » src/main/AndroidManifest.xml - the manifest » build.gradle - Gradle build file, describes how to build the app 15 Intermission all samples at https://github.com/JavaFundamentalsZT/jf-android-samples 16 Activities 17 Activity » class * extends android.app.Activity » Started with an Intent - a user action » Represents a screen in an application » Owns a View hierarchy (GUI objects) » Handles user input events » Instantiated by the framework » Lifecycle controlled by the framework 18 Activities Example Email App » InboxActivity - lists all emails in Inbox » ViewEmailActivity - view a single email » ComposeActivity - compose/send a new email » LoginActivity - log the user in 19 Activity Lifecycle » Driven by the framework through calls to specific Activity methods » onCreate/onDestroy - activity created » onStart/onStop - activity visible » onResume/onPause - activity is "on top" » When overriding any of these, make sure to call to super! 20 Starting an Activity Intents » All Activities are started by defining an Intent - an object that represents user's intentions » Sort of like a request that apps can respond to » Requires a Context instance to send the Intent to the OS » All components, including activities extend Context » Two kinds of intents - explicit and implicit 21 Explicit Intents public void clickHelp() { // launch HelpActivity of this app Intent i = new Intent(context, HelpActivity.class); context.startActivity(i); } » Used to launch a specific activity on the device, usually within the same app 22 Implicit Intents public void sendFeedback() { Uri uri = Uri.parse("mailto:[email protected]"); Intent i = new Intent(Intent.ACTION_SENDTO, uri); startActivity(i); } » Used for general actions like Send email, Open a webpage, Take a picture etc 23 Implicit Intents 24 Implicit Intents public void openWebpage() { Uri uri = Uri.parse("https://courses.cs.ut.ee/2016/javaFund/fall"); Intent i = new Intent(Intent.ACTION_VIEW, uri); startActivity(i); } 25 Implicit Intents 26 Defining an Activity package org.zeroturnaround.jf.android; import android.app.Activity; public class HelloActivity extends Activity { } 27 Defining an Activity package org.zeroturnaround.jf.android; import android.app.Activity; import android.os.Bundle; import android.widget.Toast; public class HelloActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { // always need to call super super.onCreate(savedInstanceState); // display our message String msg = "Hello World!"; Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } } 28 AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.zeroturnaround.jf.android" > <application> <activity android:name="org.zeroturnaround.jf.android.HelloActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> 29 AndroidManifest.xml The <manifest /> tag tells us that this is an app with the application ID org.zeroturnaround.jf.android <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.zeroturnaround.jf.android" > <application> <!-- components go here --> </application> </manifest> 30 AndroidManifest.xml The <activity /> tag declares an Activity component with the classname org.zeroturnaround.jf.android.HelloActivity <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.zeroturnaround.jf.android" > <application> <activity android:name="org.zeroturnaround.jf.android.HelloActivity"> <!-- optional intent filter goes here --> </activity> </application> </manifest> 31 AndroidManifest.xml The <intent-filter /> tag declares which implicit Intents our Activity handles, in this case it is the MAIN action under the LAUNCHER category This makes our app visible in the Launcher app <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> 32 AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.zeroturnaround.jf.android" > <application> <activity android:name="org.zeroturnaround.jf.android.HelloActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> 33 34 More Information Activities: https://d.android.com/guide/ components/activities.html Intents: https://d.android.com/guide/ components/intents-filters.html Manifest: https://d.android.com/guide/topics/ manifest/manifest-intro.html 35 Resources 36 37 Resources » Placed in src/main/res folder » Precompiled by aapt during the Gradle build » Value resources - strings, floats, integers, booleans, ... » Complex resources - arrays, plurals, ... » File resources - bitmaps, XMLs, drawables, layouts, ... 38 Value Resources <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Hello</string> <string name="hello_world">Hello World!</string> </resources> » Placed in src/main/res/values/<FILENAME>.xml, where <FILENAME> can be anything, like strings.xml 39 Drawables » Placed in src/main/res/drawable » Can be XML (describing shapes, colours, gradients) or bitmaps » Automatically scaled by the OS 40 Layouts » Placed in src/main/res/layout » XML files for describing UI » More on these later :) 41 Accessing Resources from XML » Resources can be referenced in XML resources (including the manifest) via @<type>/ <identifier> » A few examples: » @string/app_name » @drawable/ic_launcher 42 Accessing Resources from Code » All resources get a runtime integer ID, placed in a class called R » Need to dereference through a Resources instance, obtained through a Context » Example dereferences: » getResources().getString(R.string.app_name) » getResources().getDrawable(R.drawable.ic_launcher) 43 Resource Qualifiers » Resource folders can have extra qualifiers with -suffixes » values-et containing Estonian strings » Framework decides at runtime which resource to use » Also used to have custom layouts for tablets, different drawables for device densities, etc 44 Resource Qualifiers Resource qualifier examples: » res/layout-land for landscape layouts » res/drawable-xhdpi, res/drawable-hdpi, res/ drawable-mdpi for icons at various resolutions » res/values-et, res/values-ru for localization 45 Resources <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.zeroturnaround.jf.android" > <application> <!-- components go here --> </application> </manifest> 46 Resources <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.zeroturnaround.jf.android" > <application android:label="Hello World"> <!-- components go here --> </application> </manifest> 47 Resources <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Hello</string> <string name="hello_world">Hello World!</string> </resources> 48 Resources <application android:label="Hello World"> 49 Resources <application android:label="@string/app_name"> 50 Resources <application android:label="@string/app_name" android:icon="@drawable/ic_launcher"> 51 Resources // display our message String msg = "Hello World!"; Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); 52 Resources // display our message String msg = getResources().getString(R.string.hello_world); Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); 53 Resources 54 More Information Resources overview - https://d.android.com/ guide/topics/resources/overview.html 55 GUI 56 GUI - Units » No absolute coordinates! » Units: » dip (dp) - density-independent pixels » sp - scaled pixels, scale with the text size » px - actual physical pixels » Even with dp the sizes of screens vary wildly 57 View Hierarchy » ViewGroup (container/node) and View (leaf node) » View groups lay out their children, which could be nested groups » Can be declared through code » Can be inflated from XML layouts » Use setContentView(View root) or setContentView(int layoutResId) to attach a hierarchy to an Activity 58 Views » TextView - displays text » ImageView - displays images » EditText - text input » Button - clickable TextView with various states 59 ViewGroups » FrameLayout - simple layouts for framing children » LinearLayout - lays views out in a single row/ column » RelativeLayout - lays views out in relation to each other with rules » ListView - scrolling a lot of similar views with caching 60 Views protected void onCreate(Bundle savedInstanceState) { // always need to call super super.onCreate(savedInstanceState); // display our message String msg = getResources().getString(R.string.hello_world); Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } 61 Views Replace our toast with a TextView // display our message String msg = "Hello World!"; TextView root = new TextView(this); root.setText(msg); setContentView(root); 62 Views src/main/res/layout/hello.xml: <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/hello_world" /> 63 Views src/main/res/layout/hello.xml: <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/hello_world" /> ... and in our HelloActivity.onCreate: setContentView(R.layout.hello); 64 Views 65 Views Add some padding with android:padding <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/hello_world" android:padding="16dp" /> 66 Views Make the font larger with android:textSize <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/hello_world" android:padding="16dp" android:textSize="32sp" /> 67 Views 68 Handling Events » Views can be given generated IDs via android:id="@+id/someIdentifier" » This will generate a unique integer accessible via R.id.someIdentifier » Use findViewById(int id) to find the view in code » Note! Always returns View so might need to cast 69 Handling Events Adding a button to our view <Button android:id="@+id/my_button" android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/click" /> 70 Handling Events Adding a button to our view <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/hello_world" android:textSize="32sp" /> <Button android:id="@+id/my_button" android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/click" /> </LinearLayout> 71 Handling Events We can use setOnClickListener to attach a handler to the click event setContentView(R.layout.hello); // attach an OnClickListener to the view with id `my_button` Button myButton = (Button) findViewById(R.id.my_button); myButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(v.getContext(), R.string.click, Toast.LENGTH_SHORT).show(); } }); 72 Handling Events 73 More information Layouts: https://d.android.com/guide/topics/ui/ declaring-layout.html Handling events: https://d.android.com/guide/ topics/ui/ui-events.html 74 Tools 75 Android Studio in 5 minutes » The official IDE for Android development » Based on IntelliJ IDEA Community Edition » Download: https://d.android.com/studio/ index.html » Before opening any project, open Configure -> SDK Manager to download necessary SDK components for the homework 76 Android Studio Configuring SDK Under the SDK Platforms tab, click Show Package Details and make sure the following items are checked in the Android 7.0 (Nougat) category: » Android SDK Platform 24 » Sources for Android 24 » Google APIs Intel x86 Atom System Image 77 Android Studio Configuring SDK Under the SDK Tools tab, click Show Package Details and make sure the following items are checked: » 25.0.1 under Android SDK Build-Tools » Android SDK Platform-Tools 25.0.1 » Android SDK Tools 25.2.3 » Intel x86 Emulator Accelerator (HAXM installer) 78 Android Studio Configuring SDK With that being done, press Apply, read through and Accept both Android SDK license and Intel licenses and press Next to install the components 79 Android Studio in 5 minutes » Import the homework/samples folder via Open an existing Android Studio project » Find the green '▶' next to a dropdown in the toolbar » Studio will ask you to create an emulator, any emulator with the version later than 4.0.3 (API 15) will do » Note: we've already downloaded the image for Nougat 7.0 » You should see the app on the emulator \o/ 80 Developing with a Device » Settings -> About phone » Scroll down & tap Build number 7 times » You are now a developer! » Settings -> Developer options » Make sure USB Debugging is enabled 81 Gradle » Project layout similar to Maven » Instead of XML the build is defined through a Groovy DSL » No installation needed, gradlew will download Gradle for you » gradlew build - builds the project 82 More Information Android Studio - https://d.android.com/studio/ index.html Android and Android Studio: Getting Started (~10min video) - https://youtu.be/Z98hXV9GmzY 83 Homework 14 84 Homework 14 All the details are at: https://github.com/javafundamentalszt/jf-hwandroid-calculator Due 2016-12-05 23:59:59 Estonian time Do not leave this for the last minute! Help/questions: [email protected] 85 Links Samples - https://github.com/JavaFundamentalsZT/jf-android-samples Activities - https://d.android.com/guide/components/activities.html Intents - https://d.android.com/guide/components/intents-filters.html Manifest - https://d.android.com/guide/topics/manifest/manifest-intro.html Resources overview - https://d.android.com/guide/topics/resources/overview.html Layouts - https://d.android.com/guide/topics/ui/declaring-layout.html Handling events - https://d.android.com/guide/topics/ui/ui-events.html Android Studio - https://d.android.com/studio/index.html Android and Android Studio: Getting Started (~10min video) - https://youtu.be/Z98hXV9GmzY 86