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

Loeng 5

Loeng 5

Indrek Kõue

May 07, 2015
Tweet

More Decks by Indrek Kõue

Other Decks in Programming

Transcript

  1. REHERSAL Local data storage • Shared Preferences • Internal storage

    • External storage • SQLite database + ORM Positioning
  2. SENSORS Motion • gravity • gyroscope Postion • proximity •

    megnetometer Environmental • barometer • photometer • thermometer • humidity Note! All sensors are optional.
  3. MOTION SENSORS Gravity sensor (accelerometer) Measures linear acceleration based on

    vibration on X, Y and Z axis. Unit: m/s2 Gyroscope Detects the current orientation of the device, or changes in the orientation Unit: rad/s
  4. POSITION SENSORS Proximity sensor Laser sensor which senses if something

    is close to front side of the phone. Unit: binary (close, not close) or cm Magnetometer Measures the strength of earth’s magnetic field Unit: tesla [T]
  5. ENVIRONMENT SENSORS Barometer Air pressure. Unit: Pascal Photometer Amount of

    light. Used for calibrating screen brightness. Unit: Lux Thermometer Battery temperature and/or ambient temperature. Unit: °C Humidity Measures the relative ambient humidity. Unit: %
  6. public class SensorActivity extends Activity implements SensorEventListener { @Override public

    final void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SensorManager mSensorManager = (SensorManager) getSystemService( Context.SENSOR_SERVICE); Sensor mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); if(mLight == null){ //don't have light sensor } } @Override public final void onSensorChanged(SensorEvent event) { float lux = event.values[0]; } //register listener in onResume }
  7. SENSORS @Override protected void onResume() { super.onResume(); mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);

    } @Override protected void onPause() { super.onPause(); mSensorManager.unregisterListener(this); }
  8. RUNTIME CONFIGURATION CHANGE Configuration of app changes on runtime. Most

    commonly portrait > landscape > portrait. Activity is destroyed, but you can prevent this: <activity android:name=".MyActivity" android:configChanges="orientation|screenSize" android:label="@string/app_name"> Downside: configuration specific layout won’t work (but you could override onConfigurationChanged(Configuration newConfig) in activity)
  9. PROJECT DEPENDENCIES Adding .jar manually 1)download .jar 2)copy to project

    folder 3)reference local file in build.gradle dependencies { compile files('libs/something_local.jar') } Downsides: • time consuming • it is not recommended to host large binaries in code repository
  10. PROJECT DEPENDENCIES Using Gradle/Maven 1)add Gradle/Maven resource url to gradle.build

    Example: compile 'com.google.code.gson:gson:2.3.1' Downsides: • can't clean or first compile project without internet connection • when using unofficial dependency repo and repo goes down = problem
  11. VIEW ADAPTERS Middleman between the data source and the layout

    Why? to create dynamic layouts Most popular: ArrayAdapter
  12. VIEW ADAPTERS ArrayAdapter(Context context, int resource, T[] objects) ArrayAdapter(Context context,

    int resource, int textViewResourceId, T[] objects) ArrayAdapter(Context context, int resource, List<T> objects) ArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects)
  13. VIEW ADAPTERS ArrayList<String> list = new ArrayList<>(); list.add(“first”); list.add(“second”); list.add(“third”);

    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list); ListView listView = (ListView) findViewById(R.id.listview); listView.setAdapter(adapter);
  14. VIEW ADAPTERS CLICK LISTENING // Create a message handling object

    as an anonymous class. private OnItemClickListener handler= new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { // Do something in response to the click } }; listView.setOnItemClickListener(handler);
  15. VIEW ADAPTER UPDATE LIST notifyDataSetChanged () Triggers a complete redraw

    of all (visible) children at once ArrayList<String> list = new ArrayList<>(); list.add(“first”); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list); ListView listView = (ListView) findViewById(R.id.listview); listView.setAdapter(adapter); //in some other callback list.add(“second”); listView.getAdapter().notifyDataSetChanged();
  16. public class CustomUsersAdapter extends ArrayAdapter<User> { public CustomUsersAdapter(Context context, ArrayList<User>

    users) { super(context, 0, users); } @Override public View getView(int position, View convertView, ViewGroup parent){ // Get the data item for this position User user = getItem(position); View view = LayoutInflater.from(getContext()). inflate(R.layout.item_user, parent, false); TextView tvName = (TextView) v.findViewById(R.id.tvName); TextView tvHome = (TextView) v.findViewById(R.id.tvHometown); tvName.setText(user.name); tvHome.setText(user.hometown); return view; } }
  17. ADVANCED: PERFORMANCE OPTIMIZATION 1)reusing already inflated view convertView in getView()

    2)viewholder pattern reusing references to resources in inflated view using custom class Recycling of views is a very useful: saves CPU + memory
  18. public class CustomUsersAdapter extends ArrayAdapter<User> { public CustomUsersAdapter(Context context, ArrayList<User>

    users) { super(context, 0, users); } @Override public View getView(int position, View convertView, ViewGroup parent) User user = getItem(position); // Check if an existing view is being reuse if (convertView == null) { convertView = LayoutInflater.from(getContext()). inflate(R.layout.item_user, parent, false); } // Lookup view for data population TextView tvName = (TextView) convertView.findViewById(R.id.tvName) TextView tvHome = (TextView) convertView.findViewById(R.id.tvHomet tvName.setText(user.name); tvHome.setText(user.hometown); return convertView; } }
  19. RECYCLER VIEW Replacement for ListView Released with Android 5.0 Benefits:

    • Tighter integration of viewholder pattern (caching) • Better animation support Can use in older versions through support library: dependencies { compile 'com.android.support:recyclerview-v7:21.0.+' }
  20. REST SERVICES HTTP GET/POST + JSON = REST service Stateless:

    HTTP server does not retain information or status for the duration of multiple requests = each time state parameters are passed by.
  21. HTTP GET Request GET /blog/posts/1 Host: myblog.com Accept: application/json Response:

    HTTP/1.1 200 Success Content-Type: application/json Content-Length: 65 {"id":"1","title":"Hello World!","body":"This is my first post!"}
  22. HTTP POST Request POST /blog/newpost Host: myblog.com Accept: application/json Content-Type:

    application/json {"title":"Hello World!","body":"This is my first post!"} Response: HTTP/1.1 201 Created
  23. JSON { "name": "John", "surname": "Doe", "cars": [ { "manufacturer":

    "Audi", "model": "A4", "capacity": 1.8, "accident": false }, { "manufacturer": "Škoda", "model": "Octavia", "capacity": 2, "accident": true } ], "phone": 245987453 }
  24. JSON public class Person { private String name; private String

    surname; private Car[] cars; private int phone; private int age; private Person() { } }
  25. JSON PARSING The hard way: manually String json = loadJsonFromHttpUrl(“http://….”);

    JSONObject jObj = new JSONObject(json); Person person = new Person(); person.name = jObj.getString("name"); person.surname = jObj.getString("surname"); person.phone = jObj.getInt("phone"); person.age = jObj.getInt("age"); JSONArray jArr = jObj.getJSONArray("cars"); for (int i=0; i < jArr.length(); i++) { JSONObject obj = jArr.getJSONObject(i); Car car = new Car(); car.manu………... }
  26. JSON PARSING The efficient way: auto deserializer String json =

    loadJsonFromHttpUrl(“http://….”); Gson gson = new Gson(); Person johnDoe = gson.fromJson(json, Person.class); Most popular libraries: Gson, Jackson
  27. ?