Skip to content

Instantly share code, notes, and snippets.

@lincerely
Last active October 14, 2016 05:28
Show Gist options
  • Save lincerely/b46692088587af91a75d8638a5a099e9 to your computer and use it in GitHub Desktop.
Save lincerely/b46692088587af91a75d8638a5a099e9 to your computer and use it in GitHub Desktop.
CS4295 Mobile app midterm note

Midterm notes

Web-Apps

Can't Do

  • GPU
  • camera
  • address book
  • media library
  • background service

Sample Html

<!DOCTYPE html>
<html>
  <head>
    <title> Title of the document </title>
  </head>
  <body>
    The content of the document...
  </body>
</html>

CSS structure

Selector { Property: Value; }

HTML canvas

 var c=document.getElementById('myCanvas');
 var ctx=c.getContext && c.getContext('2d'); //Prevent calling a nonexistent element
 if (ctx){
    ctx.fillStyle="#FF0000";
    ctx.fillRect(10,10,150,75);
  }

Javascript

onload

function can use to perform drawing operation after the image is ready.

HTML geolocation

navigator.geolocation

function getLocation(){
  if (navigator.geolocation){
    navigator.geolocation.getCurrentPosition(showPosition, showError);
  }else
    //....Geolocation is not supported by this browser.
}

Function

getCurrentPosition( )

has two callback: receiving position info and error handling. Function

watchPosition( )

will call the callback function when position change is detected. (use clearWatch() to stop the tracking)

The object (position) that returns include these properties:

  • coords.latitude
  • coords.longitude
  • coords.accuracy
  • coords.altitude
  • coords.altitudeAccuracy
  • coords.heading
  • coords.speed
  • timestamps

Three error handles:

  • error.PERMISSION_DENIED
  • error.POSITION_UNAVAILABLE
  • error.TIMEOUT

and

  • error.UNKNOWN_ERROR

Google Static Map API

Heading: http://maps.googleapis.com/maps/api/staticmap?

  • center = latitude ,longitude
  • zoom = level
  • size = w x h
  • mapTypeID = google.maps.mapTypeId. ROADMAP | SATELLITE | HYBRID | TERRIN
  • sensor = true|false

window.orientation

  • portrait: 0
  • landscape: ±90

window.onresize( ) or window.orientationchange( )

compare window.innerHeight and window.innerWidth as a fallback method.

Touches

Touch events

usage : obj.ontouchstart

  • ontouchstart
  • ontouchmove
  • ontouchend
  • ontouchcancel

Touch object

"touches" is a array of "touch".
"targetTouches" is an array of "touches" on same element.
"changedTouches" is an array of "touches" changed in this event.

Properties of "touch":

  • clientX - position with respect to browser window
  • clientY
  • pageX - position with respect to HTML page
  • pageY
  • screenX - position with respect to screen
  • screenY
  • target: the HTML element that it hits
  • identifier: id of this touch

Example

document.ontouchmove = function(e){
          e.preventDefault();
}
canvas.ontouchstart = function(event){
    event.preventDefault(); //IMPORTANT
    lastx = event.touches[0].clientX;
    lasty = event.touches[0].clientY -
canvastop;
    dot(lastx,lasty);
  }
  canvas.ontouchmove = function(event){
    event.preventDefault();
var newx = event.touches[0].clientX;
var newy = event.touches[0].clientY -
canvastop;
    line(lastx,lasty, newx,newy);
lastx = newx;
    lasty = newy;
  }

calling the "preventDefault( )" function on touch event to disable the default touch behaviors.

Gesture event

use to handle the notification of two finger gestures.

  • ongesturestart
  • ongesturechange
  • ongestureend

jQuery

Syntax

$(selector).action()

Examples:

$("*").hide(); //all elements
$(this).hide();
$("element").hide();
$("#id").hide();
$(".class").hide();
$("[attribute]").hide();
$("[attribute=value]").hide();
$("element.class").hide();
$("element1 element2:first").hide(); //first element2 of first element1
$("selection1 selection2").hide(); //all selection2 that are descendants of section1

//NOTE: jQuery method may fail to complete if the document is not fully loaded.
$(document).ready(function(){
  //jQuery method
});
//or
$(function(){
  //jQuery method
});
//is needed

Simple jQuery events

Usage:

$(this).event(function(){
  //event handling code
});
Event def. example
dbclick double click
toggle toggle between hide() and show() toggle(speed,callback)
slideToggle toggle between slideUp() and slideDown()

Chaining

execute jQuery command one by one on the same element, example:

$("p").css("color","red")
  .slideUp(2000)
  .slideDown(2000);

Simple actions

use same command for both get/set operation. If parameter is included, it will be a set operation

Action usage
text() get/set text content
html() get/set text content with html tags
val() get/set value of input field
attr() get/set the value of attribute
append() insert content at the end
prepend() insert content at the beginning
remove() remove the element and its child elements
empty() remove its child elements

