network connection web service - wordpress.com...pengembangan aplikasi perangkat bergerak (mobile) k...
TRANSCRIPT
PENGEMBANGAN APLIKASIPERANGKAT BERGERAK
(MOBILE)
K Candra Brata
Mobille App Lab 2015-2016
“Network ConnectionWeb Service
http://developer.android.com/training/basics/network-ops/connecting.htmlNetwork Connection
To perform the network operations Android application manifestmust include the following permissions:
HTTP connection
Most network-connected Android apps use HTTP to send andreceive data.
Java provides a general-purpose, lightweight HTTP client API toaccess 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 availablein HttpURLConnection class. They are listed below
HTTP connection
disconnect() This method releases this connection so that its resources may be either reused or closed.
getRequestMethod() This method returns the request method which will be used to make the request to the remote HTTP server
getResponseCode() This method returns response code returned by the remote HTTP server
setRequestMethod(String method) This method Sets the request command which will be sent to the remote HTTP server.
usingProxy() This method returns whether this connection uses a proxy server or not
Obviously the network on an Android device is not alwaysavailable. You must check the network is currently availablebefore do some HTTP request .
This requires the ACCESS_NETWORK_STATE permission inmanifest.
Check the network availability
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">
<TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:text="HTTP Connection"android:textSize="25sp" />
<ImageViewandroid:id="@+id/imageView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/textView"android:layout_centerHorizontal="true" />
<Buttonandroid: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.Javapublic class MainActivity extends AppCompatActivity {
private ProgressDialog progressDialog;private Bitmap bitmap = null;private Button b1;
@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {
checkInternetConenction();downloadImage ("http://1.bp.blogspot.com/-
r4_dSLP80g0/Ty3lIThZCWI/AAAAAAAAAhs/_U5_k2a73Tw/s1600/dota+2+logo+white.png");}
});
}.....
MainActivity.Javaprivate boolean checkInternetConenction() {
// get Connectivity Manager object to check connectionConnectivityManager connec
=(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);
// Check for network connectionsif ( 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;
}
MainActivity.Javaprivate void downloadImage(String urlStr) {
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.Javaprivate 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 ServiceInteroperability has Highest Priority
A web service is a standard for exchanging information betweendifferent 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 relieson a simple URL request.
Web Service
REST web service example
activity_main.XML// ADD this View widget in Layout XML
<TextViewandroid: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" />
<Buttonandroid: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.Javapublic class MainActivity extends AppCompatActivity {
private ProgressDialog progressDialog;private Bitmap bitmap = null;private Button b1, b2;private String webcontent;
@Overrideprotected 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() {@Overridepublic 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() {@Overridepublic void onClick(View v) {
checkInternetConenction();readStream( "http://plantplaces.com/perl/mobile/viewplantsjson.pl?Combined_Name=Merlot");
}});
}.....
MainActivity.Javaprivate 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();
}};
InstallApache Web Server 2.0/2.2http://httpd.apache.org/
PHP 5.3.xhttp://php.net
MySQL 5.xhttp://dev.mysql.com/downloads
Atau:
XAMPPhttp://www.apachefriends.org/en/xampp.html
Next Week Preparation !!
Thanks!QUESTIONS?
https://groups.google.com/d/forum/papb_tif_c
JOIN !!