Tuesday, October 28, 2014

Coursera Android Notifications, Broadcast Receivers, AsyncTask (week 5)

Notifications pt1 slides & presentation

Notifications- messages shown to users outside normal interface (i.e download finishes and show message 1) toast messages pop up on screen 2) notification area status area system control notification area at top of device

Toasts (temporary messages that fade in/ fade out) - success or not, wont gather information
Dialog
Notification area - unpredictable events that don't interrupt


Toast.makeText(text,context,duration)
Toast.show()
Toast.makeText(getApplicationContext(), "You're toast!", Toast.LENGTH_LONG).show();
Toast with custom view
setView() - inflated view passed in


Notifications pt2 presentation

Notification area status bar where alert user of events User Interface

component called a drawer where they can pull it down to see more details

Notification can have title, detail, or icon
Notification area small ticker text, and an icon
Notification drawer to view and an action if they click on one of items - can attach an intent, can create a custom view


There is a notification Manager - system service that manages notifications

Notification.Builder notificationBuilder = new Notification.Builder     ( getApplicationContext())        .setTicker(tickerText)           .setSmallIcon(android.R.drawable.stat_sys_warning)         .setAutoCancel(true) .setContentTitle(contentTitle)         .setContentText( contentText + " (" + ++mNotificationCount + ")")           .setContentIntent(mContentIntent).setSound(soundURI)         .setVibrate(mVibratePattern); 
// Pass the Notification to the NotificationManager: NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(MY_NOTIFICATION_ID, notificationBuilder.build());


