Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Android builds with Gradle + REST security with...

Android builds with Gradle + REST security with Retrofit

Retrofit, Android, Gradle, AsyncTask, OAuth, OAuth2, Token

Jo Somers

March 24, 2015
Tweet

More Decks by Jo Somers

Other Decks in Programming

Transcript

  1. 1. Building with Gradle 2. Rest & Security 3. Tips

    & Tricks Email: [email protected] Twitter: @josomers LinkedIn: linkedin.com/in/josomers
  2. 25 years old Graduated in 2011 Applied Computer Sciences: Multimedia

    Strong interest in front-end development @josomers
  3. Android SDK / Gradle / Android Testing Dependency Injection /

    Git / Scrum Continuous Integration / ... @josomers 4 years of experience Android consultant at Cozmos
  4. Joris Schutijzer Android Developer Wim Maesschalck IOS & Web Developer

    Alejandro Padovan IOS Developer Jo Somers Android Developer Bart De Tandt Managing Partner Sven Beeckman IOS Developer & UI Designer Peter Menten Android & Back-end Developer Mark Meeus Windows 8 Developer Klaas Rokbroek Android Developer Stefan Van De Poel Business Developer
  5. Kris Weytjens IOS Developer Yannick Van Godtsenhoven Android Developer Nick

    Verbiest Android & Windows-phone Developer Michiel Gellynck Hybrid App Developer Bruno Van Thournout Xamarin Developer Jorge De Corte Android & IOS Developer Joris Missiaen Android Developer Bart Van Hecke Graphic & UX Designer Bart Matthys IOS & Android Developer Dwayne Coussement IOS Developer
  6. • Code and resources reuse • Application variants; multi-apk distribution

    or different flavors • Make it easy to configure, extend and customize the build process • Good IDE integration Why a build system?
  7. apply plugin: 'com.android.application'
 
 android {
 compileSdkVersion 22
 buildToolsVersion "21.1.1"


    
 defaultConfig {
 applicationId "be.cozmos.kdg.gradleapplication"
 minSdkVersion 21
 targetSdkVersion 22
 versionCode 1
 versionName "1.0"
 }
 buildTypes {
 release {
 minifyEnabled false
 proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
 }
 }
 }
 
 dependencies {
 compile fileTree(dir: 'libs', include: ['*.jar'])
 }
  8. // Top-level build file where you can add configuration options

    common to all sub-projects/modules.
 
 buildscript {
 repositories {
 jcenter()
 }
 dependencies {
 classpath 'com.android.tools.build:gradle:1.0.1'
 
 // NOTE: Do not place your application dependencies here; they belong
 // in the individual module build.gradle files
 }
 }
 
 allprojects {
 repositories {
 jcenter()
 }
 }
  9. • Each build type triggers a new .apk • Different

    configuration for the same application. • Default, always present, but not always visible: release + debug AppDebug AppRelease Build types?
  10. • Customised version of the application • Very minimum difference

    between apps AppAmsterdamDebug AppAmsterdamRelease AppParisDebug AppParisRelease Product flavors?
  11. AsyncTask<Void, Void, Void> { ... } 1) onPreExecute() 2) doInBackground

    (Params ...) 3) onProgressUpdate(Progress ...) 4) onPostExecute(Result)
  12. new DownloadFilesTask().execute(url1, url2, url3); private class DownloadFilesTask extends AsyncTask<URL, Integer,

    Long> { protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called if (isCancelled()) break; } return totalSize; } protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } }
  13. HttpURLConnection —> BufferedInputStream —> Read as String —> Parse string

    w/ Gson to desired Object http://developer.android.com/reference/java/net/HttpURLConnection.html HttpURLConnection connection = null;
 try {
 URL url = new URL(BASE_URL + context.getString(R.string.city_id) + ".json");
 
 connection = (HttpURLConnection) url.openConnection();
 connection.setConnectTimeout(1000);
 connection.setReadTimeout(5000);
 
 return new Gson().fromJson(IOUtils.toString(connection.getInputStream()),
 new TypeToken<List<Station>>() {
 }.getType());
 } catch (IOException e) {
 return null;
 } finally {
 if (connection != null) {
 connection.disconnect();
 }
 }
  14. <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="be.cozmos.kdg.gradleapplication" >
 
 <uses-permission android:name="android.permission.INTERNET"

    />
 
 <application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
 android:name="be.cities.activities.MainActivity"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />
 
 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 </application>
 
 </manifest>

  15. Application w/ RestAdapter Builder Add parser —>Gson (or Jackson) —>

    parse string into object —> parse object to string GET a list of stations Define Retrofit interface for RestAdapter
  16. final Callback<List<Station>> callback = new Callback<List<Station>>() {
 @Override
 public void

    success(List<Station> stations, Response response) {
 cityInfoTextView.setText("### " + stations.size() + " ###");
 }
 
 @Override
 public void failure(RetrofitError error) {
 Toast.makeText(getApplicationContext(), "Oops, something went wrong.",
 Toast.LENGTH_SHORT).show();
 }
 };
 
 CityApplication.getCityRetrofitService()
 .getStations(getString(R.string.city_id), callback);
  17. What is OAuth? OAuth is an authentication protocol that allows

    users to approve application to act on their behalf without sharing their password.
  18. What is OAuth 2.0? The OAuth 2.0 authorization framework enables

    a third- party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf.
  19. final Gson gson = new GsonBuilder().create();
 
 final RequestInterceptor requestInterceptor

    = new RequestInterceptor() {
 @Override
 public void intercept(RequestFacade request) {
 if (isUserLoggedIn()) {
 request.addHeader("Authorization", getToken());
 }
 }
 };
 
 return new RestAdapter.Builder()
 .setConverter(new GsonConverter(gson))
 .setEndpoint("http://api.citybik.es")
 .setRequestInterceptor(requestInterceptor)
 .build()
 .create(CityRetrofitService.class);
  20. How to track analytics/usage? @Override public void onStart() { super.onStart();

    EasyTracker.getInstance().activityStart(this); } @Override public void onStop() { super.onStop(); EasyTracker.getInstance().activityStop(this); }
  21. • Follow Android developers on G+ • Read articles about

    Android • Resources every Android developer
 must know http://cl.ly/1Z3z0G440H3E
  22. - Drawables : hdpi/xxhdpi/xdpi/... - Styles for Actionbar, widgets… -

    Holo styles & colors - App Launcher Icons - Generic icons Android Asset Studio