AJAX and XML

  • AJAX = Asynchronous JavaScript and XML
  • Partially update the content of the web page without reloading.
  • jQuery support browser independent AJAX actions.

AJAX

load(URL, data, callback)

load data from server and returned data into the selected element.

  • URL: source URL.
  • data: (optional) a set of query sting key/value pairs to send along with the request.
  • callback: name of callback function, executed after completion.

Example:

$(this).load("data.txt");
$(this).load("data2.txt #id"); //load a particular element in the data file.

ajax({name:value, name:value, ...})

Perform AJAX request and load XML file from server.

Name usage
url Default current page
type GET/POST
username
password
success success(result, status, xhr) e
rror error(xhr, status, error)
dataType data type expected from the server response
data data that send to server with the request

Example of data sent to the server:

var data1={
       user_id:$("#user_id").val(),
       username:$("#user_name").val()
};
var data2="user_id=40001234&user_name=Roy";

find(selector)

Used after get the descendants of each element in the current set of matched elements, to filter the result with a selector.

Example in AJAX:

Result XML

<?xml version="1.0" encoding="UTF-8"?>
<record>
         <studentrecord>
                 <sid> 51234567</sid>
                 <sname>Peter </sname>
         </studentrecord>
         <studentrecord>
                 <sid> 50001111</sid>
                 <sname>John </sname>
         </studentrecord>
</record>

Javascript function onSuccess()

onSuccess(result){
  $(result).find("student").each(function(){
    sidList += $(this).find("sid").text() + ", ";
    snameList += $(this).find("sname").text() + ", ";
  })

  //display the result
  $("#sid").text(sidList);
  $("#sname").text(snameList);

}

$.get(URL, callback)

Request data from a specified source, may return cached data.

$.post(URL, data, callback)

Submit data to be processed to a specified source, never cached data.


Java

Modifier

            | Class | Package | Subclass | Subclass | World
            |       |         |(same pkg)|(diff pkg)| 
————————————+———————+—————————+——————————+——————————+————————
public      |   +   |    +    |    +     |     +    |   +     
————————————+———————+—————————+——————————+——————————+————————
protected   |   +   |    +    |    +     |     +    |   o     
————————————+———————+—————————+——————————+——————————+————————
no modifier |   +   |    +    |    +     |     o    |   o
————————————+———————+—————————+——————————+——————————+————————
private     |   +   |    o    |    o     |     o    |   o

+ : accessible
o : not accessible

Diff with C++

  • string is an object
  • array is an object, and can be dynamically created.(use variable as constructor)
  • method must belong to class
  • static method: only one instance, can be accessed without object reference.

Hello World!

HelloWorld.java

public class HelloWorld{

  private str;

  public HelloWorld(){
    str = "Hello World!";
  }

  public HelloWorld(x){
    str = x;
  }

  protected void finalize(){
    //return resource to the system.
  }

  public static void main(String[] args) {
    HelloWorld hW = new HelloWorld();
    System.out.println(hW.str);
  }
}

Constructor in Java is a function having the same name as its class.

Finalizer always named finalize, taking no parameter and arguments.

Abstract class

Declaration of classes that define only part of an implementation, leaving the subclasses to provide the details.

Example

abstract class Point {
  int x= 1, y=1;
  void move(int dx, int dy){
    x+=dx;
    y+=dy;
    draw();
  }
  abstract void draw();
}

//USAGE
class SimplePoint extends Point {
  void draw(){
    //complete the implementation
    System.out.println("drawing at "+x+", "+y);
  }
}
Point p = new Point(); //WRONG! compile-time error
Point p = new SimplePoint(); //CORRECT!
  • an abstract method no implementation.
  • subclasses can override any concrete method inherited from the superclass.
  • Only abstract class may have abstract method(declared but not yet implemented).
  • abstract class can't be instantiated, however reference to it can be declared.
  • it is used to provide some common behavior in the class.

Interface

  • Used to identify a common set of methods for group of classes that implement the interface.
  • Also used to share constant.
  • In total, it provide a standard framework for accessing classes.
  • Allow object to be referenced by the methods without considering the actual object.
  • Allow standard sets of methods to be used across the class hierarchy.

Interface only consist of constants and abstract methods, class that implemented it have to define all method or declare as abstract.

Example:

public interface Clickable { //abstract by default
  int x=0, y=0; //they are static final constants

  void click();
  void doubleClick(); //all method is public
  //no constructor and finalizer is allowed.
}

//interface can extend from more than one interface.
public interface Displayable extends Drawable, Printable {
  ...
}

//use keyword "implements" to use interface
public class MyButton implements Clickable{
  public void click(){
    ...
  }

  public void doubleClick(){
    ...
  }
}

NOTE: only one interface can be declared as public in one file.

keyword usage
extends for inheriting
implements for interface

Anonymous classes

