gradle for android developers
TRANSCRIPT
W13TrackSession4/20/20162:00PM
"GradleforAndroidDevelopers"
Presented by:
Ken Kousen
Kousen IT, Inc.
Broughttoyouby:
340CorporateWay,Suite300,OrangePark,FL32073888-268-8770·904-278-0524·[email protected]·www.techwell.com
Ken Kousen Kousen IT, Inc.
Ken Kousen is the President of Kousen IT, Inc., through which he does technical training, mentoring, and consulting in all areas related to Java, specializing in Android, Spring, Hibernate, Groovy, and Grails. He is the author of the Manning book “Making Java Groovy” and the upcoming O'Reilly book "Gradle for Android". Ken is a regular speaker on the No Fluff, Just Stuff conference tour, as well as at many other international conferences. In 2013 he won a JavaOne Rock Star award. Over the past decade he has taught thousands of developers in business and industry. In addition to owning several technical certifications, his academic background includes two BS degrees from M.I.T., an MS and a Ph.D. from Princeton, and an MS in Computer Science from R.P.I. Contacts Ken @kenkousen.
AndroidMobile Dev+Test 2016
Contact Info
Ken KousenKousen IT, [email protected]://www.kousenit.comhttp://kousenit.wordpress.com (blog)@kenkousenhttps://github.com/kousen (repo)
Publications
O'Reilly video courses: See http://shop.oreilly.com for detailsGroovy Programming FundamentalsPractical Groovy ProgrammingMastering Groovy ProgrammingLearning AndroidPractical AndroidGradle FundamentalsGradle for AndroidSpring Framework Essentials
Home Page
Developer home pagehttp://developer.android.com
Android dashboards, https://developer.android.com/about/dashboards/
Android dashboards, https://developer.android.com/about/dashboards/
Android dashboards, https://developer.android.com/about/dashboards/
SDK Bundle
https://developer.android.com/sdk/index.html
Android Studio IDEAndroid SDK toolsAndroid 6.0 (Marshmallow) PlatformAndroid 6.0 Emulator
Android Studio
The only supported IDEBased on IntelliJ IDEAUses Gradle for builds
Versions
Platform version: 2.3.3, 4.4, 5.0, 5.1, 6.0
Codename:Gingerbread, ICS, JellyBean, KitKat, Lollipop,
Marshmallow
API numbers:13, 14, 15, …, 19, (skip 20), 21, 22, 23
Compatibility library
API changed significantly as of 3.0+ActionBar
Fragment
Compatibility library availableAllows for Material design on older devices
Traininghttps://developer.android.com/training/index.html
Brief tutorialsGetting Started
Thin, but useful
Referencehttps://developer.android.com/reference/packages.html
JavadocsGood search capabilitiesUse magnifying glass
Creating an application
Must select unique application IDcom.mycompany.myapp
Used in Google Play store(Not exposed to clients)
Choose min SDK levelMin level willing to support
Target SDK level preselected to current
Creating an application
Manifest
AndroidManifest.xml<uses-permission
android:name="android.permission.INTERNET" />
<application>
<activity>... </activity>
…</application>
Manifest
All activitiesPermissionsIntents and Intent filtersServicesContent providers…
Activities
Each screen is an activityExtends android.app.Activity
Full of callback methods
Activities
Each activity has an XML layoutactivity_main.xml
activity_welcome.xml
XML tags with many attributes
Activities
Activity callback methods:onCreate, onDestroy
onStart, onStop
onPause, onResume
… many others …
HAXMIntel Hardware Acceleration Execution Manager
https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager
Installer + SDK Manager entry
Activity diagram (no pun intended):https://developer.android.com/guide/components/activities.html
Moves from state to stateinvoking callback methods
Activities
res
Resources folder contains subfoldersdrawablelayoutmenuvalues...
Providing resourceshttps://developer.android.com/guide/topics/resources/providing-resources.html
Specially named subdirectoriesvalues
Configuration qualifiersvalues-v11values-sw720dp-land
dp and sp
dp: density-independent pixelsUsed for images
sp: scale-independent pixelsUsed for strings
values
Keys and values → layer of indirection
strings.xml:<string name="hello_world">Hello world!</string>
Declaring ids
If you need to access a resource from Javaneed to provide an id
android:id="@+id/name"
+ defines, otherwise references
Accessing resources
XML → compiled into R.java: full of public inner classes
generated file → do not modify
(Button) findViewById(R.id.hello_button)
Graphical editor
<LinearLayout>
<RelativeLayout>
… others, less common …
Layouts
Layouts
Add components to layouts
Must specify:layout_width
layout_height
Layout
Add layout to activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
Widgets
Widgets generate events
Buttons → View.OnClickListener(...)
(Yes, anonymous inner classes)
Buttons
Adding a button listener
helloButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sayHello(v);
}
});
Widgets
<TextView> (Label in HTML)<EditText> (TextField in HTML)<Button>
<CheckBox>
<ToggleButton>
<DatePicker> See android.widget pkg
Widgets
<EditText> with text typestext, textEmailAddress, textUri
number, phone
https://developer.android.com/guide/topics/ui/controls/text.html
Toast
Brief message over UI
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
Logging
android.util.Log
static methodsLog.d(), Log.v(), Log.i(),
Log.w(), Log.e()
Two args: TAG and message
Logging
TAG → String constant used as filter
Add filter to LogCatLog messages in classes
Intent
Messaging object
Three use cases- Start an activity- Start a service- Deliver a broadcast
Intent
Start an activityPass an intent to startActivity()Or startActivityForResult()
Intent
Start a serviceServices run in background
Pass intent to startService()
Intent
Deliver a broadcastSends messages to receivers
Pass intent to sendBroadcast()
Intent
ExplicitSpecify component to start
ImplicitDeclare action to perform (in manifest)
Intent
Extras → data carried to destination(like a map of keys and values)
Intent intent = new Intent(this, WelcomeActivity.class);
intent.putExtra("name", name);
startActivity(intent);
Views and adapters
ListView with Adapters
ArrayAdapter
creates view for each item
setAdapter on ListView
ActionBar
Apps with version > 3.0Inside <menu>:
<item
android:id="@+id/action_joke"
android:showAsAction="ifRoom|withText"
android:icon="@drawable/ic_launcher"
android:title="@string/get_joke"/>
ActionBar public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_joke:
// do whatever click should do
return true;
default:
return super.onOptionsItemSelected(item);
}
}
AsyncTask
Perform asynchronous work off UI thread
Publish results to UI thread
AsyncTaskAsyncTask<Params, Progress, Results>
Short operations (few seconds)
AsyncTask
onPreExecute()
doInBackground()
onProgressUpdate()
onPostExecute()
https://developer.android.com/reference/android/os/AsyncTask.html
Longer running tasks
Use java.concurrent packageExecutor
ThreadPoolExecutor
FutureTask
Or, better yet, use services…
Services
Long-running, background operationsnetwork operationsplay musicfile I/O
Services
StartedRuns to completion
BoundInteracts with calling clientOnly exists when bound
Services
"Runs in background"Service runs in application threadKeeps running if user switches apps
You can (and should) start new threadUse AsyncTask, for example
REST
org.json packageJSONArray
JSONObject
android.util packageJsonReader
JsonWriter
REST
org.apache.http.client packagesHttpClient
HttpGet
HttpPost
...
REST
Alternative:Spring for Android
http://projects.spring.io/spring-android/
RestTemplate classMap classes to JSON structure
Other Alternatives
Retrofithttps://square.github.io/retrofit/Uses OkHttp for networking
OkHttphttps://square.github.io/okhttp/Networking client
Storage options
Shared preferencesInternal storage on deviceExternal storageSQLite databases
https://developer.android.com/guide/topics/data/data-storage.html
Storage options
Shared preferenceskey/value pairs of primitives
getSharedPreferences()
multiple files by namegetPreferences()
Storage options
Internal storageopenFileOutput() → FileOutputStream
fos.write(...)
fos.close()
Same with input
Storage options
External storageSD card or internal
Can share files with other apps
Storage options
SQLite databaseaccessible within app only
SQLite
Extend SQLiteOpenHelperSupply constructor
Override onCreate()
Create tables with execSQL()
SQLite
Read and write usinggetReadableDatabase()
getWriteableDatabase()
Assorted query() methods
SQLite
Can access from adb shellUse sqlite3 tool
Content Providers
Provide data to other processes
Existing providers for calendar, contacts
Fragments
Portions of a user interface
Managed by activities
Fragments
Extend Fragment or one of its subclasses
Use FragmentManager to manipulatein a FragmentTransaction
Fragments
Fragments are portions of a UIOwned by ActivitiesAdditional callback methods
adb tool
Android Debug BridgePart of platform tools
adb tool
devices → list attached devices
pull, push → copy files to device
shell → open shell on device
Gradle for Android
BasicsAndroid plugin for Gradle
Added via buildscript
Lots of customization
Basicsbuildscript {
repositories { jcenter() }
dependencies {
classpath 'com.android.tools.build:gradle:1.3.2'
}
}
apply plugin: 'com.android.application'
Properties in build.gradle
android {
versionCode …versionName …
}
or even in gradle.properties
Multi-project Builds
By default, apps in AS are multi-project buildsbuild.gradle
settings.gradle
Can add additional libraries, other modules, and more
Changing the Gradle version
task wrapper(type: Wrapper) {
gradleVersion = 2.11
}
Or edit distribution URL in gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-2.11-all.zip
Build Types
Two default build types:debug
release
Configuring Build Types
Use buildTypes section of build.gradlebuildTypes {
release { … }
debug { … }
}
Can also add custom build types that way
Configuring Build Types
Each build type defines a source setsrc/main/ …src/debug/ …src/release/ …
src/androidTest/… (discussed below)
Configuring Build Types
Resources in build type source setsreplace their counterparts in main
Java classes conflict, howeverDefine class in each, or just in main
Generating a Release
Can't assemble a release untilyou can sign it
Signing Your App
Use Java's keytool to generate cert
Signing Your AppsigningConfigs {
release {
storeFile file('ICNDB.keystore')
keyAlias 'ICNDB'
storePassword 'gradle_rules'
keyPassword 'carlos_ray_aka_chuck'
}
}
Signing Your App
Passwords don't have to be in build file- Can use system properties- Can prompt user- Can use gradle.propertiesSee docs for suggestions
Signing Your App
Add signingConfig to build type config buildTypes {
release {
// …
signingConfig signingConfigs.release
}
}
Signing Your App
The signingReport task shows details
Signing Your App
Invoke assembleRelease taskResulting apk in build/outputs/apk folder
Flavors and Variants
buildTypesdebug, release
flavors → different versions of same apparrogant, friendly, obsequious
Flavors and Variants
Each flavor generates an apkVariants combine buildTypes and flavors
debug+arrogant, debug+friendly, debug+obsequious
release+arrogant, release+friendly, release+obsequious
Multiple FlavorsflavorDimensions 'attitude', 'client'
productFlavors {
arrogant { dimension 'attitude' }
…
stark { dimension 'client' }
wayne { dimension 'client' }
}
Custom Taskstask copyApks(type: Copy, dependsOn: assembleDebug) {
from("$buildDir/outputs/apk") {
exclude '**/*unsigned.apk', '**/*unaligned.apk'
}
into '../apks'
}
Custom Taskstask printVariantNames {
doLast {
android.applicationVariants.all { variant ->
println variant.name
}
}
}
Testing
Unit testingFunctional testing
RobotiumEspresso
Testing
With Gradle:Tests run on all connected devices
simultaneously
Testing
Use androidTest source setsrc/androidTest/java
Testing
Use androidTest source setsrc/androidTest/java
androidTestCompile dependencies
Testing
Use androidTest source setsrc/androidTest/java
Run connectedCheck task
References
Android new build systemhttp://tools.android.com/tech-docs/new-build-system http://tools.android.com/tech-docs/new-build-system/user-guide
Developer's Guide section on Gradlehttps://developer.android.com/sdk/installing/studio-build.html
Android Developers on G+https://plus.google.com/+AndroidDevelopers/posts
References
Gradle Recipes for Androidhttp://shop.oreilly.com/product/0636920032656.do Ask me for a coupon code :)
Summary
Activities and XML layoutsIntents and IntentFiltersWidgetsServicesStorage and SQLiteContent providers