04 android network programming

Post on 17-Jul-2016

32 Views

Category:

Documents

5 Downloads

Preview:

Click to see full reader

DESCRIPTION

Android Network Programming

TRANSCRIPT

Android Network Programming

Materi Hari ini

• Pemrograman di Android• Pemrograman Jaringan di Android

Pemrograman di Android

Materi

• Pengenalan Android• Hello World!!!• Komponen Aplikasi Android• Android UI

Pengenalan Android

Apa itu Android?

• Sistem operasi terbuka untuk perangkat mobile.

• Dikembangkan oleh Google bersama Open Handset Alliance

• Versi terbaru : Android KitKat(4.4)

Mengapa Android?

• Large market share– 50% of smartphone

• Open platform– Get source code

and make your own• Run anywhere

– smartphone, TV• Develop

everywhere– Linux, Windows,

Mac

Hello World!!!

Requirement

• OS : Linux, Windows, Mac• Java : JRE dan JDK• Android SDK• Eclipse IDE• Eclipse ADT Plugin• Emulator/Device asli

– Emulator default– Genymotion

Instalasi

• Ikuti tutorial berikut– http://developer.android.com/sdk/

installing/index.html– http://developer.android.com/sdk/

installing/installing-adt.html

Project Baru : Hello World !!!!

• Demo

Struktur Project Android• src : kode Java• gen : kode Java yang digenerate otomatis• Main Library

– Android 4.2.2– Android Private Library– Android Dependencies

• assets : aset apps misal database lokal, file.

• bin : file apk apps• res : resource apps

– drawable* : image yang digunakan dalam apps

– layout : layout dalam apps– menu : menu dalam apps– values : nilai yang dipake dalam apps misal

ukuran layout, string, dll.• AndroidManifest.xml : konfigurasi

umum apps meliputi– nama activity, service yang terdaftar– permission

Komponen Aplikasi Android

Komponen Aplikasi Android

• Activity• Service• Content Provider• Intent• Broadcast Receiver• Widget• Notification

Android Manifest<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.helloworld" android:versionCode="1" android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" />

<uses-permission android:name="android.permission.INTERNET" />

<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.helloworld.MainActivity" android:label="@string/app_name" > </activity> <activity android:name="com.example.helloworld.InternetActivity" android:label="@string/title_activity_internet" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>

Permission

Setting main activity

Activity

Activity

• Foreground dari sebuah apps

• Banyak interaksi user

• UI diimplementasi di atas Activity

• Activity bisa dipecah jadi beberapa Fragment

Membuat Activity Baru

• Klik kanan project• Pilih New > Other > Pilih Android >

Android Activity• Pilih Empty Activity pada pilihan

template• Beri nama Activity• Secara otomatis akan dibuat Activity

baru misal : NewActivity.java beserta file xml layoutnya

Code : Activity

public class NewActivity extends Activity {

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_empty);}

}

Activity Life Cycle

Perpindahan Antar Activity

• Perpindahan antar activity bisa dilakukan dengan memanfaatkan class Intent

Intent intent = new Intent (MainActivity.this,SecondActivity.class );startActivity(intent);

Fragmented Activity

• Satu Activity dapat dipecah menjadi beberapa fragment/bagian

• Referensi bacaanhttp://developer.android.com/guide/components/fragments.html

Service

• Background dari sebuah apps

• Sedikit interaksi user

• TIDAK ada UI• Contoh

penggunaan :– Whatsapp tetap bisa

menerima message walaupun keluar apps

Service

Server

Membuat Service Baru

• Klik kanan project• Pilih New > Class• Beri nama Class misal DemoService• Tambahkan service yang dibuat di

AndroidManifest.xml

<service android:name="com.example.demoactivityfragment.DemoService">

</service>

Code : Servicepublic class DemoService extends Service{

@Overridepublic IBinder onBind(Intent intent) {

// TODO Auto-generated method stubreturn null;

}

@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {

}}

Service Life Cycle

Memanggil Service dari Activity

• Service dapat dijalankan dan dihentikan dari Activity

• Contoh menjalankan ServiceIntent i= new Intent(getApplicationContext(), DemoService.class);startService(i);

Komunikasi Antara Activity dan Service

• kenapa butuh komunikasi?– Activity di foreground– Service di background

• Komunikasi bisa dilakukan lewat BrodcastMessage

Komunikasi Activity-Service dengan Broadcast

• Mengirim datavoid sendBroadcastMessage(String message, String type){Intent intent = new Intent();intent.putExtra("DATA", message);intent.setAction(type);sendBroadcast(intent);}