Implements an abstract class / interface without declare a new class, can accessing local variable of the enclosing scope.

public class HelloWorld{
  Clickable c1, c2;
  boolean dClick
  public HelloWorld(){
    Clickable = new Clickable(){
      public void doubleClick(){
        dClick = true; //can accessing member variable of the enclosing class
      }
      public void click(){
        ...
      }
    };
  }
}

Inheritance (extends)

  • Java only support single inheritance (one superclass).
  • keyword super is used to call the superclass' constructor.
  • Java automatically call superclass' default constructor by default.
super(a,b);

super.finalize(); //should be called in child's finalize()

Different of Abstract class and interface

https://stackoverflow.com/questions/18777989/how-should-i-have-explained-the-difference-between-an-interface-and-an-abstract

Abstract class Interface
all types of variable must be constant
signature method concrete method
no abstract modifier need the abstract keyword

Exception handling

Standard form

try {
    ...
}catch(){

}finally{
    //code inside finally always run
    //even if break, continue, or return is used
}

Customized Exception

public class MyException extends Exception {
    public MyException(){
        super("My Exception throw");
    }
    public MyException(String message){
        super(message);
    }
}

Throwing Exception

for method that potentially generate one or more exceptions that will not handle explicitly:

public returnType Method () throws exception1, exception2,...{

}

generate exception with throw constructor. { ... throw new IOException(); //Exception will be thrown at this point }

Android

Activities

activityCycle

//name and label is a must for all activity
<activity android:name=".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>
  • when user select an app icon from the home screen, the onCreate() method of "launcher" (or "main") activity will be called.

  • Build.VERSION.SDK_INT

  • onPause : obstructed by other visual component, partially visible.

    • stop CPU consuming activity.
    • commit unsaved change
    • release system resources
  • onStop : fully-obstructed and not visible.(e.g.when receive a phone call)

    • restart previous activity
    • system may kill the process without calling onDestroy, so release resource in onStop.
  • onDestroy

    • most clean up task should in onStop and onPause
    • kill background thread and long-running resource
  • finish

    • call in onCreate, call onDestroy without onPause and onStop
    • use in typical situation
  • onRestart

    • re-instantiate the object that is clean up in onStop
  • onStart

    • verify available resources.

Recreate an activity

Use savedInstanceState to restore value from saved state.

static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
     // Save the user's current game state
     savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
     savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
     // Always call the superclass so it can save the view hierarchy state
     super.onSaveInstanceState(savedInstanceState);
 }

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first
     // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
         // Restore value of members from saved state
         mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
         mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
         // Probably initialize members with default values for a new instance
        }
        ...
}

public void onRestoreInstanceState(Bundle savedInstanceState) {
      // Always call the superclass so it can restore the view hierarchy
      super.onRestoreInstanceState(savedInstanceState);
      // Restore state members from saved instance
      mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
      mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}

Intent

intend to do something

//Intent intent = new Intent(context,class);
Intent intent = new Intent(this, anotherActivity.class); //Explicit intents
  • context: the context of the application package implementing this class.
  • class: component class that is to be used for the intent.
Intent intent = new Intent(this, SecondActivity.class);
i.putExtra(key, value);
startActivity (intent);

//on the other hand
Intent intent = getIntent();
String msg = intent.getStringExtra(key).toString();
Log.i("Message", msg);

Back stack

task is a collection of activity that the user interact with when performing a certain job. Backstack is a stack contains the activities of a task, arranged in order in which each activity is opened.

Log Messages

There are five kinds of log message.

Code define
Log.e() error
Log.w() warnings
Log.i() information
Log.d() debugging
Log.v() verbose

Android System Architecture

android-stack_2x

Kernel

  • memory management
  • process management
  • networking
  • other operating system services

Library

Library are in C / C++, hardware specific and pre-installed by phone vendor.

  • Surface Manager: window manager, draw bitmap.
  • 2D and 3D graphics: OpenGl
  • Media Codecs
  • SQL database
  • Browser engine : Webkit library to display HTML content.

Runtime

  • virtual machine : Dalvik
  • Core Java libraries

Application Framework

High-leveling building blocks for application development.

  • Activity manager: control life cycle of apps (backstack)
  • Content provider: encapsulate data that needs to be shared between apps (e.g. Contact)
  • Resource manager: Resources are anything go with a program which is not code.
  • Location manager: Provide location info.
  • Notification manager: Present events such as arriving message, appointments and alerts quietly.

Application

  • All app have a level play field.
  • activity life cycle is not tied to the process life cycle
  • Intents : describing a specific action.
  • Service : task runs in background (Unix daemon).
  • Content Providers: set of data wrapped up in a custom API.

Security

  • Application runs in its own linux process.
  • Memory access across different process is for-bided.
  • User ID is assigned to each process, file created by one process can be accessed each other.
  • Application has to acquire permission in the manifest.xml, permission are granted by package manager.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment