phan 05 network

Upload: vuloi133

Post on 09-Oct-2015

11 views

Category:

Documents


0 download

DESCRIPTION

Phan 05 Network

TRANSCRIPT

  • Pht trin ng dng Smartphone

    Ti liu lu hnh ni b

    y l ti liu tham kho s dng trong mn hc Lp trnh ng dng Smartphone Android

    c tng hp, bin son t nhiu ngun bi cc thnh vin ca Nhm nghin cu v ng dng cng

    ngh A106-i hc Hoa Sen.

    Nhm A106-http://profiles.hoasen.edu.vn/groups/584/

  • Pht trin ng dng Smartphone Android

    Pht trin ng

    dng Smartphone

    Phn 05: Network & Telephony L c Huy

    Email: [email protected]

  • Pht trin ng dng Smartphone Android

    1 HTTP

    Chc nng ca HTTP nh l mt giao thc kiu gi yu cu-nhn hi p trong m hnh in

    ton my ch-my khch. Trn HTTP, mt trnh duyt web (Firefox, Internet Explorer, Chrome) s

    ng vai tr nh mt ngi khch, trong khi ng dng chy trn my ch (my trung tm) s ng vai

    tr nh l mt my ch. Ngi khash y s gi mt yu cu HTTP (HTTP request) ln my ch.

    My ch, ni lu tr mt ngun ti nguyn no (Hnh nh, m thanh) s thay mt my khch thc

    thi mt chc nng no l tr v mt hi p cho my khch. Hi p ny s bao gm thng tin trng

    thi v yu cu c gi i cng vi ni dung c yu cu bi my khch trong n. Giao thc HTTP

    c th hin qua hnh sau:

    Trong m hnh trn tn ti hai i tng chnh: Client v Server. Trong ng dn kt ni

    hai i tng chnh ca m hnh l giao thc HTTP. i tng Client s gi mt Request n my

    Server yu cu thc thi mt tc v hoc ly mt d liu no . i tng Request cha cc tham s

    xc nh a ch n c gi n cng vi cc tham s khc xc nh tc v cn thc thi cng nh

    loi d liu cn ly. Cc tham s ny c th thuc hai loi: POST v GET. Tham s thuc loi GET s

    nm trong ng dn a ch m i tng Request ang nm gi, tham s loi POST s khng nm

    trong ng dn a ch.

    VD: Gi i request c a ch sau: http://www.google.com.vn/search?q=leduchuy. y l mt

    request dng GET. Ta c th thy trn a ch trn c mt tham s q=leduchuy xc nh t kha yu

    cu my ch Google tm kim t kha: leduchuy.

    My Server s phn tch i tng Request tm ra yu cu ca my Client s l v tr v d

    liu trong i tng Response. My Client s phn tch i tng Response c tr v ly cc

    thng tin cn thit. y l cch m giao thc HTTP hot ng.

    Vic s dng giao thc HTTP trn Android hin nhin cng tun theo cch trn vi cc bc

    nh sau:

  • Pht trin ng dng Smartphone Android

    1.1 S dng HTTP vi GET Request

    1. Khi to mt i tng HttpClient.

    2. Khi to mt phng thc HTTP: PostMethod hoc GetMethod.

    3. Thit lp tham s cho phng thc HTTP.

    4. Thc thi HTTP request bng cch s dng HttpClient.

    5. Thao tao trn i tng Response c tr v.

    nh ngha mt class java nh sau:

    package niit.android;

    import java.io.BufferedReader;

    import java.io.IOException;

    import java.io.InputStreamReader;

    import java.net.URI;

    import org.apache.http.HttpResponse;

    import org.apache.http.client.HttpClient;

    import org.apache.http.client.methods.HttpGet;

    import org.apache.http.impl.client.DefaultHttpClient;

    public class NetworkManager {

    public String executeHttpGet(String uri) throws Exception

    {

    BufferedReader in = null;

    String result = "";

    try {

    HttpClient client = new DefaultHttpClient();

    HttpGet request = new HttpGet();

    request.setURI(new URI(uri));

    HttpResponse response = client.execute(request);

    in = new BufferedReader(new

    InputStreamReader(response.getEntity().getContent()));

    StringBuffer sb = new StringBuffer("");

    String line = "";

    String NL = System.getProperty("line.separator");

    while ((line = in.readLine())!=null) {

    sb.append(line + NL);

    }

    in.close();

  • Pht trin ng dng Smartphone Android result = sb.toString();

    } finally {

    if (in != null) {

    try {

    in.close();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    }

    return result;

    }

    }

    Trong :

    HttpClient i din cho my Client trong m hnh trn. Mt i tng HttpClient ng gi

    nhng tt c cc i tng cn thit thc thi mt HTTP request (a ch gi i, cc tham s i km).

    y cng l i tng s l cookie, chng thc ti khon, qun l kt ni cng nh cc tnh nng khc

    ca giao thc HTTP.

    S dng lnh: request.setURI(new URI("http://code.google.com/android/")); gn a ch

    s gi ng tng request i.

    Lnh HttpResponse response = client.execute(request); s thc thi mt HTTP request v tr

    v mt i tng Response.

    Lnh response.getEntity() s tr v mt i tng HttpEntity. y l i tng cha cc th

    HTML (HTML entity) c tr v t server.

    Lnh getContent() s tr v mt i tng kiu InputStream. y l mt i tng i din

    cho mt lung (stream) ni n khi d liu c tr v cha trong response. N s c dng c

    d liu t khi d liu ny.

    Tin hnh khi to mt i tng InputStreamReader bng lnh new InputStreamReader()

    to thnh mt b c t lung mi to trn.

    Tin hnh to mt BufferedReader bng lnh new BufferedReader() to thnh mt b c c

    h tr b m (buffer) tng tc vic c d liu t lun k trn.

    Tin hnh dng mt i tng String t d liu nhn v sau khi thc thi mt HTTP request.

    Thc t th i tng String ny chnh l chui cha ni dung HTML c tr v. Vic dng i tng

    String da vo StringBuffer ( sb.append(line + NL)).

    Lu : cho php ng dng kt ni Internet, ta cn b xung dng sau vo file

    AndroidManifest.xml:

  • Pht trin ng dng Smartphone Android

    1.2 S dng HTTP vi POST Request

    Cc bc lm vic vi giao thc HTTP cng vi mt request dng POST cng tng t nh

    vi request dng GET. Ta tin hnh nh ngha mt class java c ni dung nh sau:

    package niit.android;

    import java.io.BufferedReader;

    import java.io.IOException;

    import java.io.InputStreamReader;

    import java.net.URI;

    import java.util.ArrayList;

    import java.util.List;

    import org.apache.http.HttpResponse;

    import org.apache.http.NameValuePair;

    import org.apache.http.client.HttpClient;

    import org.apache.http.client.entity.UrlEncodedFormEntity;

    import org.apache.http.client.methods.HttpGet;

    import org.apache.http.client.methods.HttpPost;

    import org.apache.http.impl.client.DefaultHttpClient;

    import org.apache.http.message.BasicNameValuePair;

    public class NetworkManager {

    public String executeHttpPost(String

    uri,List postParameters) throws Exception {

    BufferedReader in = null;

    String result = "";

    try {

    HttpClient client = new DefaultHttpClient();

    HttpPost request = new HttpPost(uri);

    UrlEncodedFormEntity formEntity = new

    UrlEncodedFormEntity(

    postParameters);

    request.setEntity(formEntity);

    HttpResponse response =

    client.execute(request);

    in = new BufferedReader(new

    InputStreamReader(response.getEntity()

    .getContent()));

    StringBuffer sb = new StringBuffer("");

  • Pht trin ng dng Smartphone Android String line = "";

    String NL =

    System.getProperty("line.separator");

    while ((line = in.readLine()) != null) {

    sb.append(line + NL);

    }

    in.close();

    result = sb.toString();

    } finally {

    if (in != null) {

    try {

    in.close();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    }

    return result;

    }

    }

    Trong :

    Ta nh ngha List postParameters = new ArrayList();

    cha cc tham s gi i vi POST Request. Cc tham s ny l d liu dng thc thi cc hnh ng

    trn my ch hoc cc tham s dng xc nh d liu tr v.

    Dng lnh postParameters.add(new BasicNameValuePair("one", "valueGoesHere")); thm

    cc tham s vo danh sch tham s nh ngha trn.

    Tin hnh m ha s tham s trn gi km request: UrlEncodedFormEntity formEntity =

    new UrlEncodedFormEntity(postParameters);

    S dng class NetworkManager trn nh sau:

    String resultGet="";

    String resultPost="";

    NetworkManager networkManager = new NetworkManager();

    try {

    resultGet =

    networkManager.executeHttpGet("http://www.google.com.vn/search?q

    =hoasen+university");

    System.out.print(result);

    } catch (Exception e) {

  • Pht trin ng dng Smartphone Android

    e.printStackTrace();

    }

    }

    List postParameters = new

    ArrayList();

    postParameters.add(new BasicNameValuePair("q",

    "hoasen+university"));

    try {

    resultPost = networkManager.executeHttpPost("www.abc.com",

    postParameters);

    System.out.print(result);

    } catch (Exception e) {

    e.printStackTrace();

    }

    2 Telephony

    2.1 SMS

    2.1.1 Gi tin nhn

    To Project vi cc thng s:

    Project name: TelephonyExample

    Build target: Android 2.3.3.

    Application name: Telephony Example

    Package name: niit.android

    Create Activity: main

    ng dng c th gi/nhn tin nhn trn ng dng, ta cn b xung ng k trn file

    AndroidManifest.xml bng cch b xung hai dng sau:

    Chnh sa file main.xml vi ni dung nh sau:

  • Pht trin ng dng Smartphone Android

    c c giao din nh sau:

  • Pht trin ng dng Smartphone Android

    Thay i file main.java vi ni dung nh sau:

    package niit.android;

    import android.app.Activity;

    import android.app.PendingIntent;

    import android.content.Intent;

    import android.os.Bundle;

    import android.telephony.SmsManager;

    import android.view.View;

    import android.widget.Button;

    import android.widget.EditText;

    import android.widget.Toast;

    public class main extends Activity {

    Button btnSendSMS;

    EditText txtPhoneNo;

    EditText txtMessage;

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState)

    {

  • Pht trin ng dng Smartphone Android

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    btnSendSMS = (Button) findViewById(R.id.btnSendSMS);

    txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);

    txtMessage = (EditText) findViewById(R.id.txtMessage);

    btnSendSMS.setOnClickListener(new

    view.OnClickListener()

    {

    public void onClick(View v)

    {

    String phoneNo =

    txtPhoneNo.getText().toString();

    String message =

    txtMessage.getText().toString();

    if (phoneNo.length()>0 &&

    message.length()>0)

    sendSMS(phoneNo, message);

    else

    Toast.makeText(getBaseContext(),

    "Please enter both phone number and

    message.",

    Toast.LENGTH_SHORT).show();

    }

    });

    }

    //---sends an SMS message to another device---

    private void sendSMS(String phoneNumber, String message)

    {

    SmsManager sms = SmsManager.getDefault();

    sms.sendTextMessage(phoneNumber, null, message, null,

    null);

    }

    }

    gi mt tin nhn SMS, ta s dng mt i tng kiu SmsManager. Tuy nhin, khng ging

    nh cc class khc, ta khng tin hnh khi to mt i tng kiu ny; thay vo ta s gi phng

    thc static tn getDefault() tr v i tng SmsManager mc nh ca thit b. Trong phng

    thc phng thc sendTextMessage() s gi tin nhn SMS vi mt i tng kiu PendingIntent. i

    tng PendingIntent ny dng xc nh i tng s gi sau ny. V d: Sau khi gi tin nhn, ta c

    th s dng i tng PendingIntent hin th mt Activity. Trong trng hp trn, i tng

    PendingIntent n gin l ch n activity gi tin nhn i, bng cch ny s khng c vic g sy ra

    sau khi tin nhn c gi i. Ta thay i phng thc sendSMS vi ni dung nh sau:

    private void sendSMS(String phoneNumber, String message)

    {

  • Pht trin ng dng Smartphone Android PendingIntent sentIntent =

    PendingIntent.getActivity(this, 0, new Intent(this,

    SentActivity.class), 0);

    PendingIntent deliveryIntent =

    PendingIntent.getActivity(this, 0, new Intent(this,

    DeliveryActivity.class), 0);

    SmsManager sms = SmsManager.getDefault();

    sms.sendTextMessage(phoneNumber, null, message,

    sentIntent, deliveryIntent);

    }

    Trong ta to ra hai i tng PendingIntent bng cch gi phng thc getActivity().

    Phng thc ny s tr v mt PendingIntent dng khi ng mt activity vi cc thng s ch nh

    i km. Ta to hai i tng kiu PendingIntent dng khi ng hai activity, mt activity s c

    m ra khi tin nhn SMS c gi i (SentActivity) v mt activity s c m ra khi tin nhn SMS

    c chuyn giao thnh cng.

    Nu bn mong mun theo di tin trnh gi tin nhn, bn c th s dng PendingIntent cng vi

    hai BroadcastReceiver nh sau:

    private void sendSMS(String phoneNumber, String message)

    {

    String SENT = "SMS_SENT";

    String DELIVERED = "SMS_DELIVERED";

    PendingIntent sentPI = PendingIntent.getBroadcast(this,

    0,

    new Intent(SENT), 0);

    PendingIntent deliveredPI =

    PendingIntent.getBroadcast(this, 0,

    new Intent(DELIVERED), 0);

    //---when the SMS has been sent---

    registerReceiver(new BroadcastReceiver(){

    @Override

    public void onReceive(Context arg0, Intent arg1) {

    switch (getResultCode())

    {

    case Activity.RESULT_OK:

    Toast.makeText(getBaseContext(), "SMS

    sent",

    Toast.LENGTH_SHORT).show();

    break;

    case

    SmsManager.RESULT_ERROR_GENERIC_FAILURE:

  • Pht trin ng dng Smartphone Android Toast.makeText(getBaseContext(),

    "Generic failure",

    Toast.LENGTH_SHORT).show();

    break;

    case SmsManager.RESULT_ERROR_NO_SERVICE:

    Toast.makeText(getBaseContext(), "No

    service",

    Toast.LENGTH_SHORT).show();

    break;

    case SmsManager.RESULT_ERROR_NULL_PDU:

    Toast.makeText(getBaseContext(), "Null

    PDU",

    Toast.LENGTH_SHORT).show();

    break;

    case SmsManager.RESULT_ERROR_RADIO_OFF:

    Toast.makeText(getBaseContext(), "Radio

    off",

    Toast.LENGTH_SHORT).show();

    break;

    }

    }

    }, new IntentFilter(SENT));

    //---when the SMS has been delivered---

    registerReceiver(new BroadcastReceiver(){

    @Override

    public void onReceive(Context arg0, Intent arg1) {

    switch (getResultCode())

    {

    case Activity.RESULT_OK:

    Toast.makeText(getBaseContext(), "SMS

    delivered",

    Toast.LENGTH_SHORT).show();

    break;

    case Activity.RESULT_CANCELED:

    Toast.makeText(getBaseContext(), "SMS

    not delivered",

    Toast.LENGTH_SHORT).show();

    break;

    }

    }

    }, new IntentFilter(DELIVERED));

    SmsManager sms = SmsManager.getDefault();

    sms.sendTextMessage(phoneNumber, null, message, sentPI,

    deliveredPI);

    }

  • Pht trin ng dng Smartphone Android Trong phn code trn ta dng mt i tng PendingIntent (sendPI) theo di qu trnh gi

    d tin nhn. Khi mt tin nhn SMS c gi i, phng thc onReceive ca BroadcastReceiver u

    tin s c thc thi. Trong phng thc ny ta s tin hnh kim tra trng thi ca tin trnh gi tin

    nhn. i tng PendingIntent th hai dng theo di qu trnh chuyn giao tin nhn. Phng thc

    onReceive ca BroadcastReceiver th hai s c thc thi khi qu trnh chuyn giao mt tin nhn kt

    thc. Ti y ta cng tin hnh kim tra trng thi ca vic chuyn giao tin nhn. Ta s dng phng

    thc getBroadcast() to mt i tng PendingIntent dng khi ng mt Broadcast receiver.

    i tng Intent c to trong trng hp ny c intent filter l String SENT =

    "SMS_SENT"; v String DELIVERED = "SMS_DELIVERED";. Hai bin ny n gin l b lc dng

    chn ng BroadcastReceiver m ta s nh ngha di.

    Phng thc registerReceiver() dng ng k mt BroadcastRecevier s chy trn lung ca

    activity hin ti. Phng thc ny s nhn vo hai tham s: tham s th nht chnh l i tng ci t

    li interface BroadcastReceiver, tham s th hai l i tng Intent xc nh nhng Intent cng loi s

    c dng khi ng BroadcastReceiver ny.

    n y, kim tra s hot ng ca chng trnh ta cn hai my o Android c kh nng gi

    nhn tin nhn vi nhau. lm c vic ny, trc tin ta cn m thm mt my o Android th hhai

    bng cch m Window/Android SDK and AVD Manager trn Eclipse. To mt my o mi v nhn

    Start khi ng my o mi to c kt qu nh sau:

  • Pht trin ng dng Smartphone Android gi tin nhn gia hai my o vi nhau ta thay s in thoi ngi nhn bng cch thay i

    s in thoi ngi nhn bng Emulators port ca my o. Emulators port ca my o trn l 5556

    hin th gc tri trn cng ca my o.

    T my o u tin, s dng ng dng mi xy dng trn tin hnh gi tin nhn n my

    o th hai kim th chng trnh.

    2.1.2 Nhn tin nhn

    Bn cnh vic gi tin nhn ta cn c th nh ngha mt BroadcastReceiver dng nhn tin

    nhn c gi n thit b.

    Tin hnh chnh sa file AndroidManifest.xml bng cch thm mt th receiver t c ni

    dung nh sau:

    Thm mt class SmsReceiver vi ni dung nh sau:

  • Pht trin ng dng Smartphone Android package niit.android;

    import android.content.BroadcastReceiver;

    import android.content.Context;

    import android.content.Intent;

    import android.os.Bundle;

    import android.telephony.gsm.SmsMessage;

    import android.widget.Toast;

    public class SmsReceiver extends BroadcastReceiver {

    @Override

    public void onReceive(Context context, Intent intent)

    {

    //---get the SMS message passed in---

    Bundle bundle = intent.getExtras();

    SmsMessage[] msgs = null;

    String str = "";

    if (bundle != null)

    {

    //---retrieve the SMS message received---

    Object[] pdus = (Object[]) bundle.get("pdus");

    msgs = new SmsMessage[pdus.length];

    for (int i=0; i

  • Pht trin ng dng Smartphone Android

    B xung vo file AndroidManifest.xml ni dung nh sau:

    To file SMSFolderExampleActivity.java vi ni dung:

    package niit.android;

    import android.app.ListActivity;

    import android.database.Cursor;

    import android.net.Uri;

    import android.os.Bundle;

    import android.widget.ListAdapter;

    import android.widget.SimpleCursorAdapter;

    public class SMSFolderExampleActitvity extends ListActivity {

    private ListAdapter adapter;

    private static final Uri SMS_INBOX =

    Uri.parse("content://sms/inbox");

    @Override

    public void onCreate(Bundle bundle) {

    super.onCreate(bundle);

    Cursor c = getContentResolver().query(SMS_INBOX, null,

    null, null, null);

    startManagingCursor(c);

    String[] columns = new String[] {"body"};

    int[] names = new int[] { R.id.row };

    adapter = new SimpleCursorAdapter(this,

    R.layout.sms_folder, c, columns,

    names);

    setListAdapter(adapter);

    }

    }

  • Pht trin ng dng Smartphone Android Lnh Cursor c = getContentResolver().query(SMS_INBOX, null, null, null, null); s to ra mt

    i tng con tr dng c tin nhn trong th mc inbox. Lnh startManagingCursor s bo cho

    activity hin ti qun l vng i ca con tr va mi to ra (Khi activity thay i trng thi n cng

    thay i trng thi ca con tr). Bng cch ny khi Activity b loi khi b nh n cng dn dp con tr

    ny. Ngoi cch s dng SimpleCursorAdapter ta cn c th s dng con tr c d liu theo cch

    sau:

    result.moveToFirst();

    while (!result.isAfterLast()) {

    String address = result.getString(2);

    String body =result.getString(11);

    result.moveToNext();

    }

    Di y l danh sch cc th mc cha tin nhn SMS:

    - All: content://sms/all

    - Inbox: content://sms/inbox

    - Sent: content://sms/sent

    - Draft: content://sms/draft

    - Outbox: content://sms/outbox

    - Failed: content://sms/failed

    - Queued: content://sms/queued

    - Undelivered: content://sms/undelivered

    - Conversations: content://sms/conversations

    2.2 Gi email

    Android khng h tr gi email trc tip t ng dng nn ta s phi to mt i tng Intent

    khi ng ca s Activity dng gi mail nh sau:

    Intent emailIntent=new Intent(Intent.ACTION_SEND);

    String subject = "Hi!";

    String body = "hello from android....";

    String[] extra = new String[]{"[email protected]"};

    emailIntent.putExtra(Intent.EXTRA_EMAIL, extra);

    emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);

    emailIntent.putExtra(Intent.EXTRA_TEXT, body);

    emailIntent.setType("message/rfc822");

  • Pht trin ng dng Smartphone Android

    startActivity(emailIntent);

    2.3 Lm vic vi Telephony maganager

    Gi s ta vit mt ng dng chi nhc cho h iu hnh Android, khi ta cn bt c cc s

    kin khi c cuc gi n ngng chi nhc. Hoc khi cuc in thoi kt thc ta cn tip tc chi

    nhc. lm c vic ny ta c th s dng TelephonyManager c cung cp sn trong Android vi

    cch thc nh sau:

    package niit.android;

    import android.app.Activity;

    import android.content.Context;

    import android.os.Bundle;

    import android.telephony.PhoneStateListener;

    import android.telephony.TelephonyManager;

    import android.util.Log;

    import android.widget.Toast;

    public class TelephonyServiceExampleActivity extends Activity{

    private static final String TAG="TelephonyServiceDemo";

    @Override

    protected void onCreate(Bundle savedInstanceState)

    {

    super.onCreate(savedInstanceState);

    TelephonyManager teleMgr =

    (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

    teleMgr.listen(new MyPhoneStateListener(),

    PhoneStateListener.LISTEN_CALL_STATE);

    }

    class MyPhoneStateListener extends PhoneStateListener

    {

    @Override

    public void onCallStateChanged(int state, String

    incomingNumber) {

    super.onCallStateChanged(state, incomingNumber);

    Toast toast =

    Toast.makeText(TelephonyServiceExampleActivity.this, "", 3000);

    switch(state)

    {

    case TelephonyManager.CALL_STATE_IDLE:

    Log.d(TAG, "call state idle...incoming

    number is["+

  • Pht trin ng dng Smartphone Android incomingNumber+"]");break;

    case TelephonyManager.CALL_STATE_RINGING:

    Log.d(TAG, "call state ringing...incoming

    number is["+

    incomingNumber+"]");break;

    case TelephonyManager.CALL_STATE_OFFHOOK:

    Log.d(TAG, "call state Offhook...incoming

    number is["+

    incomingNumber+"]");break;

    default:

    Log.d(TAG, "call state ["+state+"]incoming

    number is["+

    incomingNumber+"]");break;

    }

    }

    }

    }