(o) want network ?
(o) network client -> HttpURLConnection
https://developer.android.com/reference/java/net/HttpURLConnection.html
(o) simple get (_v1_get()) =>
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
// NOTE: std in/out streams do not have buffering; better use Buffered* classes !
http://developer.android.com/reference/java/io/BufferedOutputStream.html
with at lest 2 problems ;) by default (as opposite of our good intensions to use Networking);
more info for what we have as network(ing): detect wifi or mobile inside meConnected() for example.
for everything else: https://developer.android.com/training/basics/network-ops/managing.html (like user prefs for networking);
(o) by the book way: AsyncTask, namely _v2_get();
http://developer.android.com/reference/android/os/AsyncTask.html
NOTE (quoting):
The three TYPES used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:
private class MyTask extends AsyncTask { ... }
The 4 steps, we have to implement !!! (by the book);
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
But hey?! how to .start() this? -> new MyAsyncTask().execute(Params... params)
hmm... try #01:
04-25 14:15:13.844 1379-1454/net.yaht.m.backproc V/=-= AnAsyncGet, doInBackground(): BEGIN
04-25 14:15:33.884 1379-1379/net.yaht.m.backproc V/=-= AnAsyncGet, onPostExecute(): java.net.UnknownHostException: Unable to resolve host "rmi.yaht.net": No address associated with hostname
try #02:
04-25 14:19:03.528 5102-5148/net.yaht.m.backproc V/=-= AnAsyncGet, doInBackground(): BEGIN
04-25 14:19:03.916 5102-5148/net.yaht.m.backproc V/=-= AnAsyncGet, doInBackground(), server response code:: 200
04-25 14:19:03.920 5102-5102/net.yaht.m.backproc V/=-= AnAsyncGet, onPostExecute(): java.lang.NullPointerException: src == null
try #03:
04-25 14:20:16.200 6239-6319/net.yaht.m.backproc V/=-= AnAsyncGet, doInBackground(): BEGIN
04-25 14:20:16.284 6239-6319/net.yaht.m.backproc V/=-= AnAsyncGet, doInBackground(), server response code:: 200
04-25 14:20:16.288 6239-6319/net.yaht.m.backproc V/=-= AnAsyncGet, doInBackground(): END
04-25 14:20:16.288 6239-6239/net.yaht.m.backproc V/=-= AnAsyncGet, onPostExecute(): Index of /repo Index of /repo
Apache/2.2.22 (Debian) Server at m.yaht.net Port 80
and what about http post ?! - the only important thing, it just needs to be handled correctly :)
(o) what are our other option(s)?
remember Intent(s)? the other thing they were good for, was Services...
4 long running tasks we can use Service(s):
two major types: Started and Bound.
Started: A service is "started" when an application component (such as an activity) starts it by calling startService().
Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.
Usually, a started service performs a single operation and does not return a result to the caller.
For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.
Bound: A service is "bound" when an application component binds to it by calling bindService().
A bound service offers a client-server interface that allows components to interact with the service,
send requests, get results, and even do so across processes with interprocess communication (IPC).
A bound service runs only as long as another application component is bound to it.
Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.
NOTE: Caution: A service runs in the main thread of its hosting process—the service does not create its own
thread and does not run in a separate process (unless you specify otherwise).
This means that, if your service is going to do any CPU intensive work or blocking operations
(such as MP3 playback or networking), you should create a new thread within the service to do that work.
By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's
main thread can remain dedicated to user interaction with your activities.
One more time we subclass Service class. 4 major methods:
onStartCommand() - called when someone requests to start a service (for example activity); once executed, we are in game;
how log - indefinitely; or until stopSelf() || stopService();
onBind() - called by system when someone wants to bind() to a Service (with bindService() method);
IBinder plays a major role here;
onCreate() - when service is first created, this one is called;
to perform one time setup procedure (before onStartCommand() || onBind());
onDestroy() - when services are no longer used; here is the cleanup place for our service infrastructure;
NOTE: If a component starts the service by calling startService() (which results in a call to onStartCommand()),
then the service remains running until it stops itself with stopSelf() or another component stops it by calling stopService().
two kinds of started Service(s):
Service
This is the base class for all services. When you extend this class, it's important that you create a new thread
in which to do all the service's work, because the service uses your application's main thread, by default,
which could slow the performance of any activity your application is running.
IntentService
This is a subclass of Service that uses a worker thread to handle all start requests, one at a time.
This is the best option if you don't require that your service handle multiple requests simultaneously.
All you need to do is implement onHandleIntent(),
which receives the intent for each start request so you can do the background work.
NOTE: do not forget to offer them in application's manifest file...
the easier one: IntentService - we need an constructor and onHandleIntent;
but: If you decide to also override other callback methods, such as
onCreate(), onStartCommand(), or onDestroy(),
be sure to call the super implementation, so that the IntentService can properly
handle the life of the worker thread.
when we extend intent service class we already have the following:
The IntentService does the following:
Creates a default worker thread that executes all intents delivered to onStartCommand() separate from your application's
main thread.
Creates a work queue that passes one intent at a time to your onHandleIntent() implementation,
so you never have to worry about multi-threading.
Stops the service after all start requests have been handled, so you never have to call stopSelf().
Provides default implementation of onBind() that returns null.
Provides a default implementation of onStartCommand() that sends the intent to the work queue
and then to your onHandleIntent() implementation.
When we subclass Service, we should do all the upper work for ourselves ...
how to stop? stopService(intent) or stopSelf();
the only communication with user - Toasts || notifications;
(o) last but not least :)
Or bound service - IBinder :( It's a kind of too complex thing ... with all of that client-server "semi-imaplementation".
Bult let's see it in action;
more info on services: http://developer.android.com/guide/components/services.html