creates a PendingIntent using the PendingIntent.getActivity() method. The call to that method passes in an Intent flag, Intent.FLAG_ACTIVITY_NEW_TASK so that The underlying Intent may be called outside of an existing Activity.

  ContentIntent = PendingIntent.getActivity(getApplicationContext(), 0, mNotificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

Broadcast Receiver pt1 slides & presentation

BroadcastReceiver - base class
receive messages for that which interested, informed of events via intents, these intents broadcasted to system, delivered to those that are registered to receive them
receives event by OnReceive() being called, broadcast receivers handle event

statically by android manifest xml file:
<receiver> with <intent-filter>:

<receiver
android: enabled -True/False to enabled
android : exported : outside its application
android : name - name of class implements this receiver
android : permission 
<intent-filter
action,data,categories in intent filter

boot up - registration gets bootstrapped

SingleBroadcastStatic


<receiver android:name=".Receiver" android:exported="false" >
<intent-filter>
     <action android:name="course.examples.BroadcastReceiver.show_toast" > </action>
</intent-filter>
</receiver>

sendBroadcast()
sendBroadcast(new Intent(CUSTOM_INTENT),android.Manifest.permission.VIBRATE);

public class Receiver extends BroadcastReceiver {  
private final String TAG = "Receiver";  
@Override public void onReceive(Context context, Intent intent) {


Dynamically - register it dynamically at runtime 

intent filter, broadcast receiver, registerReceiver

LocalBroadcastManager class - only within 1 app
Context class - system wide by any application

Context.registerReceiver()  - receiver will be called with any broadcast Intent that matches filter, in the main application thread.

BroadcastReceiver.onRecieve()

BcastRecSinBcastDynReg
mBroadcastMgr = LocalBroadcastManager .getInstance(getApplicationContext()); mBroadcastMgr.registerReceiver(receiver, intentFilter);
...       mBroadcastMgr.sendBroadcast(new Intent(CUSTOM_INTENT)); 

...       protected void onDestroy() { mBroadcastMgr.unregisterReceiver(receiver);


normal - undefined order
ordered - multiple in priority order
sticky intent - sticks around may still receive it (i.e. battery state changes)
non-sticky : discarded after initial broadcast
permission can be applied

FLAG_DEBUG_LOG_RESOLUTION - set intent flag to this for debugging


Broadcast Receiver pt2  presentation


Delivered to OnReceive (context,intent) -  android may have to start receiver , high priority when running, expensive short lived, should not block. runs in main thread, event handling should not be lengthy, try service for processing if lengthy , android may terminate onReceive() receiver, receivers cant start asynch operations.

BcastRecCompBcast in CompoundBroadcast.java - sent out normally

BcastRecCompOrdBcast in SendOrderedBroadcast (priority order)
sendOrderedBroadcast(new Intent(CUSTOM_INTENT), android.Manifest.permission.VIBRATE);

BcastRecCompOrdBcastWithResRec 


<receiver android:name=".Receiver2" android:exported="false" > 
<intent-filter android:priority="10" > <action android:name="course.examples.BroadcastReceiver.show_toast" > </action> </intent-filter> </receiver> 

<receiver android:name=".Receiver3" android:exported="false" > 
<intent-filter android:priority="1" > <action android:name="course.examples.BroadcastReceiver.show_toast" > </action> </intent-filter> </receiver>


IntentFilter intentFilter = new IntentFilter(CUSTOM_INTENT);
intentFilter.setPriority(3); 
registerReceiver(mReceiver, intentFilter);

Intent with priority 10 received first, followed by priority 3, however broadcast canceled by this call in receiver:

if (isOrderedBroadcast()) {abortBroadcast(); }



CompoundOrderedBroadcastWithResultReceiver.java  has different parms for method with call back like method when all receivers have been invoked.

non-sticky event is over it disposes of event,  where as sticky is opposite. want event to remain when receiver is not registered (persist over time). an example is a battery going low.  sticky events are cached by android.  new intents override older intents they match.

BcastRecStickyInt

sendStickyBroadcast , sendStickyOrderedBroadcast

BROADCAST_STICKY permission required

telnet localhost port#

power capacity 95

Messaging pt1 slides & presentation

Multiple apps running at same time -Multithreaded
Thread - computations running at same time in process , own program counter and stack, but share heap
java.lang.thread
Runnable run()
http://docs.oracle.com/javase/tutorial/essential/concurrency/threads.html

start() - start thread,
sleep(time) - suspend thread
 wait() waits until another thread invokes the notify() on the object
notify() - wakes up a single thread that is waiting()

instantiate - use new thread() , but doesn't start thread
start thread - invoke start() and run() gets called
thread terminates - when run() returns

ThreadingNoThreading
-load icon that takes a while
- other button toast message ,
- operation preventing the other button working

ThreadingSimple
- views created by other threads can be allowed to launch it

applications have main thread (UI thread), application complements in same  process use same UI thread, life cycle methods handled in UI thread, UI toolkit not thread safe, blocking UI thread hurts applications responsiveness, long running operations need to be put in background threads. thus, dont access UI components from non-UI thread, But, update UI in UI thread.

methods that are guaranteed to run in UI thread:
- boolean View.post(Runnable action)(
- void Activity.runOnUiThread(Runnable action)

ThreadingViewPost

Async Tasks and Messaging pt2 presentation

Async Task - short operations
managing tasks involve work background thread and UI thread

  • bg thread - long running operations report their progress
  • ui thread  - initial setup, intermediate progress, completing operation after background does its work


class AsyncTask <Params,Progress,Results>

params -type used in background work
progress - type used when indicating progress 
result - type of result

OnPreExecute() - run in UI thread before doInBackground() starts
Result given in doInBackground() does most of works

may call publishProgress() long running progress

onProgressUpdate() to UI update

onPostExecute() in UI thread

ThreadingAsyncTask application added progress bar, how much of bit map loading is complete

AsyncTaskActivity has an inner class:
   class LoadIconTask extends AsyncTask<Integer, Integer, Bitmap> {

when someone clicks button:
   new LoadIconTask().execute(R.drawable.painter);

OnPreExecute()  in LoadIconTask
    run on UIThread and sets visibility

doInBackground() - passed in resource Id and does work of loading bitmap
    call periodically publishProgress()

OnProgressUpdate() -UIThread
   receives integer passed in to publishProgress and updates the screen percentage loaded

OnPostExecute -UIThread
   receives bitmap and makes it visible



Handler - handing off work between any 2 threads, more flexible for any 2 threads


each handler assoc specific threads - send messages and posting runnables

messages - has data sent so can run in another thread

thread has : message queue and looper

message queue -data struct holds messages and runnables dispatched by looper

handler post()

handler sendMessage() method

- message placed on message queue

handler waiting -looper reacts based on what arrived

if message , handlemessage() method
if runnable, calls runnables run() method


runnable- post(runnable r)

postAtTime()

postDelayed()

create messages- create message Handler.obtainMessage()

Message.obtain() - set data for message
sendMessage()

sendMessageAtFrontOfQueue

sendMessageAtTime()

sendMessageDelayed()

ThreadingHandlerRunnable application

Class HandlerRunnableActivity

class LoadIconTask implements runnable

when someone clicks button:
   new Thread(new LoadIconTask(R.drawable.painter)).start();

 LoadIconTask class run method ()
   posts runnable:
      handler.post(new Runnable() { @Override public void run() {
mProgressBar.setVisibility(ProgressBar.VISIBLE); } });

 Subsequent to first post is several other  handler posts

ThreadingHandlerMessages application

in the LoadIconTask, it looks at message it receives by calling handler.obtainMessage()

calls sendMessage for Handler to execute

Android supports several HTTP clients - HttpURLConnection recommended


Runnables are used when the Sender implements the action to be taken.

Messages are used when the Handler implements the Message response​



MainActivity extends Activity implements SelectionListener

- onCreate calls ensureData()
- onResume
    // Register the BroadcastReceiver to receive a 
    // DATA_REFRESHED_ACTION broadcast
   IntentFilter filter = new IntentFilter();
   filter.addAction(DATA_REFRESHED_ACTION);
   registerReceiver(mRefreshReceiver, filter);
-onPause
      unregisterReceiver(mRefreshReceiver);


DownloaderTask extends AsyncTask<String, Void, String[]> 

private MainActivity mParentActivity;
protected String[] doInBackground(String... urlParameters) {
     -> calls download(urlParameters);
- download method simulates tweets and then calls notify(downloadCompleted);
- notify() :
      // Sends an ordered broadcast to determine whether MainActivity is
      // active and in the foreground. Creates a new BroadcastReceiver
      // to receive a result indicating the state of MainActivity
      // The Action for this broadcast Intent is
     // MainActivity.DATA_REFRESHED_ACTION
     // The result MainActivity.IS_ALIVE, indicates that MainActivity 
     // is active and in the foreground.

      







No comments:

Post a Comment