12/3 - Users.wmin.ac.uk

knapsackyarnMobile - Wireless

Dec 14, 2013 (3 years and 7 months ago)

91 views

ECWM511MOBILEAPPLICATIONDEVELOPMENT
Lecture8:ConnectingtotheNetwork
DrDimitrisC.Dracopoulos
1
TheBrowserIntentApplication
ThesimplestthingyoucandowithAndroidsnetworkingAPIistoopenabrowseronawebpageof
yourchoice.
2/42
BrowsingbyIntent
Thelayoutfileres/layout/main.xml:
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/
res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:id="@+id/url_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
3/42
2
BrowsingbyIntent(cont’d)
android:layout_weight="1.0"
android:lines="1"
android:inputType="textUri"
android:imeOptions="actionGo"/>
<Button
android:id="@+id/go_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/go_button"/>
</LinearLayout>
4/42
BrowsingbyIntent(cont’d)
Fileres/values/strings.xml:
<?xmlversion="1.0"encoding="utf-8"?>
<resources>
<stringname="app_name">BrowserIntent</string>
<stringname="go_button">Go</string>
</resources>
5/42
3
TheBrowserIntentClass
packageorg.example.browserintent;
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.view.KeyEvent;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.view.View.OnKeyListener;
importandroid.widget.Button;
importandroid.widget.EditText;
publicclassBrowserIntentextendsActivity{
privateEditTexturlText;
privateButtongoButton;
6/42
TheBrowserIntentClass(cont’d)
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Getahandletoalluserinterfaceelements
urlText=(EditText)findViewById(R.id.url_field);
goButton=(Button)findViewById(R.id.go_button);
//Setupeventhandlers
goButton.setOnClickListener(newOnClickListener(){
publicvoidonClick(Viewview){
openBrowser();
}
});
7/42
4
TheBrowserIntentClass(cont’d)
urlText.setOnKeyListener(newOnKeyListener(){
publicbooleanonKey(Viewview,intkeyCode,
KeyEventevent){
if(keyCode==KeyEvent.KEYCODE_ENTER){
openBrowser();
returntrue;
}
returnfalse;
}
});
}
8/42
TheBrowserIntentClass(cont’d)
TheopenBrowser()method:
/**OpenabrowserontheURLspecifiedinthe
textbox*/
privatevoidopenBrowser(){
Uriuri=Uri.parse(urlText.getText().toString());
Intentintent=newIntent(Intent.ACTION_VIEW,
uri);
startActivity(intent);
}
9/42
5
WebwithaView
AndroidprovidesawrapperaroundtheWebKitbrowserenginecalledWebViewthatyoucanuse
togettherealpowerofabrowserwithaslittleas1MBofoverhead.
Thiscanbeusedtoembedabrowserinsideanapplication.
WebViewworksprettymuchlikeanyotherAndroidviewexceptthatithasafewextramethods
specifictothebrowser.
10/42
11/42
6
ThelayoutfileforWebwithaView
Fileres/layout/main.xml:
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/
res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/url_field"
12/42
ThelayoutfileforWebwithaView(cont’d)
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:lines="1"
android:inputType="textUri"
android:imeOptions="actionGo"/>
<Button
android:id="@+id/go_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/go_button"/>
</LinearLayout>
<WebView
android:id="@+id/web_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"/>
</LinearLayout>
13/42
7
TheWebViewClass
packageorg.example.browserview;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.view.KeyEvent;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.view.View.OnKeyListener;
importandroid.webkit.WebView;
importandroid.widget.Button;
importandroid.widget.EditText;
publicclassBrowserViewextendsActivity{
privateEditTexturlText;
privateButtongoButton;
privateWebViewwebView;
14/42
TheWebViewClass(cont’d)
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Getahandletoalluserinterfaceelements
urlText=(EditText)findViewById(R.id.url_field);
goButton=(Button)findViewById(R.id.go_button);
webView=(WebView)findViewById(R.id.web_view);
//Setupeventhandlers
goButton.setOnClickListener(newOnClickListener()
{
publicvoidonClick(Viewview){
openBrowser();
}
});
15/42
8
TheWebViewClass(cont’d)
urlText.setOnKeyListener(newOnKeyListener(){
publicbooleanonKey(Viewview,intkeyCode,
KeyEventevent){
if(keyCode==KeyEvent.KEYCODE_ENTER){
openBrowser();
returntrue;
}
returnfalse;
}
});
}
/**OpenabrowserontheURLspecifiedinthe
textbox*/
privatevoidopenBrowser(){
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(urlText.getText().toString());
}
}
16/42
ThestringResources
<?xmlversion="1.0"encoding="utf-8"?>
<resources>
<stringname="app_name">BrowserView</string>
<stringname="go_button">Go</string>
</resources>
Thefollowinglineneedstobeaddedtothemanifestbeforethe<application>tagtoallowaccess
totheinternet:
<uses-permissionandroid:name=
"android.permission.INTERNET"/>
17/42
9
UsingWebServices
AndroidprovidesafullsetofJava-standardnetworkingAPIs,suchasthejava.netpackage
containingamongotherstheHttpURLConnectionclass.
Example:UsetheGoogleTranslationAPIorasimilarwebservicetocreateatranslationprogram.
AsGoogleTranslatehasmovedtoversion2asubscriptionisrequired.InsteadtheApertium
webservicecanbeused:
http://wiki.apertium.org/wiki/Apertium_web_service
18/42
10
11
ListofsupportedpairsoflanguagesbyApertium
ThefollowingdescribeswhichpairslanguagesaresupportedbyApertium:
{"responseData":[{"sourceLanguage":"ro","targetLanguage":"es"},
{"sourceLanguage":"es","targetLanguage":"fr"},
{"sourceLanguage":"en","targetLanguage":"gl"},
{"sourceLanguage":"oc","targetLanguage":"es"},
{"sourceLanguage":"es","targetLanguage":"ro"},
{"sourceLanguage":"es","targetLanguage":"ca_valencia"},
{"sourceLanguage":"mk","targetLanguage":"bg"},
{"sourceLanguage":"fr","targetLanguage":"es"},
{"sourceLanguage":"oc_aran","targetLanguage":"ca"},
{"sourceLanguage":"pt","targetLanguage":"gl"},
{"sourceLanguage":"en","targetLanguage":"ca"},
{"sourceLanguage":"an","targetLanguage":"es"},
{"sourceLanguage":"eu","targetLanguage":"es"},
{"sourceLanguage":"es","targetLanguage":"gl"},
{"sourceLanguage":"es","targetLanguage":"ca"},
{"sourceLanguage":"fr","targetLanguage":"eo"},
{"sourceLanguage":"nb","targetLanguage":"nn_a"},
{"sourceLanguage":"ca","targetLanguage":"pt"},
{"sourceLanguage":"mk","targetLanguage":"en"},
{"sourceLanguage":"ca","targetLanguage":"en_US"},
{"sourceLanguage":"is","targetLanguage":"en"},
{"sourceLanguage":"pt","targetLanguage":"ca"},
{"sourceLanguage":"fr","targetLanguage":"ca"},
{"sourceLanguage":"gl","targetLanguage":"en"},
{"sourceLanguage":"gl","targetLanguage":"es"},
{"sourceLanguage":"ca","targetLanguage":"oc_aran"},
{"sourceLanguage":"nn","targetLanguage":"nb"},
{"sourceLanguage":"ca","targetLanguage":"oc"},
{"sourceLanguage":"en","targetLanguage":"es"},
{"sourceLanguage":"es","targetLanguage":"pt"},
{"sourceLanguage":"oc_aran","targetLanguage":"es"},
{"sourceLanguage":"es","targetLanguage":"eo"},
{"sourceLanguage":"es","targetLanguage":"en"},
{"sourceLanguage":"oc","targetLanguage":"ca"},
{"sourceLanguage":"cy","targetLanguage":"en"},
{"sourceLanguage":"ca","targetLanguage":"fr"},
{"sourceLanguage":"br","targetLanguage":"fr"},
{"sourceLanguage":"en","targetLanguage":"eo"},
{"sourceLanguage":"bg","targetLanguage":"mk"},
{"sourceLanguage":"ca","targetLanguage":"eo"},
{"sourceLanguage":"ca","targetLanguage":"en"},
{"sourceLanguage":"es","targetLanguage":"oc_aran"},
{"sourceLanguage":"sv","targetLanguage":"da"},
{"sourceLanguage":"pt","targetLanguage":"es"},
{"sourceLanguage":"nn","targetLanguage":"nn_a"},
{"sourceLanguage":"es","targetLanguage":"pt_BR"},
{"sourceLanguage":"es","targetLanguage":"oc"},
{"sourceLanguage":"es","targetLanguage":"an"},
{"sourceLanguage":"da","targetLanguage":"sv"},
{"sourceLanguage":"gl","targetLanguage":"pt"},
{"sourceLanguage":"it","targetLanguage":"ca"},
{"sourceLanguage":"eo","targetLanguage":"en"},
{"sourceLanguage":"ca","targetLanguage":"es"},
12
ListofsupportedpairsoflanguagesbyApertium(cont’d)
ThefollowingdescribeswhichpairslanguagesaresupportedbyApertium:
{"sourceLanguage":"nn_a","targetLanguage":"nn"},
{"sourceLanguage":"es","targetLanguage":"en_US"},
{"sourceLanguage":"nb","targetLanguage":"nn"}],
"responseDetails":null,"responseStatus":200}
20/42
21/42
13
TheLayoutoftheTranslateProgram
Themain.xmlfile:
<?xmlversion="1.0"encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/
res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1"
android:padding="10dip">
22/42
TheLayoutoftheTranslateProgram(cont’d)
<TableRow>
<TextViewandroid:text="@string/from_text"/>
<Spinnerandroid:id="@+id/from_language"/>
</TableRow>
<EditText
android:id="@+id/original_text"
android:hint="@string/original_hint"
android:padding="10dip"
android:textSize="18sp"/>
23/42
14
TheLayoutoftheTranslateProgram(cont’d)
<TableRow>
<TextViewandroid:text="@string/to_text"/>
<Spinnerandroid:id="@+id/to_language"/>
</TableRow>
<TextView
android:id="@+id/translated_text"
android:padding="10dip"
android:textSize="18sp"/>
</TableLayout>
</ScrollView>
24/42
Thelistoflanguages
Thelistoflanguagesisdefinedinanarrayresourceinfileres/values/arrays.xml:
<?xmlversion="1.0"encoding="utf-8"?>
<resources>
<arrayname="languages">
<item>Bulgarian(bg)</item>
<item>ChineseSimplified(zh-CN)</item>
<item>ChineseTraditional(zh-TW)</item>
<item>Catalan(ca)</item>
<item>Croatian(hr)</item>
<item>Czech(cs)</item>
<item>Danish(da)</item>
<item>Dutch(nl)</item>
<item>English(en)</item>
25/42
15
Thelistoflanguages(cont’d)
<item>Filipino(tl)</item>
<item>Finnish(fi)</item>
<item>French(fr)</item>
<item>German(de)</item>
<item>Greek(el)</item>
<item>Indonesian(id)</item>
<item>Italian(it)</item>
<item>Japanese(ja)</item>
<item>Korean(ko)</item>
<item>Latvian(lv)</item>
<item>Lithuanian(lt)</item>
<item>Norwegian(no)</item>
<item>Polish(pl)</item>
<item>Portuguese(pt-PT)</item>
<item>Romanian(ro)</item>
26/42
Thelistoflanguages(cont’d)
<item>Russian(ru)</item>
<item>Spanish(es)</item>
<item>Serbian(sr)</item>
<item>Slovak(sk)</item>
<item>Slovenian(sl)</item>
<item>Swedish(sv)</item>
<item>Ukrainian(uk)</item>
</array>
</resources>
27/42
16
Thestrings.xmlfile
<?xmlversion="1.0"encoding="utf-8"?>
<resources>
<stringname="from_text">From:</string>
<stringname="app_name">Translate</string>
<stringname="original_hint">Entertextto
translate</string>
<stringname="to_text">To:</string>
<stringname="translation_error">(Translation
error)</string>
</resources>
Thefollowinglineneedstobeaddedtothemanifestbeforethe<application>tagtoallowaccess
totheinternet:
<uses-permissionandroid:name=
"android.permission.INTERNET"/>
28/42
TheTranslateclass
packagecom.example.translate2;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.net.HttpURLConnection;
importjava.net.URL;
importjava.net.URLEncoder;
importorg.json.JSONException;
importorg.json.JSONObject;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.text.Editable;
importandroid.text.TextWatcher;
29/42
17
TheTranslateclass(cont’d)
Restofimportsare:
importandroid.util.Log;
importandroid.view.View;
importandroid.widget.AdapterView;
importandroid.widget.AdapterView.
OnItemSelectedListener;
importandroid.widget.ArrayAdapter;
importandroid.widget.EditText;
importandroid.widget.Spinner;
importandroid.widget.TextView;
30/42
TheTranslateclass(cont’d)
publicclassTranslateextendsActivity{
privatestaticfinalStringTAG="TranslateTask";
privateSpinnerfromSpinner;
privateSpinnertoSpinner;
privateEditTextorigText;
privateTextViewtransText;
privateStringfromLang;
privateStringtoLang;
privateTextWatchertextWatcher;
privateOnItemSelectedListeneritemListener;
31/42
18
TheTranslateclass(cont’d)
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViews();
setAdapters();
setListeners();
}
//...Restofmethodsgohere...
}
32/42
TheTranslateclass(cont’d)
MethodfindViews:
privatevoidfindViews(){
fromSpinner=(Spinner)findViewById(
R.id.from_language);
toSpinner=(Spinner)findViewById(
R.id.to_language);
origText=(EditText)findViewById(
R.id.original_text);
transText=(TextView)findViewById(
R.id.translated_text);
}
33/42
19
TheTranslateclass(cont’d)
MethodsetAdapters():
/**Definedatasourceforthespinners*/
privatevoidsetAdapters(){
//Spinnerlistcomesfromaresource,
ArrayAdapter<CharSequence>adapter=
ArrayAdapter.createFromResource(
this,R.array.languages,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
fromSpinner.setAdapter(adapter);
toSpinner.setAdapter(adapter);
//Automaticallyselecttwospinneritems
fromSpinner.setSelection(8);//English(en)
toSpinner.setSelection(25);//Spanish(es)
}
34/42
TheTranslateclass(cont’d)
MethodsetListeners():
privatevoidsetListeners(){
textWatcher=newTextWatcher(){
publicvoidbeforeTextChanged(CharSequences,
intstart,
intcount,
intafter){}
publicvoidonTextChanged(CharSequences,
intstart,
intbefore,
intcount){
Stringtranslation=doTranslate(
origText.getText().toString().trim(),
fromLang,toLang);
transText.setText(translation);
}
35/42
20
TheTranslateclass(cont’d)
publicvoidafterTextChanged(Editables){}
};
origText.addTextChangedListener(textWatcher);
itemListener=newOnItemSelectedListener(){
publicvoidonItemSelected(AdapterViewparent,
Viewv,intposition,
longid){
fromLang=getLang(fromSpinner);
toLang=getLang(toSpinner);
Stringtranslation=doTranslate(
origText.getText().toString().trim(),
fromLang,toLang);
transText.setText(translation);
}
36/42
TheTranslateclass(cont’d)
publicvoidonNothingSelected(AdapterViewparent)
{
/*Donothing*/
}
};//endofOnItemSelectedListener()
fromSpinner.setOnItemSelectedListener(itemListener);
toSpinner.setOnItemSelectedListener(itemListener);
}
37/42
21
TheTranslateclass(cont’d)
ThegetLang()method:
/*Extractthelanguagecodefromthecurrent
spinneritem*/
privateStringgetLang(Spinnerspinner){
Stringresult=spinner.getSelectedItem().toString();
intlparen=result.indexOf(’(’);
intrparen=result.indexOf(’)’);
result=result.substring(lparen+1,rparen);
returnresult;
}
38/42
TheTranslateclass(cont’d)
ThedoTranslate()method:
privateStringdoTranslate(Stringoriginal,
Stringfrom,
Stringto){
Stringresult=getResources().getString(
R.string.translation_error);
HttpURLConnectioncon=null;
try{
//BuildRESTfulqueryforGoogleAPI
Stringq=URLEncoder.encode(original,"UTF-8");
39/42
22
TheTranslateclass(cont’d)
URLurl=newURL(
"http://api.apertium.org/json/translate"
+"?q="+q+"&langpair="+from
+"%7C"+to);
con=(HttpURLConnection)url.openConnection();
con.setReadTimeout(10000/*milliseconds*/);
con.setConnectTimeout(15000/*milliseconds*/);
con.setRequestMethod("GET");
con.addRequestProperty("Referer",
"http://www.pragprog.com/hello-android");
con.setDoInput(true);
//Startthequery
con.connect();
40/42
TheTranslateclass(cont’d)
//Readresultsfromthequery
BufferedReaderreader=newBufferedReader(
newInputStreamReader(con.getInputStream(),
"UTF-8"));
Stringpayload=reader.readLine();
reader.close();
//Parsetogettranslatedtext
JSONObjectjsonObject=newJSONObject(payload);
result=jsonObject.getJSONObject("responseData")
.getString("translatedText")
.replace("&#39;","’")
.replace("&amp;","&");
}
41/42
23
TheTranslateclass(cont’d)
catch(IOExceptione){
Log.e(TAG,"IOException",e);
}
catch(JSONExceptione){
Log.e(TAG,"JSONException",e);
}
finally{
if(con!=null){
con.disconnect();
}
}
returnresult;
}
42/42
24