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

3. Loeng 2015 Mobiilirakenduste arendamine Andr...

3. Loeng 2015 Mobiilirakenduste arendamine Android platvormile

Avatar for Indrek Kõue

Indrek Kõue

May 03, 2015
Tweet

More Decks by Indrek Kõue

Other Decks in Programming

Transcript

  1. TOPICS 1. User Interface Thread 2. Restore Activity State 3.

    Device Independent Pixel 4. Services 5. Content Providers 6. Broadcast Receivers
  2. REHERSAL Context = Object which helps us to access system

    resources (screen rendering, writing to disc, network requests etc) Fragment = piece of user interface (similar callbacks to activity) Intent = an operation to be performed (explicit or implicit)
  3. REHERSAL Alternative resources for different type of configurations Configuration =

    screen size, screen orientation, language, platform version etc. .../res/values/strings.xml .../res/values-fr/strings.xml .../res/values-et/strings.xml
  4. USER INTERFACE THREAD ...also known as main or UI thread

    Responsible: • positioning & drawing views • updating layout • component creating (Activity, Service etc.) • garbage collection (pre ART) or GC callbacks (ART) Warning! Never do computation intensive or long lasting tasks on UI thread. Note! You can’t manipulate UI from background thread!
  5. USER INTERFACE THREAD Can do in UI thread: • manipulate

    UI • start components • simple datamodel manipulation Do not do in UI thread: • network requests • query a database • long write/read tasks • intensive data model manipulation
  6. USER INTERFACE THREAD Start background thread example: Thread backgroundThread =

    new Thread(new Runnable(){ public void run() { Bitmap bitmap = loadImageFromNetwork("http: //example.com/image.png"); } }); backgroundThread.start();
  7. USER INTERFACE THREAD Run on UI thread from background thread

    Example: activity.runOnUiThread(new Runnable() { public void run() { Log.d("UI thread", "I am the UI thread"); } }); Note! Need to have reference to Activity
  8. USER INTERFACE THREAD To achieve 60 frames per second (fps),

    each frame has to take less than 16ms Why 60 fps? Human eye can’t make difference past that range Detect less than 60fps rendering on your phone: Settings >> Developer options >> Profile GPU rendering
  9. RESTORE ACTIVITY STATE When Activity is destroyed from memory all

    member variables are discarded But what if we need to restore the previous state after when garbage collector has destroyed our Activity? Example: • user selected value in list • user scroll position • view which is inflated from member variable objects
  10. RESTORE ACTIVITY STATE onCreate(Bundle savedInstanceState) onStart() onResume() //activity is on

    foreground and visible onSaveInstanceState(Bundle savedInstanceState); onPause() onStop() onDestroy()
  11. RESTORE ACTIVITY STATE Saving state: Before system destroys your activity,

    onSaveInstanceState() is called. Specify data you'd like to save. @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); }
  12. RESTORE ACTIVITY STATE Restoring state: The system passes the saved

    state data to the onCreate method and the onRestoreInstanceState() method. @Override 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 } }
  13. DEVICE INDEPENDENT PIXEL DP = Device Independent Pixel SP =

    Device Independent Pixel for text Why can’t we use pixels? Different devices have different amount of pixels. Example: Button on device which has 200 pixel height, would be very very tiny on device which has 4000 pixel height Don’t worry: Android OS handles everything for you. Rough measurement: 50dp ~ 1cm
  14. SERVICES Service is a component that runs in the background

    to perform long-running operations • No user interface • Needs to be declared in the AndroidManifest.xml • Must extend the Service class or one of its subclasses • Started with Intent Starting service: Intent intent = new Intent(this, HelloService.class); startService(intent); Example: audio playback, look for new push messages etc.
  15. CONTENT PROVIDERS Each app runs in separate virtual machine: how

    can we share data between them? Answer: Content providers: interface for querying data • Can be protected with permissions • Needs to be defined in AndroidManifest.xml • Unique path for each content provider ex: “content: //com.example.myapp/students" Example: phonebook
  16. CONTENT PROVIDERS Define content provider: <provider android:authorities="com.example.android.contentprovider" android:name=".contentprovider.MyTodoContentProvider" /> ----------

    public class StudentsProvider extends ContentProvider { @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Cursor c = new SQLiteQueryBuilder().query(db,projection,selection, selectionArgs, null, null, null); return c; } }
  17. CONTENT PROVIDERS Use content provider: public View onCreateView( getLoaderManager().initLoader(URL_LOADER, null,

    this); } @Override public Loader<Cursor> onCreateLoader(int loaderID, Bundle bundle){ return new CursorLoader(getActivity(), mDataUrl, mProjection, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { mAdapter.changeCursor(cursor); }
  18. BROADCAST RECEIVER Broadcast: message to everyone whos interested • Every

    app can can send broadcasts and listen for broadcasts • Broadcasts can be local (in your app only) or global to every app in the phone • Has to be defined in manifest • Broadcasts received as Intent objects • Needs to extend BroadcastReceiver Example: OS battery low, screen unlocked, Wifi connected/connection lost etc.
  19. BROADCAST RECEIVER Define: <receiver android:name="MyScheduleReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" />

    </intent-filter> </receiver> Receive: public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // do something here } }
  20. TOPICS 1. User Interface Thread 2. Restore Activity State 3.

    Device Independent Pixel 4. Services 5. Content Providers 6. Broadcast Receivers
  21. ?