• Keterangan :– message : data yang akan dikirim. Data yang

dikirim diberi label "Data". Label harus unik dan harus disepakati oleh pengirim dan penerima

– type : tipe pesan yang akan dikirim. Sifatnya harus unik dan harus disepakati oleh pengirim dan penerima. Misal DemoService.DEMO_ACTIVITY_MSG

Komunikasi Activity-Service dengan Broadcast

• Menerima DataBroadcastReceiver ActivityReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();Bundle extras = intent.getExtras();if(action.equalsIgnoreCase(DemoService.DEMO_ACTIVITY_MSG)){String data = extras.getString("DATA");}}};

• Daftarkan Receiver di fungsi onCreate()IntentFilter filter = new IntentFilter();filter.addAction(DemoService.DEMO_ACTIVITY_MSG);registerReceiver(ActivityReceiver, filter);

• Keterangan :– extras.getString("DATA") : mendapatkan data berdasarkan label yang

disepakati dengan pengirim– if(action.equalsIgnoreCase(DemoService.DEMO_ACTIVITY_MSG))

: Hanya terima pesan dengan type yang disepakati

Android User Interface

Overview

• Secara umum, Android UI terbagi menjadi dua pokok bahasan :– Layout– Component

Layout

• Layout mengatur tata letak komponen-komponen pada Android UI

• Layout dapat berupa kode Java atau xml• Kode xml diletakkan di folder res/layout• Jenis layout

– Linear Layout– Relative Layout– Table Layout– Grid Layout

Linear Layout

• Komponen ditata dalam sebuah urutan

• Jenis urutan– Vertikal– Horizontal

• Antar komponen dapat diberi margin/jarak

Contoh Linear Layout Horizontal<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" >

<TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" />

<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" />

<TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Contoh Linear Layout Vertikal<?xml version="1.0" encoding="utf-8"?><LinearLayout

xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >

<TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" />

<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" />

<TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Relative Layout

• Komponen diletakkan relatif terhadap komponen lainnya

• Flexibel– Sebuah komponen dapat diletakkan di

kanan, kiri, atas atau bawah komponen lain.

• Jarak antar komponen bisa diatur

Relative Layout<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" >

<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginRight="57dp" android:layout_marginTop="36dp" android:text="Button" />

<TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button1" android:layout_alignBottom="@+id/button1" android:layout_alignParentLeft="true" android:layout_marginLeft="36dp" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/textView1" android:layout_below="@+id/button1" android:layout_marginTop="30dp" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Komponen

• Ada beberapa komponen UI pada Android– TextView– EditText– Button– ImageButton– CheckBox– RadioButton– dll.

Komponen

• Demo

Bahan Bacaan

• Android Programming Guidehttp://developer.android.com/guide/index.html

• Android Traininghttp://developer.android.com/training/index.html

• Android Design Patternhttp://developer.android.com/design/index.html

Latihan• BMI adalah sebuah index yang menunjukkan apakah berat

badan seseorang dikatakan ideal.• Input :

– Berat Badan (kg)– Tinggi Badan (m)

• Rumus : BMI = Berat/Tinggi2• Ketentuan skor BMI

– Very severely underweight less than 15– Severely underweight from 15.0 to 16.0– Underweight from 16.0 to 18.5– Normal (healthy weight) from 18.5 to 25– Overweight from 25 to 30– Obese Class I (Moderately obese) from 30 to 35– Obese Class II (Severely obese) from 35 to 40– Obese Class III (Very severely obese) over 40

Pemrograman Jaringan di Android

Materi

• HTTP• Raw socket

Overview

• Android/Java dibekali library untuk melakukan komunikasi lewat jaringan.– HTTP Library– Raw Socket Library

• Komunikasi jaringan TIDAK boleh dilakukan di foreground process.

• Alternatif :– AsyncTask– Thread– Service

HTTP

• Pakai library HttpURLConnection• Contoh :URLConnection connection = url.openConnection();HttpURLConnection httpConnection = (HttpURLConnection) connection;int responseCode = httpConnection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {

InputStream inputStream = httpConnection.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);StringBuilder sb = new StringBuilder();

String line = null;while ((line = reader.readLine()) != null){

sb.append(line + "\n");}result = sb.toString();

}

HTTP : Complete Code

• Demo

Raw Socket

• socket = new Socket(hostname, port)Inisialisasi dan membuka koneksi socket

• socket.getInputStream();Mendapatkan input stream untuk pembacaan

• socket.getOutputStream();Mendapatkan output stream untuk penulisan

• socket.close();Menutup socket

Raw Socket : Complete Code

• Demo

top related