PENGEMBANGAN APLIKASI PERANGKAT BERGERAK (MOBILE) Network Connection Web Service K Candra Brata andra.course@gmail.com Mobille App Lab 2015-2016
Network Connection http://developer.android.com/training/basics/network-ops/connecting.html
HTTP connection To perform the network operations Android application manifest must include the following permissions:
HTTP connection Most network-connected Android apps use HTTP to send and receive data. Java provides a general-purpose, lightweight HTTP client API to access resources via the HTTP or HTTPS protocol. java.net.url class and the java.net.httpurlconnection class. The Android platform includes the HttpURLConnection client, which supports HTTPS, streaming uploads and downloads, configurable timeouts, IPv6, and connection pooling. HttpURLConnection allows you to create an InputStream.
HTTP connection java.net.url class HttpURLConnection class.
HTTP connection HttpURLConnection class. A part from this connect method, there are other methods available in HttpURLConnection class. They are listed below disconnect() getrequestmethod() getresponsecode() setrequestmethod(string method) usingproxy() This method releases this connection so that its resources may be either reused or closed. This method returns the request method which will be used to make the request to the remote HTTP server This method returns response code returned by the remote HTTP server This method Sets the request command which will be sent to the remote HTTP server. This method returns whether this connection uses a proxy server or not
Check the network availability Obviously the network on an Android device is not always available. You must check the network is currently available before do some HTTP request. This requires the ACCESS_NETWORK_STATE permission in manifest.
activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".mainactivity"> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:text="http Connection" android:textsize="25sp" /> <ImageView android:id="@+id/imageview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textview" android:layout_centerhorizontal="true" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/imageview" android:layout_centerhorizontal="true" android:layout_margintop="50dp" android:text="button" /> </RelativeLayout>
MainActivity.Java public class MainActivity extends AppCompatActivity { private ProgressDialog progressdialog; private Bitmap bitmap = null; private Button b1;... @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); b1 = (Button) findviewbyid(r.id.button); b1.setonclicklistener(new View.OnClickListener() { @Override public void onclick(view v) { checkinternetconenction(); downloadimage ("http://1.bp.blogspot.com/- r4_dslp80g0/ty3lithzcwi/aaaaaaaaahs/_u5_k2a73tw/s1600/dota+2+logo+white.png"); );
MainActivity.Java private boolean checkinternetconenction() { // get Connectivity Manager object to check connection ConnectivityManager connec =(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE); // Check for network connections if ( connec.getnetworkinfo(0).getstate() == android.net.networkinfo.state.connected connec.getnetworkinfo(0).getstate() == android.net.networkinfo.state.connecting connec.getnetworkinfo(1).getstate() == android.net.networkinfo.state.connecting connec.getnetworkinfo(1).getstate() == android.net.networkinfo.state.connected ) { Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show(); return true; else if (connec.getnetworkinfo(0).getstate() == android.net.networkinfo.state.disconnected connec.getnetworkinfo(1).getstate() == android.net.networkinfo.state.disconnected ) { Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show(); return false; return false;
private void downloadimage(string urlstr) { MainActivity.Java progressdialog = ProgressDialog.show(this, "", "Please Wait..!! \n Downloading Image... "); final String url = urlstr; new Thread() { public void run() { InputStream in = null; Message msg = Message.obtain(); msg.what = 1; try { in = openhttpconnection(url); bitmap = BitmapFactory.decodeStream(in); Bundle b = new Bundle(); b.putparcelable("bitmap", bitmap); msg.setdata(b); in.close(); catch (IOException e1) { e1.printstacktrace(); messagehandler.sendmessage(msg);.start(); private Handler messagehandler = new Handler() { public void handlemessage (Message msg) { super.handlemessage(msg); ImageView img = (ImageView) findviewbyid(r.id.imageview); img.setimagebitmap((bitmap) (msg.getdata().getparcelable("bitmap"))); progressdialog.dismiss(); ;
MainActivity.Java private InputStream openhttpconnection(string urlstr) { InputStream in = null; int rescode = -1; try { URL url = new URL(urlStr); URLConnection urlconn = url.openconnection(); if (!(urlconn instanceof HttpURLConnection)) { throw new IOException("URL is not an Http URL"); HttpURLConnection httpconn = (HttpURLConnection) urlconn; httpconn.setallowuserinteraction(false); httpconn.setinstancefollowredirects(true); httpconn.setrequestmethod("get"); httpconn.connect(); rescode = httpconn.getresponsecode(); if (rescode == HttpURLConnection.HTTP_OK) { in = httpconn.getinputstream(); catch (MalformedURLException e) { e.printstacktrace(); catch (IOException e) { e.printstacktrace(); return in;
REST Web Service Interoperability has Highest Priority
Web Service A web service is a standard for exchanging information between different types of applications irrespective of language and platform. For example, an android application can interact with PHP, java or.net application using web services. REpresentational State Transfer (REST) web service : REST relies on a simple URL request.
REST web service example
activity_main.xml // ADD this View widget in Layout XML <TextView android:id="@+id/textview2" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/imageview" android:layout_margintop="10dp" android:layout_centerhorizontal="true" android:text="http Response..." android:textcolor="#ff3615" android:textisselectable="false" android:textsize="12dp" android:gravity="center_horizontal" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/button" android:layout_centerhorizontal="true" android:layout_margintop="10dp" android:text="webcontent" />
MainActivity.Java public class MainActivity extends AppCompatActivity { private ProgressDialog progressdialog; private Bitmap bitmap = null; private Button b1, b2; private String webcontent; @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); b1 = (Button) findviewbyid(r.id.button); b2 = (Button) findviewbyid(r.id.button2); b1.setonclicklistener(new View.OnClickListener() { @Override public void onclick(view v) { checkinternetconenction(); downloadimage ("http://1.bp.blogspot.com/-r4_dslp80g0/ty3lithzcwi/aaaaaaaaahs/_u5_k2a73tw/s1600/dota+2+logo+white.png"); ); b2.setonclicklistener(new View.OnClickListener() { @Override public void onclick(view v) { checkinternetconenction(); readstream( "http://plantplaces.com/perl/mobile/viewplantsjson.pl?combined_name=merlot"); );...
MainActivity.Java private void readstream (String urlstr) { progressdialog = ProgressDialog.show(this, "", "Please Wait..!! "); final String url = urlstr; new Thread() { public void run() { InputStream in = null; Message msg = Message.obtain(); msg.what = 1; try { StringBuilder sb = new StringBuilder(); in = openhttpconnection(url); BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8")); String nextline = ""; while ((nextline = reader.readline())!= null) { sb.append(nextline); webcontent = sb.tostring(); in.close(); catch (IOException e) { e.printstacktrace(); messagehandler2.sendmessage(msg);.start(); private Handler messagehandler2 = new Handler() { public void handlemessage(message msg) { super.handlemessage(msg); TextView content = (TextView) findviewbyid(r.id.textview2); content.settext(webcontent); progressdialog.dismiss(); ;
Next Week Preparation!! Install Apache Web Server 2.0/2.2 http://httpd.apache.org/ PHP 5.3.x http://php.net MySQL 5.x http://dev.mysql.com/downloads Atau: XAMPP http://www.apachefriends.org/en/xampp.html
Thanks! QUESTIONS? JOIN!! https://groups.google.com/d/forum/papb_tif_c