160 likes | 341 Views
cosc 4730. Brief return Sockets And HttpClient And AsyncTask. Networking. Android networking is built on standard Java SE So use the same network code you learned earlier. See the source code example, Android TCPclient and TCPserv for examples that run on the Android platform.
E N D
cosc 4730 Brief return Sockets And HttpClient And AsyncTask
Networking • Android networking is built on standard Java SE • So use the same network code you learned earlier. • See the source code example, Android TCPclient and TCPserv for examples that run on the Android platform.
Permissions! • Android app require a permission line in the AndroidManifest.xml • Otherwise it fails to work. • The line must be in specific place as well. Putting in the work spot, causes it to be ignored.
AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.cosc4755.TCPclient" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".TCPclient" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdkandroid:minSdkVersion="5" /> <uses-permission android:name="android.permission.INTERNET" /> </manifest>
simulator • For server code, you need to tell the simulator to accept the port number • In android-sdk-windows\tools directory, run the following dos command • adb forward tcp:3012 tcp:3012 • assuming you are using port 3012
References • Android dev site of course • http://developer.android.com/intl/zh-CN/reference/android/net/package-summary.html • Socket programming tutorial. http://www.anddev.org/socket_programming-t325-s30.html
Main thread and network. • Networking can take some time and should not be done on the main thread • Ie it can lock up the drawing. • As of v11 (honeycomb) • It will force close if you attempt networking on the main thread. • It must be done in a thread • Or a AsyncTask
HttpClient • This is a modified version of Apache’s HttpClient • http://hc.apache.org/httpclient-3.x/ • Used a lot with the J2EE space
Use • Create an HttpClient • Instantiate a new HTTP method • PostMethod or GetMethod • Set HTTP parameter names/values • Execute the HTTP call using the HttpClient • Process the HTTP response.
Example get HttpClientclient = new DefaultHttpClient(); HttpGetrequest = new HttpGet(); request.setURI(new URI("http://www.uwyo.edu/")); HttpResponseresponse = client.execute(request); • To add parameters to a get HttpGet method = new HttpGet( "http://www.com/do.php?key=valueGoesHere"); HttpResponse response = client.execute(method);
Example Post • HttpClient client = new DefaultHttpClient(); • HttpPost request = new HttpPost("http://somewebsite/do.php"); • List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); • postParameters.add(new BasicNameValuePair("one", "valueGoesHere")); • UrlEncodedFormEntityformEntity = new UrlEncodedFormEntity(postParameters); • request.setEntity(formEntity); • HttpResponse response = client.execute(request);
AsyncTask • This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. • AsyncTasks should ideally be used for short operations (a few seconds at the most.) otherwise you should use threads and handlers.
AsyncTask (2) • An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute. • doInBackground runs in the background. • onProgressUpdate and onPostExecute are executed on the main/UI thread • Meaning they can also update the widgets. • The return value from doInBackground is called as parameter to onPostExecute • publishProgress (called in doInBackground) invokes the onProgressUpdate
AsyncTask Example private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) {int count = urls.length; long totalSize = 0; for (inti = 0; i < count; i++) {totalSize += Downloader.downloadFile(urls[i]);publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called if (isCancelled()) break; }return totalSize;} //background thread protected void onProgressUpdate(Integer... progress) {setProgressPercent(progress[0]);} //UI thread protected void onPostExecute(Long result) {showDialog("Downloaded " + result + " bytes");} //UI thread} • Once created, a task is executed very simply: new DownloadFilesTask().execute(url1, url2, url3); URL is pamaters to doInBackground Integer is the value for publishProgress and onProgressUpdate And Long is the return value and parameter to onPostExecute The call, uses URL to create the “list” used in doInBackground
Rest of the examples • See the hand page pages for the rest of the source code for the examples. • HttpClientDemo.zip uses threads • HttpClientDemo2.zip uses AsyncTask
Q A &