SlideShare una empresa de Scribd logo
1 de 293
Android Application Development
Practical Training Course
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
Ver2.00(03)
1
About textbook usage
2
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
・This textbook is licensed under the Creative Commons License
BY-NC-SA 4.0. It is prohibited to use this material for commercial
use otherwise you are OESF member or OESF education
consortium member.
・This training program including all the provided documents are
provided without any warranty from OESF. OESF assume no
responsibility whatsoever for any damages/ occurrence of legal action
resulting from the use or misuse of this course content/ detailed information
of course.
• To learn the practical knowledge, technology in
developing Android application
– Component of Android
– Practical development
• To bring up the power of execution in application
development through seminar.
– The main purpose is the developing skill
3
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
Purpose of training course
Training schedule
• The 1st day
– Chapter 1 Introduction
– Chapter 2 Android component
– Chapter 3 Practical development
• The 2nd day
– Chapter 4 Practical development 2
– Chapter 5 Outside solidarity
– Chapter 6 Practical debug
– Chapter 7 Summary
4
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
The necessary skills for attending this course
• Unless attended OESFcertificated Android
application development basic training course, need
following skills:
– Precondition: having the basic skills of Android application
– Be able to create the a simple application with several
screens
– Understand the syntax of JavaSE briefly and have actual
experience
– Understand the basic Eclipse operations
5
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
1. Introduction
6
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
Chapter 1 - Outline
• Development environment
• Practice used in this course
• Practice outline
7
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
1.1. Development environment
• In this training course, the following development
tools will be used
• They are installed already
• The path is ready for running on the tools of SDK
8
Software Version
Integrated development environment Eclipse 3.5 (Galileo)
Java SDK JDK 6 Update 21
Android SDK 2.2
Android Plug-in Android Development Tools (ADT) Ver.0.9.6
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
1.1. Development environment
• Eclipse workspace
Specify C:android_training_appliedworkspace
• Emulator
The emulator used for practicing will be WVGA-normal-hdpi if no
particular one is specified
• SDK path
C:android_trainingtoolsandroid-sdk-windows
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 9
1.2. Application used in practice
• In the 1st day of practice, the RSS reader created in
Android application development basic training course
will be added with extension
10
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
• Outline of screens & functions of RSS reader
– This includes 3 screens
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
11
Start
up
# Screen name Function outline
1 Menu • Start up List view
• Display option menu
• When open menu is clicked, get RSS feed from Internet and register to database
• After getting RSS feed, display the finish message by dialog
2 List • Display the RSS feed registered in database in list type
3 Detail • Display title, distributed date time, distributor name, detailed content of the RSS
feed selected in list view
1.2. Application used in this course
RSS reader ・・・ Direction of screen
transition
①
Menu
screen
②
List
screen
③
Detail
screen
1.3. Practice outline
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
12
Internet
Database
Get RSS feed from
Internet
Register RSS feed to
database
Search RSS feed from
database
Click List displaying
button
Select list
data
Display dialog after
registering to
database
Get with
service
Start the processing
with broadcast receiver
Access with content
provider
Display notification of
getting finished
Multi resolution
Support
multi-language
Menu
screen
List
screen
Detail
screen
1.3. Practice outline
Table layout
– RSS_FEED table
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 13
String name type remarks
_id INTEGER
• Primary key
• Auto increment
GUID TEXT • Identifier allocated to RSS fee
TITLE TEXT • Title
PUBLISH_DATE TEXT • Distributed date time
DESCRIPTION TEXT • Detailed content
LINK TEXT • Link
SENDER_NAME TEXT • Name of distributor
2. Android component
14
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
Chapter 2 - Outline
• Activity
• Intent
• Service
• Broadcast receiver
• Content provider
※ Only consolidate on Activity and Intent
The others will be practiced after the lecture
15
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
2.1. Activity
• What is activity?
– The Android application screen is created by placing many
parts such as Button, Checkbox, … on Activity
– 1 screen is constructed based on 1 activity
– Activity has 2 status: running and pausing
16
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
• Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 17
package jp.oesf.mtgeduwg.training.rssreader;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
public class RssReaderActivity extends Activity implements OnClickListener {
public void onClick(View view) {
Log.v("RssReaderActivity","Clicked");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View listButton = findViewById(R.id.list_button);
listButton.setOnClickListener(this);
}
}
• Set Activity class as super class
• Execute call back method if needed
2.1. Activity
• Sample code of AndroidManifest.xml
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 18
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jp.oesf.mtgeduwg.training.rssreader"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:debuggable="true">
・・・
<activity android:label="@string/app_name" android:name="RssListActivity"></activity>
</application>
<uses-sdk android:minSdkVersion=“7" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
•Creates the tag name as activity tag
•Specify attribute android:name=“activity name”
2.1. Activity
• [Ref] Life cycle which includes the notified events
19
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
2.1. Activity
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 20
• [Ref] It is possible to set AndroidManifest.xml with resource
editor
2.1. Activity
2.2. Intent
• What is intent?
– The mechanism for requesting process or exchanging
message between components
• The components which can use intent are activity, broadcast receiver,
service
– Intent use cases
• Start up activity B from activity A(screen transition)
• Request telephone call to the application of calling from Address
book application
21
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
2.2. Intent
• When component is called by intent, in the intent the
calling destination component information will be
added and request to Android
– Example of calling component B from component A
22
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
B is started up
2.2. Intent
• Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 23
package jp.oesf.mtgeduwg.training.rssreader;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class RssReaderActivity extends Activity implements OnClickListener {
・・・・・・・・
public void onClick(View view) {
if (R.id.list_button == view.getId()) {
Intent intent = new Intent(this, RssListActivity.class);
startActivity(intent);
}
}
}
•Generate object of intent
•Pass intent
2.3. Service
• What is service?
– The mechanism for the processing by the independent thread
– Service is implemented by the thread different with activity of
foreground. Therefore, even the interruption occurs by other activity
the processing can be continued
24
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
Play music (not use Service) Play music (use Service)
The difference in operating when Activity interrupt
occurred by receiving mail in case of playing music
directly from Activity or through service.
2.3. Service
• How to implement service
– Create newly service
– Register the created service to AndroidManifest.xml
– Start the created service by startService method
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 25
2.3. Service
• How to implement service
1. Create new service class
• Create the service class inherited from Service base class
• It is necessary to implement abstract onBind method.
Binding is not used here, so null is returned
Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 26
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class SampleService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
・・・1
2.3. Service
2. Implement call back method if needed
• There are 3 methods: onCreate, onStart,
onDestroy
• Recognize life cycle and implement appropriately
• onStart will be called each time when starting
• The other 2 methods will be called once when
creating and destroying object
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 27
# Events name Content
1 onCreate The event occurs in the first startup
2 onStart The event occurs just before the Service is
started
3 onDestroy The event occurs just before the Service is
destroyed
2.3. Service
• Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 28
@Override
public void onCreate() {
super.onCreate();
Log.v(“SampleService", "onCreate");
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Thread t = new Thread() {
@Override
public void run() {
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
Log.e("RegisterService", e.toString());
}
}
};
t.start();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.v(“SampleService", "onDestroy");
}
・・・2
2.3. Service
2. Register the created service in AndroidManifest.xml
• Creating steps
i. Open AndroidManifest.xml and select Application tab
ii. Click [Add] button of Application Nodes
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 29
i
ⅱ
2.3. Service
iii. Select Service from the displayed screen, click 「OK」 button
※ In case cursor is in the registered node, the layer will be checked,
so please select upon radio button
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 30
ⅲ
※
2.3. Service
iv. After checking that the added service is selected, input name of
class of the service created in [Name] field
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 31
ⅳ
Clicking Browse
button, browsing is
convenient
2.3. Service
※ The following will be added to AndroidManifest.xml
The class of service becomes registered by this
Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 32
・・・
<application ・・・>
・・・
<service android:name=“SampleService"></service>
・・・
</application>
・・・
2.3. Service
3. Start up the created service by startService method
i. Create new intent object by setting to the argument of Intent the calling
source object and the class of calling destination service
ii. Execute Context#startService. Set Intent object created in i. to argument
of method
• Sample code (extracted from code of activity)
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 33
Intent intent = new Intent(this, SampleService.class);
startService(intent);
・・・ⅰ
・・・ⅱ
Practice
2.3. Service
Practice 1
• Practice theme
– In menu screen, create the processing of starting RSS getting method
with service when pushing 「menu」 button => 「Get RSS」 button
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 34
Screen can be
operated as it is
Started as service
No affect to screen
Practice
2.3. Service
Practice 1
• Steps:
1. Create new service RegisterService class
2. Get RSS with onStart method of RegisterService
3. Output log of starting/ending to RegisterService#onStart
• Tag:「 RegisterService 」
• Message:when starting 「onStart start」 and when ending 「onStart end」
4. Delete logic of RSS getting existed in onOptionsItemSelected method
of RssReaderActivity, use Intent to call RegisterService
5. Output log of starting/ending to
RssReaderActivity#onOptionsItemSelected
• Tag: 「 RssReaderActivity 」
• Message:「onOptionsItemSelected start」 and 「onOptionsItemSelected end」
6. Add setting of RegisterService to AndroidManifest.xml
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 35
Practice
2.3. Service
Practice 1
– Setting information 1
• Execute the following class, method
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 36
Target Class Method Outline
Service RegisterService
• Create newly
• Package is
jp.oesf.mtgeduwg.training.rssreader
onStart
• Get RSS
• Output starting & ending log
Menu screen RssReaderActivity onOptionsItemSelected
• Delete the existed RSS getting log
• Start RegisterService
• Output starting & ending log
Practice
2.3. Service
Practice 1
– Setting information 2
• Edit the following file
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 37
File name Outline
AndroidManifest.xml • Register RegisterService as service
Practice
2.3. Service
Practice 1
• How to check
– When pushing 「Get RSS」 button, the following log output will be
checked with LogCat
• RegisterService#onStart
– Starting log 「onStart start 」
– Ending log 「 onStart end」
• RssReaderActivity#onOptionsItemSelected
– Starting log 「onOptionsItemSelected start 」
– Ending log 「 onOptionsItemSelected end」
– Close log of RssReaderActivity#onOptionsItemSelected will be checked
with the output after close log of RegisterService#onStart
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 38
Practice
2.3. Service
Practice 1
• Answer of Practice
– RegisterService
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 39
package jp.oesf.mtgeduwg.training.rssreader;
import jp.oesf.mtgeduwg.training.rssreader.helper.RssFeedRegister;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class RegisterService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.v("RegisterService", "onStart start");
new
RssFeedRegister(this).registration("http://www.oesf.jp/modules/news/index.php?page=rss");
Log.v("RegisterService", "onStart end");
}
}
Practice
2.3. Service
Practice 1
• Answer of Practice
– RssReaderActivity (Only the corresponding part extracted)
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 40
・・・
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.v("RssReaderActivity", "onOptionsItemSelected start");
if (item.getItemId() == R.id.main_menu_add) {
// new RssFeedRegister(this).registration("http://www.oesf.jp/modules/news/index.php?page=rss");
// new AlertDialog.Builder(this).setTitle(R.string.ok_dialog_label).show();
Intent intent = new Intent(this, RegisterService.class);
startService(intent);
Log.v("RssReaderActivity", "onOptionsItemSelected end");
return true;
}
return false;
}
・・・
Practice
2.3. Service
Practice 1
• Answer of Practice
– AndroidManifest.xml (Only the corresponding part extracted)
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 41
・・・
<application>
・・・
<service android:name="RegisterService"></service>
・・・
</application>
・・・
Practice
2.3. Service
Practice 1[Supplement]
• Practice theme
– Use toast to notify that service processing is completed
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 42
Screen will be
operated as it is
Service logic
Toast will be explained from the next page
Practice
2.3. Service
• What is toast?
– The function to display message on screen for a short time
– This is the function for displaying message only and can not operate
combining with cursor
– It is convenient if you use the component without UI such as service
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 43
Practice
2.3. Service
• Execute toast
– Use 1 of the 2 methods as below:
public static Toast makeText (Context context, CharSequence text, int duration)
public static Toast makeText (Context context, int resId, int duration)
+ context: context
+ text: the displayed text resId: the resource ID of the displayed text
+ duration: Toast.LENGTH_SHORT (short time) or Toast.LENGTH_LONG(long
time)
– For the return value of the above methods, it is displayed that Toast#show
method is implemented
Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 44
Toast.makeText(this, “TEST", Toast.LENGTH_SHORT).show();
Toast.makeText(this, R.string.test, Toast.LENGTH_LONG).show();
Practice
2.3. Service
Practice 1[Supplement]
1. When service logic is completed, try to display the favorite message with
toast
2. Change duration and check if the display time is changed or not
3. Try to use all makeText methods with the different 2nd argument
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 45
2.4. Broadcast receiver
• What is broadcast receiver?
– Broadcast receiver is the mechanism to response the
broadcasted intent
– Can inherit broadcast receiver class to create the original
broadcast receiver
46
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
2.4. Broadcast receiver
• Use cases of broadcast receiver
– Check mail when starting Android device
1. Receive broadcast intent when starting Android device completed
with broadcast receiver
※ Describe IntentFilter in AndroidManifest.xml about receiving which broadcast
intent
2. Call mail checking service from broadcast receiver
※ It is possible to check mail directly from broadcast receiver, but in case of long
time processing it is better to use service
47
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
Broadcast
receiver
Send broadcast intent
Send intent
② Execute mail
checking service
Intent
① Starting completed
message
Intent
Mail checking
service
2.4. Broadcast receiver
• How to implement service
– Create newly broadcast receiver class
– Register the created broadcast receiver to AndroidManifest.xml
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 48
2.4. Broadcast receiver
• How to implement broadcast receiver
1. Create newly broadcast receiver class
• Create the class inherited from BroadcastReceiver base class
• It is necessary to implement abstract onReceive method
• Implement actual process which you want in onReceive method
• Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 49
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class SampleStarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, SampleService.class);
context.startService(serviceIntent);
}
}
・・・1
2.4. Broadcast receiver
※ In case you want to divide the processing according to the receiving
intent, check if which intent will be received by checking action caused
by Intent#getAction, and describe the divided processing
Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 50
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class SampleStarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
Intent serviceIntent = new Intent(context, SampleService.class);
context.startService(serviceIntent);
}
}
}
・・・※
2.4. Broadcast receiver
2. Register the created broadcast receiver to AndroidManifest.xml
• Steps
i. Open AndroidManifest.xml, select Application tab
ii. Click [Add] button of Application Nodes
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 51
ⅰ
ⅱ
2.4. Broadcast receiver
iii. Select Receiver from the displayed screen and click 「OK」 button
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 52
ⅲ
2.4. Broadcast receiver
iv. After checking if the added receiver is selected or not, input the
name of the created broadcast receiver into Name field
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 53
ⅳ
It is convenient if you
click Browse button
2.4. Broadcast receiver
v. After checking if the added receiver is selected or not, click 「Add」
button
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 54
ⅴ
2.4. Broadcast receiver
vi. After checking if the lower radio button is selected on the displayed
screen or not, select Intent Filter and click 「OK」 button
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 55
ⅵ
2.4. Broadcast receiver
vii. After checking if the added Intent Filter is selected or not, click 「Add
」 button
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 56
ⅶ
2.4. Broadcast receiver
viii. After checking if the lower radio button is selected on the displayed
screen or not, select Intent Filter and click 「OK」 button
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 57
Ⅷ
2.4. Broadcast receiver
ix. After checking if the added receiver is selected or not, input name
of class of the created service into Name field
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 58
Can select by pull down
ⅸ
2.4. Broadcast receiver
※ It is added to AndroidManifest.xml as below:
In the following, broadcast intent of
android.intent.action.BOOT_COMPLETED is captured and the service class –
SampleServiceStart is started up
Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 59
・・・
<application ・・・>
・・・
<receiver android:name=“SampleServiceStarter">
<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
・・・
</application>
・・・
Practice
2.4. Broadcast receiver
Practice 2
• Practice theme
– When system finished starting, create the starting processing for RSS
getting method with service
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 60
System finished
starting
Start as service
No impact to screen
Practice
2.4. Broadcast receiver
Practice 2
• Steps
1. Create newly RegisterServiceStarter class which is the broadcast
receiver
2. Call RegisterService with onReceive method of
RegisterServiceStarter#onReceive
3. Add setting of RegisterServiceStarter to AndroidManifest.xml
• Register RegisterServiceStarter as broadcast receiver
• As setting of Intent Filter of RegisterServiceStarter, set
android.intent.action.BOOT_COMPLETED(starting completed) to
Action
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 61
Practice
2.4. Broadcast receiver
Practice 2
– Setting information
• Execute the following class, method
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 62
Target Class Method Outline
Broadcast
receiver
RegisterServiceStart
er
• Create newly
• Package is
jp.oesf.mtgeduwg.training.rssreader
onReceive • Start up RegisterService
Practice
2.4. Broadcast receiver
Practice 2
– Setting information 2
• Edit the following file
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 63
File name Outline
AndroidManifest.x
ml
• Register RegisterServiceStarter as service
• As setting of Intent Filter, set
android.intent.action.BOOT_COMPLETED (starting
completed) to Android
Practice
2.4. Broadcast receiver
Practice 2
• How to check
– After starting application once, close emulator once, and re-start. Check
if the log at that time output or not
• RegisterService#onStart
– Starting log 「onStart start 」
– Ending log 「 onStart end」
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 64
Practice
2.4. Broadcast receiver
Practice 2
• Answer of Practice
– RegisterServiceStarter
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 65
package jp.oesf.mtgeduwg.training.rssreader;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class RegisterServiceStarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
Intent serviceIntent = new Intent(context, RegisterService.class);
context.startService(serviceIntent);
}
}
}
※This case only 1 intent will come, so it is ok with non-if statement
Practice
2.4. Broadcast receiver
Practice 2
• Answer of Practice
– AndroidManifest.xml (Only the corresponding part extracted)
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 66
・・・
<application>
・・・
<receiver android:name="RegisterServiceStarter">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
・・・
</application>
Practice
2.4. Broadcast receiver
Practice 2[Supplement]
1. Check code of SendBroadcast project, check if the broadcast of the given
action will be thrown or not when pushing button of this application.
2. For that action, modify the file of RssReader project in order to start
RegisterServiceStarter
3. After starting RssReader, check with log if service of RssReader started or
not when starting SendBroadcast and pushing button
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 67
2.5. Content provider
• What is content provider?
– The mechanism which can access (search, add, update,
delete the data kept by application※ from other application
– Detailed example:
• Refer the telephone call log from application
• Add Website from application to bookmark of browser
• Refer the address book from application
• Refer calendar from application
※Data is the information shown by application in file, database permanently
68
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
2.5 Content provider
• Content provider will decide interface in order to
execute the safe accessing
– Main interface
69
Content provider
query
insert
update
delete
External
application
Interface is
decided# Event name Content
1 Search
(query)
Search data,
return
searching
result
2 Add (insert) Add data
3 Update
(update)
Update data
4 Delete
(delete)
Delete data
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
■Refer to development guide for Android Developers
http://developer.android.com/intl/ja/reference/android/content/ContentProvider.html
2.5 Content provider
• How to implement content provider
– Create newly class of content provider
– Implement the abstract method of content provider if needed
– Register the created content provider to AndroidManifest.xml
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 70
2.5 Content provider
• How to implement content provider
1. Create new content provider class
• Create the content provider class inherited from ContentProvider base
class
• The following 6 methods are defined as the abstract methods of
ContentProvider class, so all methods are supposed to be implemented
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 71
Method Return value type Outline
onCreate boolean
• Run when starting content provider
• When provider initialization is stopped abnormally, true will be returned
getType String • Return the handling text string in MIME type
query cursor
• Search
• Return result as Cursor object
Insert int
• Insert
• Return the inserted number
update int
• Update
• Return the updated number
delete int
• Delete
• Return the deleted number
2.5 Content provider
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 72
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
public class SampleProvider extends ContentProvider {
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
・Sample code
2.5 Content provider
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 73
@Override
public boolean onCreate() {
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
return null;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
return 0;
}
}
・Sample code
(continue)
2.5 Content provider
2. Implement the abstract method of content provider if needed
i. Generate object of normal SQLiteOpenHelper with onCreate and save as
instance variable
The context specified to argument of constructor will use getContext
method
ii. With 4 methods operate database, get object of SQLiteDatabase from
SQLiteOpenHelper object
Use the gotten SQLiteDatabase object to operate for database
※ SQLiteDatabase object can be got by the one who implement with onCreate also.
iii. onType is the method of returning MIME type, and in case of dividing type
with the specified URI, it will be implemented as a means to inform that
type to user
In not complicated case, it is OK with usual-unused (return null;)
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 74
2.5 Content provider
• Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 75
・・・
private SampleSqliteOpenHelper sqliteOpenHelper;
private SQLiteDatabase db;
@Override
public boolean onCreate() {
sqliteOpenHelper = new DatabaseOpenHelper(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
db = sqliteOpenHelper.getReadableDatabase();
return db.query("RSS_FEED", projection, selection, selectionArgs, null, null, sortOrder);
}
・・・
・・・1
・・・2
2.5 Content provider
3. Register the created content provider to AndroidManifest.xml
• Steps
i. Open AndroidManifest.xml and select Application tab
ii. Click [Add] button of Application Nodes
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 76
i
ⅱ
2.5 Content provider
iii. Select Provider from the displayed screen, click 「OK」 button
※ In case cursor is in the registered node, the layer will be checked,
so please select upon radio button
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 77
ⅲ
※
2.5 Content provider
iv. After checking that the added Provider is selected, input name of
class of the Provider created in [Name] field
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 78
ⅳ
It is convenient to
browse if clicking
Browse button
2.5 Content provider
v. Scroll down Attribute for Provider, specify the unique content
provider name to Authorities tag
Normally it is the same with package name
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 79
ⅴ
2.5 Content provider
※ It is added to AndroidManifest.xml as below:
By doing this, it could be registered as class of content provider
Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 80
・・・
<application ・・・>
・・・
<provider
android:authorities="jp.oesf.sample.sampleprovider“ android:name=“SampleProvider">
</provider>
・・・
</application>
・・・
2.5 Content provider
3. The created content provider will use ContentResolver object
i. Pass URI for accessing to content provider to parse method of Uri object
to generate Uri object
The specified URI is content:// the value of Authorities of content
provider
ii. Use Context#getContentResolver method to get ContentResolver object
In ContentResolver, query, Insert, update, delete, getType methods are
prepared in the same form with ContentProvider
• Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 81
Uri uri = Uri.parse("content:// jp.oesf.sample.sampleprovider”);
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
・・・ⅰ
・・・ⅱ
2.5 Content provider
• Reference
– In case of diverging the processing according to value of URI (for example: specifying
table name, simple authentication), it is necessary to check URI with logic
At that time, it is better to use android.content.UriMatcher class
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 82
import android.content.UriMatcher;
private static final UriMatcher uriMatcher;
static{
uriMatcher = new
UriMatcher(UriMatcher.NO_MATCH);uriMatcher.addURI("jp.oesf.mtgeduwg.traini
ng.rssreader", "FOO", 1);
uriMatcher.addURI("jp.oesf.mtgeduwg.training.rssreader", “FOO/#", 2);
}
Inside method
switch(uriMatcher.match(uri)){
case 1: ・・・
case 2: ・・・
default: ・・・
Sample code
Practice
2.5 Content provider
Practice 3
• Practice theme
– Create content provider in RssReader, make it is possible to search
information of RSS_FEED table from external application.
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 83
Click button
Practice
2.5 Content provider
Practice 3
• Practicing steps
1. Create newly RssProvider which is content provider
2. With onCreate of RssProvider, get SQLiteOpenHelper object
3. With query method of RssProvider, get SQLiteDatabase object with
SQLiteOpenHelper#getReadableDatabase method
4. With query method of RssProvider, call SQLiteDatabase#query,
return the recorded Cursor
5. Add setting of RssProvider to AndroidManifest.xml
6. Check Main# onClickGetList method of TestContentProvider project
(It is implemented already so check only)
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 84
Practice
2.5 Content provider
Practice 3
– Setting information 1
• Execute the following class, method
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 85
Target Class Method Outline
Content
Provider
RssProvider
• Create newly
• Package is
jp.oesf.mtgeduwg.training.rssreader
onCreate • Get SQLiteOpenHelper object
query
• Search the condition of argument as it
is from RSS_FEED table, and return that
result
Practice
2.5 Content provider
Practice 3
– Setting information 2
• Edit the following file
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 86
File name Outline
AndroidManifest.xml
• Register RssProvider as content provider
• Set jp.oesf.mtgeduwg.training.rssreader to android:authorities
Practice
2.5 Content provider
Practice 3
• How to check
– When launching TestContentProvider application, and pushing 「GET
LIST」 button, get the value from database via content provider and
make it display list on screen
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 87
Click button
Practice
2.5 Content provider
Practice 3
• Answer of Practice
– RssProvider.java
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 88
package jp.oesf.mtgeduwg.training.rssreader;
import jp.oesf.mtgeduwg.training.rssreader.helper.DatabaseOpenHelper;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
public class RssProvider extends ContentProvider {
private DatabaseOpenHelper databaseOpenHelper;
private SQLiteDatabase db;
Practice
2.5 Content provider
Practice 3
• Answer of Practice
– RssProvider (continue)
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 89
@Override
public boolean onCreate() {
databaseOpenHelper = new DatabaseOpenHelper(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
db = databaseOpenHelper.getReadableDatabase();
return
db.query("RSS_FEED", projection, selection, selectionArgs, null, null, sortOrder);
}
・・・
Practice
2.5 Content provider
Practice 3
• Answer of Practice
– AndroidManifest.xml
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 90
・・・
<application>
・・・
<provider android:authorities="jp.oesf.mtgeduwg.training.rssreader"
android:name="RssProvider"></provider>
・・・
</application>
・・・
Practice
2.5 Content provider
Practice 3[Supplement]
• Practice theme
– Try to implement as below:
• Make it specifies with URI, not writing without spaces in code
content://jp.oesf.mtgeduwg.training.rssreader/RSS_FEED
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 91
There is no answer, please refer to sample
3. Practical development
92
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
Chapter 3 - Outline
• Notification
• Support multi-resolution
• Support multi-language
• adb tool
93
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
3.1. Notification
• What is notification?
– The function to display information in a given time on status bar of the
upper part of screen
– When opening status bar, the list screen of notification will be
displayed, and then it is possible to start up activity
94
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
3.1. Notification
• How to implement notification
– Get NotificationManager class which handles notification
– Generate Notification object
– Generate the pending intent which started when notification list is
clicked
– Set event information in Notification object
– Display notification
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 95
3.1. Notification
• How to implement notification
1. Get NotificationManager class which handles notification
– Can get NotificationManager by invoking Context#getSystemService
– Specify constant of Context.NOTIFICATION_SERVICE to argument of
the above method
– Return value is Object type so typecast in NotificationManager type
Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 96
import android.app.NotificationManager;
import android.content.Context;
・・・
NotificationManager nm =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
・・・1
3.1. Notification
2. Generate Notification object
• Call constructor and generate object
• Specify resource ID of icon, message displayed on status bar in
argument of constructor, and time (milliseconds) displayed in list
Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 97
import android.app.Notification;
・・・
Notification notification = new Notification(R.drawable.icon,“Could get RSS",
System.currentTimeMillis());
・・・2
3.1. Notification
3. Generate the pending intent which started when
notification list is clicked
• Generate PendingIntent by getActivity method (static method) of
PendingIntent
• There are 4 arguments of getActivity, so specify context, request
code (now it is unused, so it is usually 0), intent, flag (it is 0 in
case of not used )
Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 98
import android.app.PendingIntent;
import android.content.Intent;
・・・
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this,RssListActivity.class), 0);
About flag: PendingIntent.FLAG_UPDATE_CURRENT,…
Refer to: http://developer.android.com/reference/android/app/PendingIntent.html
・・・3
3.1. Notification
4. Set event information in Notification object
• Set event information with Notification#setLatestEventInfo
• There are 4 arguments of setLatestEventInfo, so specify context,
title, ticker text, pending intent
Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 99
notification.setLatestEventInfo(this, "RssReader", “RSS got", pendingIntent); ・・・4
3.1. Notification
5. Display notification
• Display notification actually with NotificationManager#notify
• There are 2 arguments of notifying, so specify id(the number
unified with that notification inside application), Notification
object
Sample code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 100
nm.notify(0,notification); ・・・5
3.1. Notification
The sample code until 1-5 are summarized and shown as below:
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 101
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
・・・
NotificationManager nm = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon,“Could get RSS",
System.currentTimeMillis());
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new
Intent(this,RssListActivity.class), 0);
notification.setLatestEventInfo(this, "RssReader", “RSS got", pendingIntent);
nm.notify(0,notification);
・・・
Practice
3.1. Notification
Practice 4
• Practice theme
– Use notification to create the processing to notify the ending when
logic of getting RSS with service is ended
– Click to the applicable notification on screen of notification list, it will
transit to list screen (RssListActivity)
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 102
Logic ended
Start as service
Click
Practice
3.1. Notification
Practice 4
• Practicing steps
1. Execute the following steps after logic of getting RSS of
RegisterService#onStart
i. Get NotificationManager
ii. Generate Notification object
iii. Generate PendingIntent like transiting to list screen(RssListActivity)
iv. Set event information to Notification object
v. Display notification
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 103
Practice
3.1. Notification
Practice 4
– Setting information 1
• Execute the following class, method
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 104
Target Class Method Outline
Get RSS RegisterService onStart
• Display notification
• Flag of PendingIntent is 0
Supplemental notes
In case of specifying text string to display by strings.xml without describing directly
to Java, CharSequence will be required as argument in Java, so it is OK if using
Context#getText(int resId)
Eg: getText(R.string.app_name)
Practice
3.1. Notification
Practice 4
– Setting information 2
• It should be displayed as below:
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 105
Display image of
R.drawable.icon
Display 「could
get RSS」
Display 「RSS
getting
completed」
Display
「RssReader」
Display time at
displaying
timing
Practice
3.1. Notification
Practice 4
• How to check
– When getting RSS by pushing 「Get RSS」 button…, the following
notification will be displayed
– Tap to the applicable notification from list of notification, it will transit to
list screen of RSS reader
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 106
Click
Practice
3.1. Notification
Practice 4
• Practice answers
– RegisterService
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 107
import jp.oesf.mtgeduwg.training.rssreader.helper.RssFeedRegister;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
・・・
@Override
public void onStart(Intent intent, int startId) {
・・・
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon,getText(R.string.notification_ticker_text),
System.currentTimeMillis());
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,RssListActivity.class), 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title), getText(R.string.notification_text),
pendingIntent);
nm.notify(0,notification);
・・・
Practice
3.1. Notification
Practice 4
• Answer of Practice
– strings.xml
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 108
・・・
<resources>
・・・
<string name="notification_title">RssReader</string>
<string name="notification_ticker_text">Could not get RSS</string>
<string name="notification_text">RSS getting finished</string>
・・・
</resources>
※ In answer example, the displaying text is defined in resource file of text string
The correct answer is the value of String written directly to code of Java
Or key name of resource(notification_title…)
Practice
3.1. Notification
Practice 4[Supplement]
• Practice theme
– Delete notification when transiting to list screen
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 109
There is no answer example
Please refer to sample
3.2. Support multi-resolution
• Support multi-resolution
– Android support multi-resolution officially from version 1.6
– In case the version installed to Android terminal is unknown, if the
application doesn’t support multi-resolution, it may display incorrectly
– It is necessary to know how one Android application can support
multi-resolution
110
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
3.2. Support multi-resolution
• Density and screen server
• DIP (Density Independent Pixel)
• Scaling
• Multi-resolution-supported Tips
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 111
3.2. Support multi-resolution
• Density and screen size
– In Android, devices are categorized according to Density and screen size
– Density is divided according to value of DPI (Dots Per Inch/ Number of dots per
inch) to 3 types as below
– According to 3 types, the directory of the photo file to be called will be divided
and it is possible to display the photo suitable to that Density.
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 112
Density DPI range Deemed DPI value Supported photo file directory
Low-Density 100dpi-140dpi 120dpi res/drawable-ldpi
Medium-Density 140dpi-180dpi 160dpi res/drawable-mdpi
High-Density 190dpi-250dpi 240dpi res/drawable-hdpi
※ Deemed DPI value
Eg: In Low-Density device, all DPI are 120dpi
3.2. Support multi-resolution
– Screen sizes are divided into 3 types according size of screen
– By dividing the layout directory to be called according to 3 types, the layout
suitable to that screen size can be called out.
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 113
Name Screen size Supported layout file directory
Small Screen - 3.0 inch res/layout-small
Normal Screen 3.0 inch – 4.0 inch res/layout
Large Screen 4.0 inch- res/layout-large
Low-Density Medium-Density High-Density
Small Screen QVGA (240x320), 2.6"-3.0" inch
Normal
Screen
WQVGA (240x400), 3.2"-3.5" inch
FWQVGA (240x432), 3.5"-3.8" inch
HVGA (320x480), 3.0"-3.5" inch
WVGA (480x800), 3.3"-4.0" inch
FWVGA (480x854), 3.5"-4.0" inch
Large Screen
WVGA (480x800), 4.8"-5.5" inch
FWVGA (480x854), 5.0"-5.8" inch
– The following table is the result of summarizing 2 types
Refer to: http://developer.android.com/intl/ja/guide/topics/resources/providing-resources.html#AlternativeResources
3.2. Support multi-resolution
• DIP (Density Independent Pixel)
– When specifying size directly, normally Pixel/px is used, but in case of pixel the UI
will be not intended by Density
– In Android the concept of DIP(Density Independent Pixel) _ the virtual pixel
unit is introduced, and it can be supported for that.
– Unit of DIP is described as dip or dp, but dp is suggested.
– It is calculated with the formula: pixels = dips * (density / 160)
It means with 160dpi= Medium-Density, 1px=1dp
– Scale-independent Pixels (sp) is a concept like DIP, but it is the value added by not
only Density but also font size of user.
But currently in Android, there is no 「User font size setting」, so it is 1dp=1sp
– [Supplement] In all methods of Java prepared in Android, only pixel can be used.
Therefore, it is necessary to convert with the above formula in code of Java
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 114
3.2. Support multi-resolution
• Scaling
– 3 directories to be called according to Photo file Density are prepared, but
sometimes only res/drawable not all of them are prepared.
– In the above case, Scale Density of Medium-Density will be 1, and the scaling
function to enlarge/reduce the size of photo according to Density will be prepared.
– If the photo which no need to scale is stored in res/drawable-nodpi, it will be
displayed with that resolution as it is without scaling.
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 115
Density Scale Density
High-Density 1.5
Medium-Density 1
Low-Density 0.75
Scale Density
3.2. Support multi-resolution
• Multi-resolution-supported Tips
– Use wrap_content or fill_parent (match_parent from 2.2) to specify size of
width/height of layout
In case it is necessary to specify numeric value, use dp not px
– Photo file is prepared suitable with Density
– Recognize the different of screen size in order not to fill over in horizontal
direction
In case of filling by force, prepare layout file for Small Screen separately
– Convert the pixel value in Java code to DIP which do not hard code
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 116
3.2. Support multi-resolution
• Multi-resolution-supported Tips (continue)
– When the screen not supported is set in the 3 types of screen size, it is no
problem if describing the setting of supports-screens of AndroidManifest.xml
Sample of AndroidManifest.xml (Not support Small Screen)
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 117
・・・
<application>
・・・
<supports-screens
android:largeScreens=“true”>
android:normalScreens=“true”>
android:smallScreens=“false” />
・・・
</application>
・・・
Practice
3.2. Support multi-resolution
Practice 5
• Practice theme
– Run the application of Multi Resolution project on each emulator which
is different in screen size and Density, and check that screen and source.
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 118
ldpi mdpi hdpi
Practice
3.2. Support multi-resolution
Practice 5
• Checking point of practice
– Check in Small-Screen if buttons are 2-stage group or not
=> res/layout-small/main.xml is read
– Check if R.drawable.droid is displayed by other photo prepared for
each resolution or not
=> res/drawable-Xdpi/droid.jpg is displayed
– Check if R.drawable.droid_nodpi is displayed by one photo without
scaling or not
=> res/drawable-nodpi/droid_nodpi.jpg is displayed
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 119
Practice
3.2. Support multi-resolution
• Checking point of practice (continue)
– Check if R.drawable.droid_scaling is scaled and displayed with
enlarged/reduced size combining with resolution or not
=> res/drawable/droid_scaling.jpg is scaled and displayed
– The displayed text is specified as px for the upper one, dp for the
lower, so that check if the lower text ‘s size is changed combining with
the resolution or not.
=> res/layout/main.xml is read
– The margin of photo is dp specified, so check if the size is changed
combining with resolution or not.
=> res/layout/main.xml is read
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 120
Practice
3.2. Support multi-resolution
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 121
R.drawable.droid
Different photo is
prepared for each
Density
R.drawable.droid_nodpi
All are displayed with
the same resolution
without scaling
R.drawable.droid_scaling
scaled to be displayed
In Small-Screen buttons are
divided into 2 stage to be
displayed
Upper is px specified
Lower is dp specified
Lower will be changed
according to resolution
Margin of photo is dp
specified
Practice
3.2. Support multi-resolution
Practice 5
• Practice steps
1. The following 3 emulators are prepared, so start up that, launch
application Multi Resolution project and check the displayed screen
and source
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 122
Emulator name Screen size and Density
QVGA-small-ldpi Small Screen, Low-Density
HVGA-normal-mdpi Normal Screen, Medium-Density
WVGA-normal-hdpi Normal Screen, High-Density
Practice
3.2. Support multi-resolution
Practice 5
• How to check
– Check the checking point of practice
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 123
3.3. Support multi-language
• Support multi-language
– Android application would be used in many countries on the world, so
it should support multi-language.
– If the text string is described in Android as resource file in advance,
the mechanism to support multi-language will be prepared simply.
– Combining with language setting in device, the resource file under
directory of res/values-[language code] or res/values-[language code]-
r[region code] can be read
– In case device has no directory for language setting, it will be read
under res/values
124
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
3.3. Support multi-language
• In case of English(Australia): values-en-
rAU
• In case of English (not Australia: values-en
• In case of Japanese: values-ja
• In the cases other than above: values will
be read
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 125
Example
Specify language code ISO 639-1 form http://www.loc.gov/standards/iso639-2/php/code_list.php
Specify region code ISO 3166-1-alpha-2 form
http://www.iso.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_elements.htm
Practice
3.3. Support multi-language
Practice 6
• Practice theme
– When changing language setting of emulator, check if the text string
resource file called corresponded to that is changed or not
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 126
Practice
3.3. Support multi-language
Practice 6
• Practice steps
1. Create res/values-en, res/values-en-rAU, res/values-ja
2. Copy res/values/strings.xml to the created 3 directories
3. Change strings.xml/go_to_list_page_button_label key value of each
strings.xml as below:
4. Start up emulator, check if the display of changing language setting is
changed or not
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 127
Target Key Value
res/values/strings.xml go_to_list_page_button_label List displaying (Default)
res/values-en/strings.xml go_to_list_page_button_label List displaying (English)
res/values-en-rAU/strings.xml go_to_list_page_button_label List displaying (Australia)
res/values-ja/strings.xml go_to_list_page_button_label List displaying (Japan)
Practice
3.3. Support multi-language
Practice 6
• How to check
– Launch RssReader on emulator
Change language setting and check if the displaying text of button in
menu screen is changed or not
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 128
Language Displaying text string Value
Japan go_to_list_page_button_label List displaying (Japan)
English(Australia) go_to_list_page_button_label List displaying (Australia)
English ※not Australia go_to_list_page_button_label List displaying (English)
All above go_to_list_page_button_label List displaying (Default)
Practice
3.3. Support multi-language
Practice 6
• How to set up language
i. In Home screen, 「menu」 button =>Push 「Setting」
ii. In Setting screen, push 「Language & Keyboard」
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 129
ⅰ ⅱ
Practice
3.3. Support multi-language
iii. On Language & Keyboard setting screen, push 「Select language」
iv. Push target language on Locale screen
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 130
ⅲ ⅳ
Practice
3.3. Support multi-language
Practice 6
• Answer of Practice (only the applicable part)
– res/values/strings.xml
– res/values-en/strings.xml
– res/values-en-rAU/strings.xml
– res/values-ja/strings.xml
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 131
<string name=“go_to_list_page_button_label”>List displaying (Default)</string>
<string name=“go_to_list_page_button_label”>List displaying (English)</string>
<string name=“go_to_list_page_button_label”>List displaying (Australia)</string>
<string name="go_to_list_page_button_label">List displaying (Japan)</string>
3.4.adb tool
• What is adb tool?
– This is the tool to manage the status of device of emulator which
belong to SDK
– Input command by command prompt to use
– In case of passing path in <SDK_ROOT>/tools, recognize adb command
in every directory
132
This material is licensed under the Creative
Commons License BY-NC-SA 4.0.
Practice
3.4.adb tool
Practice 7
• Practice theme
– Operate actually what described in explanation to learn how to use
adb tool
1. adb -help
Help of adb tool is displayed
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 133
Practice
3.4.adb tool
Practice 7
2. adb devices
Display the list of the running emulator and real device
3. adb uninstall <Package name>
Uninstall the application applicable to package name
4. adb install <apk path>
Install application
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 134
Practice
3.4.adb tool
Practice 7
5. adb push <local path> <remote path>
Copy <remote path> of <local path>
6. adb pull <Remote path> <local path>
Copy <remote path> file to <local path>
7. adb shell
Connect with Terminal(emulator) and launch shell
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 135
Practice
3.4.adb tool
Practice 7 (Shell operation is as below:)
8. cd <direct path>
Direct to current directory
9. ls
Display information of file or directory
10.rm <Target file path>
Delete file
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 136
Practice
3.4.adb tool
Practice 7 (sqlite3 command is as below:)
11.sqlite3 <Database file path>
Direct to current directory
12. .help
Display Help
13..dump
Display dump file
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 137
Practice
3.4.adb tool
Practice 7
11..schema
Display CREATE sentence
12. <SQL sentence>;
Issue SQL sentence
13..exit
Exit sqlite3 command
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 138
3.5.JUnit
• What is JUnit?
– It is the testing framework to carry out unit test of Java program
– It can create test code for confirming the behavior of the created
program runs as expected or not, and carry out verification by
executing test code
– Testing is made to a program, and can be executed many times
mechanically, so it is helpful for securing quality
139
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 139
3.5.JUnit
• What is JUnit for Android?
– In Android, the JUnit is customized from JUnit3
– It is able to issue user’s screen operation and event( onCreate, etc) of
Life cycle
=> It reaches beyond unit test partially to able to use in scenario test
– Normal JUnit will run in Java VM on development machine, but
Android JUnit runner implements testing by installing and running
testing application on Emulator and real machine.
140
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 140
3.5.JUnit
• Structure of JUnit base class
– It is necessary to make test class extended from
junit.framework.TestCase base class
– In Android, the class inherited from TestCase class above is
prepared after matching to test target
– It is up to purpose for using this inherited class
141
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 141
3.5.JUnit
– The relation of TestCase class and class for testing being
provided by Android
junit.framework.TestCase
InstrumentationTestCase
ActivityTestCase
ActivityInstrumentationTestCase2
ActivityUnitTestCase
SingleLaunchActivityTestCase
AndroidTestCase
ServiceTestCase
ProviderTestCase2
ApplicationTestCase
142
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 142
3.5.JUnit
– Outline of each basis class
• ActivityInstrumentationTestCase2
– Screen operation such as push button is possible
• ActivityUnitTestCase
– It is possible to execute event( such as onCrete) on Life cycle of Activity
• ServiceTestCase
– It is possible to execute service
• ProviderTestCase2
– It is possible to execute Content Provider
• ApplicationTestCase
– It is possible to use it in testing application
143
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 143
3.5.JUnit
• JUnit real code sample
– At first, general JUnit code without relation with Android
144
public class Foo {
public int add(int x, int y){
return x + y;
}
}
• Code of test target Method that returns after adding 2
arguments
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 144
3.5.JUnit
• Test code
145
import junit.framework.TestCase;
public class FooTest extends TestCase {
private Foo foo = null;
protected void setUp() throws Exception {
super.setUp();
foo = new Foo();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testAdd(){
int actual = foo.add(4, 5);
assertEquals(9, actual);
}
}
・・・1
・・・2
・・・3
・・・4
・・・5
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 145
3.5.JUnit
1. Inherit junit.framework.TestCase, and create class
Class name is usually 「Class name of test target」 + “Test”
2. setUp method is executed before test is started
Prepare testing( arrange data, generate object, etc.) by this method
3. tearDown method is run when testing finishes
Clean-up( such as restore data) by this method after test
4. Method name of test method is testXXX, and assumed no argument with
public void
5. assertEquals method is to confirm the behavior of Test target code is
correct or not. By setting the acquired value according to expectation
value in the first argument, and actual testing in the second argument, if
both are right, testing passed, if not it is error
Besides, there are assertTrue, assertFalse, etc.
146
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 146
3.5.JUnit
• Sample of ActivityInstrumentationTestCase2
147
public class FooctivityTest
extends ActivityInstrumentationTestCase2<FooActivity> {
public FooActivityTest() {
super("jp.oesf.mtgeduwg.training.rssreader", FooActivity.class);
}
public void testUrlFieldKeyInput() {
// Transmission of key ("T","E","S","T", and input)
sendKeys(KeyEvent.KEYCODE_T, KeyEvent.KEYCODE_E
KeyEvent.KEYCODE_S, KeyEvent.KEYCODE_T);
assertEquals(“test”, urlField.getText().toString());
}
}
1: Package of test target class
2: Class information of test target class
Input key
Activity of
test target
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 147
3.5.JUnit
• Sample of ActivityInstrumentationTestCase2
148
package jp.oesf.mtgeduwg.training.test;
public class AddActivityTest
extends ActivityInstrumentationTestCase2<AddActivity> {
public AddActivityTest() {
super("jp.oesf.mtgeduwg.training.rssreader", AddActivity.class);
}
public void testAddButtonClick() {
getActivity().runOnUiThread(new Runnable() {
public void run() {
urlField.setText("http://www.oesf.jp/modules/news/index.php?page=rss");
addButton.performClick();
}});
getInstrumentation().waitForIdleSync();
assertTrue(existsUrlAddressById(10));
Run button clicking
Request processing to UI
thread
Activity of
test target
Wait closing process of UI
thread
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 148
3.5.JUnit
• Sample of ActivityInstrumentationTestCase2 (Screen
transition)
149
public void testAddButtonClick() {
ActivityMonitor monitor = new
ActivityMonitor("jp.oesf.mtgeduwg.training.rssreader.RssListActivity", null, false);
getInstrumentation().addMonitor(monitor);
getActivity().runOnUiThread(new Runnable() {
public void run() {
addButton.performClick();
}});
Activity rssListActivity = getInstrumentation().waitForMonitor(monitor);
if(rssListActivity != null){
rssListActivity.finish();
}
}
Monitor transition target
Activity
Get transition target Activity
Finish transition target Activity
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 149
3.5.JUnit
• Sample of ActivityUnitTestCase
150
package jp.oesf.mtgeduwg.training.test;
public class AddActivityUnitTest extends ActivityUnitTestCase<AddActivity> {
public AddActivityUnitTest() {
super(AddActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
public void testSendResumeEvent() throws Exception {
Intent intent = new Intent(Intent.ACTION_MAIN);
startActivity(intent, null, null);
getInstrumentation().callActivityOnResume(getActivity());
}
Activity of
Test target
Run onResume
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 150
3.5.JUnit
• Sample of ServiceTestCase
151
package jp.oesf.mtgeduwg.training.test;
public class AddServiceTest extends ServiceTestCase <AddService> {
public AddServiceTest() {
super(AddSer viceclass);
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
public void testService() {
Intent intent = new Intent(AddService.class.getName());
int result = startService(intent);
・・・
}
Activity of
test target
Create Intent, then start
up Server based on that
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 151
3.5.JUnit
• Memo
152
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 152
3.5.JUnit
• How to create JUnit project
1. Select “New”->”Other” from menu “File” of Eclipse
153
1
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 153
3.5.JUnit
2. Select “Android Test Project” in Android folder, then push
“Next” button
3. Default value for specifying Test target project in the
column of An Exisiting Android Project of TestTarget is
input, so if there is no change reason, click “Finish”
button
154
2 3
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 154
3.5.JUnit
4. Next, select “File”, then “New”->”Other” to create
TestCase
5. Select 「JUnit Test Case」 in JUnit folder, then press
“Next” button
155
4
5
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 155
3.5.JUnit
6. Confirm the buttons being selected in New JUnit 3, and
input parent class in Superclass, then push “Finish”
button
156
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 156
3.5.JUnit
• AndroidManifest.xml
– When creating Test project by using Eclipse, the following bold-faced
type is added in 2 places automatically( it is required for test
execution)
157
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jp.oesf.mtgeduwg.training.rssreader.test"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-library android:name="android.test.runner" />
</application>
<uses-sdk android:minSdkVersion="7" />
<instrumentation android:targetPackage="jp.oesf.mtgeduwg.training.rssreader"
android:name="android.test.InstrumentationTestRunner" />
</manifest>
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 157
3.5.JUnit
– How to execute test
• Right-click on Test project, then select Run as -> Android JUnit
Test
It is necessary to connect with emulator or real device
158
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 158
3.5.JUnit
– Check testing succeed/fail
• It is possible to check by JUnit view
159
Success Failure
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 159
Practice
3.5.JUnit
Practice 8
• Practice theme
– Create real test case of JUnit practically
– Create 2 test cases
– Study the way to do unit test in Android through what above
mentioned
160
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 160
Practice
3.5.JUnit
Practice 8
• Practice steps
1. Create RssReaderTest project that assumes RssReader is test target
2. Create class for testing RssReaderActivity and RegisterService
separately
3. Implement test method one by one for each one
i. In testing RssReaderActivity, push “Display list)” button, then check item
quantity of ListView being displayed in the “Display list” screen is bigger
than 0
Describe testing done
Hint: It is possible to get item quantity of ListView by
ListView#getCount()
ii. In testing RegisterService
Check data quantity being stored in RSS_FEED table of DB before and
after executing ResigsterService is increasing
Hint: It is possible to get data quantity of Cursor by Cursor#getCount()
161
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 161
Practice
3.5.JUnit
Practice 8
• How to confirm
– Execute testing to be green
162
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 162
Practice
3.5.JUnit
Practice 8
• Answer of Practice
– RssReaderActivityTest.java
163
package jp.oesf.mtgeduwg.training.rssreader.test;
import jp.oesf.mtgeduwg.training.rssreader.R;
import jp.oesf.mtgeduwg.training.rssreader.RssReaderActivity;
import android.app.Activity;
import android.app.Instrumentation.ActivityMonitor;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.Button;
import android.widget.ListView;
public class RssReaderActivityTest extends ActivityInstrumentationTestCase2<RssReaderActivity>{
public RssReaderActivityTest(){
super("jp.oesf.mtgeduwg.training.rssreader", RssReaderActivity.class);
}
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 163
Practice
3.5.JUnit
– RssReaderActivityTest.java (Continue)
164
public void testOnClickListButton(){
ActivityMonitor monitor = new
ActivityMonitor("jp.oesf.mtgeduwg.training.rssreader.RssListActivity", null, false);
getInstrumentation().addMonitor(monitor);
final Button button = (Button) getActivity().findViewById(R.id.list_button);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
button.performClick();
}
});
getInstrumentation().waitForIdleSync();
Activity rssListActivity = getInstrumentation().waitForMonitor(monitor);
ListView listView = (ListView) rssListActivity.findViewById(android.R.id.list);
assertTrue(listView.getCount() > 0);
if(rssListActivity != null){
rssListActivity.finish();
}
}
} This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 164
Practice
3.5.JUnit
– RegisterServiceTest.java
165
package jp.oesf.mtgeduwg.training.rssreader.test;
import jp.oesf.mtgeduwg.training.rssreader.RegisterService;
import jp.oesf.mtgeduwg.training.rssreader.helper.DatabaseOpenHelper;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.test.ServiceTestCase;
public class RegisterServiceTest extends ServiceTestCase<RegisterService> {
public RegisterServiceTest() {
super(RegisterService.class);
}
public void testRegisterService() {
int before;
int after;
Intent intent = new Intent(RegisterService.class.getName());
before = countDb();
startService(intent);
after = countDb();
assertTrue(after - before > 0);
}
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 165
Practice
3.5.JUnit
– RegisterServiceTest.java (Continue)
166
private int countDb() {
int result = 0;
Cursor cursor = null;
DatabaseOpenHelper databaseOpenHelper = new DatabaseOpenHelper(getContext());
SQLiteDatabase database = null;
try {
database = databaseOpenHelper.getReadableDatabase();
cursor = database.query(“RSS_FEED”, null, null, null, null, null, null);
result = cursor.getCount();
} finally {
if (database != null) {
database.close();
}
if(cursor != null){
cursor.close();
}
}
return result;
}
}
it will be an exception if not
close Cursor explicitly in
JUnit
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 166
Practice
3.5.JUnit
Practice 8[Supplement]
• Practice Theme
– Test other method
167
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 167
4. Practical development 2
168
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 168
Outline of Chapter 4
• Activity and Task
– Task
– Affinity
– Start-up mode
• Task management
169
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 169
4.1.Activity and Task
• The task of Application
– The task of Android is a mechanism of managing Activities
– The task is managing Activities by Stack structure
– Even when activity of other application is started up, that activity will
be handled as same task
170
Task Task Task
Start
up
Start
up
Start
up
Back BackBack
Root activity
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 170
4.1.Activity and Task
• Affinity
– It means 親和性(Affinity) if literal translation
– All activities in application have Affinity that all is the same task in
default
– Normally, activity in the same application has the same affinity, but it
is also possible to set affinity separately by setting affinity in individual
activity
171
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 171
4.1.Activity and Task
• The setting and the behavior of Affinity
– The value of affinity could be registered in AndroidManifest.xml
– In the default behavior, activities will be the same task even if affinity
is set
– In case of starting up by other task, it is necessary to describe the
setting of flag in intent that delivers to startActivity method
=> Even if taskAffinity is specified, if there is no flage, it will be the
same task
AndroidManifest.xml sample code
172
・・・
<activity android:name=“TestActivity" android:taskAffinity=“jp.sample.test"></activity>
・・・
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 172
4.1.Activity and Task
• Flag of intent
– Flag of intent is prepared in android.content.Intent
– It is ok to deliver the value of flag to Intent#setFlags
– In case of starting up by other task, it is necessary to describe the
setting of flag to intents that delivers to startActivity method
– The task linkage flag is as below
FLAG_ACTIVITY_NEW_TASK
start up new task based on Affinity
FLAG_ACTIVITY_MULTIPLE_TASK
start up new task in the multiple by using the flag
mentioned above at the same time
173
・・・
Intent intent = new Intent(this, NextActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
・・・
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 173
B:yyyTask:foo
X:xxx
Task:foo
4.1.Activity and Task
– FLAG_ACTIVITY_NEW_TASK
174
A:foo
Task:foo
A:xxxTask:bar
B:bar
Task:bar
B:yyyTask:foo
A:foo
X:foo
Task:bar
B:bar
Y:bar
Task:bar
B:yyy
Y:yyy
B:yyyTask:foo
A:foo
X:foo
C:foo
B X Y C
The activity which started up newly is allocated into new task,
and in case there is a task that has the same affinity,
it is allocated into that task.
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 174
Task:foo
4.1.Activity and Task
– FLAG_ACTIVITY_NEW_TASK
175
A:foo
Task:foo
A:xxxTask:bar
B:bar
B C B
However, in case the same activity has been allocated
as root activity of task, new task is not started,
and the task that has that activity will move to foreground
Task:foo
A:xxxTask:bar
B:bar
Task:foo
A:xxxTask:bar
B:bar
C:bar C:bar
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 175
Task:foo
4.1. Activity and Task
176
A:foo
Task:foo
A:xxxTask:bar
B:bar
B C B
If setting together with FLAG_ACTIVITY_NEW_TASK,
Task will be started newly even if the same affinity Task exists.
Task:foo
A:xxxTask:bar
B:bar
Task:foo
A:xxxTask:bar
B:barTask:bar
C:bar
Task:bar
Task:bar
B:bar
– FLAG_ACTIVITY_MULTIPLE_TASK
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 176
4.1.Activity and Task
177
• android:allowTaskReparenting attribute
– There is no application element of AndroidManifest.xml, and it is
possible to specify this as attribute of activity element
– In case of application element, and in case of activity element in
the entire of that application, this has effect on that activity
– In case of specifying the value as ”true”, when a certain task
moves to foreground, the activities that have affinity same as that
task are absorbed by that task, and reallocated
– Disable Root activity ( Rearrangement is not done)
Task:foo
A:foo
X:bar
Task:bar
B:bar Start up C: bar
Task:foo
A:foo
Task:bar
B:bar
Foreground Foreground
X:bar
C:bar
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 177
4.1. Activity and Task
• Activity and Start-up mode android:launchMode
– It is possible to specify as attribute of activity element of AndroidManifest.xml
178
Start-up Mode Allocated
task
Multiple
generation of
same activity
Whether to able
to include other
activities in task
The way to process new intent
when instance of same activity
exists
Standard
(Default)
Started
task
Multiple
generation
Possible To be processed newly( new
instance is generate)
singleTop Reuse or process newly when
same activity exists in the top of
stack
singleTask New
task( be
root
activity
always)
Only one task
is generated
In case it exists in the current task,
this task will move to
foreground( In case there is no
activity concerning to the top
position, intent will drop)
singleInstance Impossible
(only itself)
To be processed newly
Reference http://developer.android.com/intl/ja/guide/topics/fundamentals.html#lmodesThis material is licensed under the Creative
Commons License BY-NC-SA 4.0. 178
4.1.Activity and Task
• Memo column
179
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 179
4.2.Task management
180
• Clear Task
– After a certain period of time without application operation, when
Application is started up again from Launcher, excepting for root
activity, others will be destroyed
–The behavior above is default, and it is possible to change the
behavior by changing attribute of activity element
Task:foo
A:foo
B:bar
Start up App
C:foo
D:bar
Task:foo
A:foo
B:bar
C:foo
D:bar
Destroy 3
After a certain
period of time
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 180
4.2.Task management
181
–android:alwaysRetainTaskState
– In case it is specified as “true”, task is not cleared
– The setting is active for Root activity only
Task:foo
A:foo
B:bar
Start up App
C:foo
D:bar
Task:foo
A:foo
B:bar
C:foo
D:bar
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 181
4.2.Task management
182
– android:clearTaskOnLaunch
– In case it is specified as “true”, status of task is always
cleared even though a certain period of time has not elapsed,
and excepting for root activity, others will be destroyed
– Exactly, it is destroyed at the time of moving to background
– The setting is active for Root activity only
Task:foo
A:foo
B:bar
Start up App
C:foo
D:bar
Task:foo
A:foo
B:bar
C:foo
D:bar
Destroy 3
Always
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 182
4.2. Task management
183
–android:finishOnTaskLaunch
– In case it is specified as “true”, status of task is cleared
even if a certain period of time has not elapsed, excepting
for root activity, others will be destroyed
– Exactly, it is destroyed at the time of moving to background
– The setting is only active for root activity
Task:foo
A:foo
B:bar
Start up App
C:foo
D:bar
Task:foo
A:foo
B:bar
C:foo
D:bar
Destroy 3
Always
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 183
4.2.Task management
184
• Task and Intent flag
– FLAG_ACTIVITY_CLEAR_TOP
– When starting up an activity, if the same activities have been
allocated, destroy the activities upper than the started up one
–In case Start-up mode is ”standard”, destroy the display activities
to generate new instance
Task
A
B Start up A
C
Task
A
B
C
Destroy
A
If Start-up mode is not
“standard”, A is not destroyedThis material is licensed under the Creative
Commons License BY-NC-SA 4.0. 184
4.2.Task management
185
– FLAG_ACTIVITY_REORDER_TO_FRONT
– When starting up an activity, if the same activities have been
allocated, move the started up one to the head of task
– In case Start-up Mode is ”standard”, also destroy the displayed
activity to generate new instance
Task
A
B Start up A
C
Task
B
C
A
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 185
4.2.Taks management
186
– FLAG_ACTIVITY_NO_HISTORY
– If activity which started up after setting is moved to background,
activity will close
–The same behavior is done even if setting android:noHistory
attribute of activity as ”true”
Task
A
B Start up C
Task
A
C
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 186
4.2.Task management
187
– FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
– If activity which started up after setting this flag is moved to
background, activity will close
–The same behavior is done even if setting android:noHistory
attribute of activity as ”true”
Task
A
B Start up C
Task
A
C
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 187
Practice
4.3. Practice
Practice 9
• Practice theme
– Confirm behavior of FLAG_ACTIVITY_NEW_TASK
– Set flags above to all transitions, and confirm as follows
188
B:yyyTask:foo
X:xxx
Task:foo
A:foo
Task:foo
A:xxxTask:bar
B:bar
Task:bar
B:yyyTask:foo
A:foo
X:foo
Task:bar
B:bar
Y:bar
Task:bar
B:yyy
Y:yyy
B:yyyTask:foo
A:foo
X:foo
C:foo
B X Y C
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 188
Practice
4.3. Practice
Practice 9
• Practice steps
1. Modify the following points of Affinity project to complete
i. Confirm file composition of stub project
ii. Implement onClickGoTo?Button to each activity( exclude C.java)
Try to set flag FLAG_ACTIVITY_NEW_TASK of all intents when screen
transition
iii. Edit AndroidManifest.xml so that activities A,X,C become the same
affinity
iv. Similarly, try to make so that acitivities B, Y also become the same
affinity
189
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 189
Practice
4.3. Practice
Practice 9
– Setting information 1
• Implement the following class, method
190
Object Class Method Outline
- Each activity onClickGoTo?Button • Refer to screen transition
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 190
Practice
4.3. Practice
Practice 9
– Setting information 2
• Edit the following file
191
File name Outline
AndroidManifest.xml
• Set android:taskAffnity to each activity
• If group could be divided like steps, the value is decided properly
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 191
Practice
4.3. Practice
Practice 9
• How to confirm
– Confirm the transition: A=>B=>X=>Y=>C when you push a button of
screen
– After it is transited to C, check the transition :C=>X=>A=>Y=>B when you
push Back button
[Supplement] You understand that the task can be done to be 2 tasks
even if you long-push Home button
192
B:yyyTask:foo
X:xxx
Task:foo
A:foo
Task:foo
A:xxxTask:bar
B:bar
Task:bar
B:yyyTask:foo
A:foo
X:foo
Task:bar
B:bar
Y:bar
Task:bar
B:yyy
Y:yyy
B:yyyTask:foo
A:foo
X:foo
C:foo
B X Y C
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 192
Practice
4.3. Practice
Practice 9
• Answer of Practice
– A.java (Solution for other activity is omitted)
193
・・・
public void onClickGoToBButton(View v){
Intent intent = new Intent(this, B.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
・・・
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 193
Practice
4.3. Practice
Practice 9
• Answer of Practice
– AndroidManifest.xml
194
・・・
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".A"
android:label="@string/app_name">
・・・・
<activity android:name="B" android:taskAffinity="jp.oest.mtgeduwg.training.affinity.b"></activity>
<activity android:name="X"></activity>
<activity android:name="Y" android:taskAffinity="jp.oest.mtgeduwg.training.affinity.b"></activity>
<activity android:name="C"></activity>
・・・
※ Because the value of the affinity is one example, anything is good
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 194
Practice
4.3. Practice
Practice 9[Supplement 1]
• Practice theme
– Similarly, try to set other FLAG_ACTIVITY_NEW_TASK flag in screen C
transited from screen B which is the last transition target to do
transition
– If you do in that way, screen Y will be displayed without transition
from Screen C to Screen B
– Screen B is root activity, so the tasks that belong to Screen B only
move to foreground
195
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 195
Practice
4.3. Practice
Practice 9 [Supplement 2]
• Practice theme
– Change Affinity project freely, then confirm the change of behavior by
setting other flag, attribute
– Confirming from FLAG_ACTIVITY_XXXXX which is used at relatively-
high frequency in actual work is recommended.
196
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 196
5. Outside solidarity
197
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 197
The outline of chapter 5
• Outside solidarity outline and method
• JSON analyzing
• [Supplemental practice] XML analyzing
198
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 198
5.1.Outside solidarity outline and method
• The feature of Android is able to unite with outside
• The application that connects with Cloud server( server side) can be
made on the assumption of being able to connect with network at all
times
• XML and JSON are used mostly for data transaction between Cloud
server and terminal Cloud
• It is necessary to do to be able parse XML, JSON on Terminal
• Further, there are many samples implemented with JSON
199
Cloud
Service
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 199
5.1.Outside solidarity outline and method
• A sample of service
– Most of famous services have been providing XML and JSON
200
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 200
5.1.Outside solidarity outline and method
• What is XML?
• Extensible Markup Language
• A format that surrounds beginning and ending data by tag to add meaning
• Tag can be nested, so the hierarchical structure can be expressed, but the
cyclic structure can not be expressed, so it is specified by attribute
• It is used widely and it is possible to specify character code also
• There is tag as well as attribute in that, so it is a fault that the redundancy
readability is not good
201
<?xml version="1.0" encoding="UTF-8"?>
<statuses type="array">
<status>
<created_at>Thu Oct 21 19:13:18 +000
<id>28052969836</id>
<user>
<id>20536157</id>
<name>A Googler</name>
・・・・
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 201
5.1. Outside solidarity outline and method
• What is JSON?
• JavaScript Object Notation
• Originally it was the method of describing object in JavaScript, and
the specification of data format is made from that without change
• It is very simple and easy to understand
• Basically, character code is only UTF-8
• The faults are function is restrictive (「Numerical value」「Character
string」「Truth value(true、false)」「Array」「Object」「null」),
show-able data is restricted, and cycled data can not be handled
202
Reference:http://www.json.org/json-ja.html/
[
{
"created_at": "Thu Oct 21 19:13:18 +0000 2010",
"id": 28052969836,
"user": {
"id": 20536157,
“name”: “A Googler”,・・・
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 202
5.1. Outside solidarity outline and method
• HTTP communication on Android
• It is ok with the method same as HTTP connection in Java
• Use java.net class
Explanation about implementation Sample
1. Generate URL object based on URL of access target
2. Get HttpURLConnection object
and set method of HTTP also
3. Connect actually, and get resource as InputStream
Then, keep InputStream as byte[]
4. Write out byte[] to ByteArrayOutputStream
5. Settle HTTP communication
203
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 203
5.1.Outside solidarity outline and method
204
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
・・・
private void getHttp() {
HttpURLConnection http = null;
InputStream in = null;
ByteArrayOutputStream out = null;
byte[] byteArray = null;
Int size = 0;
try {
URL url = new URL(“http://www.oesf.jp”);
http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.connect();
in = http.getInputStream();
byteArray = new byte[in.available()];
・・・1
・・・2
・・・3
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 204
5.1.Outside solidarity outline and method
205
out = new ByteArrayOutputStream();
while ((size = in.read(byteArray)) } != -1) {
out.write(byteArray, 0, size);
} catch (Exception e) {
} finally {
try {
in.close();
} catch (Exception e) {
}
try {
http.disconnect();
} catch (Exception e) {
}
}
}
・・・4
・・・5
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 205
5.2.JSON analyzing
• JSON analyzing
– Data which is got by communication with HTTP is character
string in JSON format
– It is necessary to handle that character string as an object
to be able to use data
– JSONObject and JSONArray class of org.json package are
used for that
206
This material is licensed under the Creative
Commons License BY-NC-SA 4.0. 206
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced
Android Application Development Advanced

Más contenido relacionado

La actualidad más candente

Introduction to Android Development Latest
Introduction to Android Development LatestIntroduction to Android Development Latest
Introduction to Android Development Latest
Prof. Erwin Globio
 
Using Maven to build Java & Android program
Using Maven to build Java & Android programUsing Maven to build Java & Android program
Using Maven to build Java & Android program
Mu Chun Wang
 

La actualidad más candente (7)

Open Source Licenses and Tools
Open Source Licenses and ToolsOpen Source Licenses and Tools
Open Source Licenses and Tools
 
Android Application Development
Android Application DevelopmentAndroid Application Development
Android Application Development
 
Video Streaming: from the native Android player to uncoventional devices
Video Streaming: from the native Android player to uncoventional devicesVideo Streaming: from the native Android player to uncoventional devices
Video Streaming: from the native Android player to uncoventional devices
 
Developing Multi-OS Native Mobile Applications with Intel INDE
Developing Multi-OS Native Mobile Applications with Intel INDEDeveloping Multi-OS Native Mobile Applications with Intel INDE
Developing Multi-OS Native Mobile Applications with Intel INDE
 
Introduction to Android Development Latest
Introduction to Android Development LatestIntroduction to Android Development Latest
Introduction to Android Development Latest
 
The unconventional devices for the video streaming in Android
The unconventional devices for the video streaming in AndroidThe unconventional devices for the video streaming in Android
The unconventional devices for the video streaming in Android
 
Using Maven to build Java & Android program
Using Maven to build Java & Android programUsing Maven to build Java & Android program
Using Maven to build Java & Android program
 

Destacado

Android Application Development
Android Application DevelopmentAndroid Application Development
Android Application Development
InfoShell
 
iPhone and iPad Application Development
iPhone and iPad Application DevelopmentiPhone and iPad Application Development
iPhone and iPad Application Development
InfoShell
 

Destacado (14)

Androidプログラミング入門
Androidプログラミング入門Androidプログラミング入門
Androidプログラミング入門
 
Android組み込み開発テキスト pandaboard es編
Android組み込み開発テキスト pandaboard es編Android組み込み開発テキスト pandaboard es編
Android組み込み開発テキスト pandaboard es編
 
Android™組込み開発基礎コース BeagleBoard編
Android™組込み開発基礎コース BeagleBoard編Android™組込み開発基礎コース BeagleBoard編
Android™組込み開発基礎コース BeagleBoard編
 
Androidタブレットアプリケーション開発入門
Androidタブレットアプリケーション開発入門Androidタブレットアプリケーション開発入門
Androidタブレットアプリケーション開発入門
 
Androidアプリケーション応用 WebAPI開発
Androidアプリケーション応用 WebAPI開発Androidアプリケーション応用 WebAPI開発
Androidアプリケーション応用 WebAPI開発
 
Android UIデザイン入門
Android UIデザイン入門Android UIデザイン入門
Android UIデザイン入門
 
Android Application Development
Android Application DevelopmentAndroid Application Development
Android Application Development
 
Andriod vs iOS
Andriod vs iOSAndriod vs iOS
Andriod vs iOS
 
iPhone and iPad Application Development
iPhone and iPad Application DevelopmentiPhone and iPad Application Development
iPhone and iPad Application Development
 
Mobile application development: part 1: Andriod Vs IOS
Mobile application development: part 1: Andriod Vs IOS Mobile application development: part 1: Andriod Vs IOS
Mobile application development: part 1: Andriod Vs IOS
 
Androidアプリケーション開発入門
Androidアプリケーション開発入門Androidアプリケーション開発入門
Androidアプリケーション開発入門
 
Androidテスティング実践 基礎編
Androidテスティング実践 基礎編Androidテスティング実践 基礎編
Androidテスティング実践 基礎編
 
IT in banking
IT in bankingIT in banking
IT in banking
 
Thesis: THE ROLE OF INFORMATION TECHNOLOGY ON COMMERCIAL BANKS IN NIGERIA
Thesis: THE ROLE OF INFORMATION TECHNOLOGY ON COMMERCIAL BANKS IN NIGERIAThesis: THE ROLE OF INFORMATION TECHNOLOGY ON COMMERCIAL BANKS IN NIGERIA
Thesis: THE ROLE OF INFORMATION TECHNOLOGY ON COMMERCIAL BANKS IN NIGERIA
 

Similar a Android Application Development Advanced

Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
Jagdish Gediya
 
Android application development
Android application developmentAndroid application development
Android application development
slidesuren
 
In Act Developers Platform
In Act Developers PlatformIn Act Developers Platform
In Act Developers Platform
Eris Ristemena
 
China Science Challenge
China Science ChallengeChina Science Challenge
China Science Challenge
remko caprio
 
report_barc
report_barcreport_barc
report_barc
siontani
 

Similar a Android Application Development Advanced (20)

Fun Food
Fun FoodFun Food
Fun Food
 
How to create android applications
How to create android applicationsHow to create android applications
How to create android applications
 
Introduction to android basics
Introduction to android basicsIntroduction to android basics
Introduction to android basics
 
Bn1 1020 demo android
Bn1 1020 demo  androidBn1 1020 demo  android
Bn1 1020 demo android
 
Android App development and test environment, Understaing android app structure
Android App development and test environment, Understaing android app structureAndroid App development and test environment, Understaing android app structure
Android App development and test environment, Understaing android app structure
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
 
Presentation1
Presentation1Presentation1
Presentation1
 
Android Workshop
Android WorkshopAndroid Workshop
Android Workshop
 
MuleSoft Nashik Virtual Meetup#4 - Implementing CI/CD pipeline for deploying ...
MuleSoft Nashik Virtual Meetup#4 - Implementing CI/CD pipeline for deploying ...MuleSoft Nashik Virtual Meetup#4 - Implementing CI/CD pipeline for deploying ...
MuleSoft Nashik Virtual Meetup#4 - Implementing CI/CD pipeline for deploying ...
 
Android application development
Android application developmentAndroid application development
Android application development
 
Mobile web development
Mobile web developmentMobile web development
Mobile web development
 
Android Development recipes with java.pptx
Android Development recipes with java.pptxAndroid Development recipes with java.pptx
Android Development recipes with java.pptx
 
Introduction to android - SpringPeople
Introduction to android - SpringPeopleIntroduction to android - SpringPeople
Introduction to android - SpringPeople
 
In Act Developers Platform
In Act Developers PlatformIn Act Developers Platform
In Act Developers Platform
 
Introduction to Aspect Oriented Software Development
Introduction to Aspect Oriented Software DevelopmentIntroduction to Aspect Oriented Software Development
Introduction to Aspect Oriented Software Development
 
China Science Challenge
China Science ChallengeChina Science Challenge
China Science Challenge
 
SgCodeJam24 Workshop
SgCodeJam24 WorkshopSgCodeJam24 Workshop
SgCodeJam24 Workshop
 
How To Integrate Native Android App With React Native.
How To Integrate Native Android App With React Native.How To Integrate Native Android App With React Native.
How To Integrate Native Android App With React Native.
 
report_barc
report_barcreport_barc
report_barc
 
Android dev o_auth
Android dev o_authAndroid dev o_auth
Android dev o_auth
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Android Application Development Advanced

  • 1. Android Application Development Practical Training Course This material is licensed under the Creative Commons License BY-NC-SA 4.0. Ver2.00(03) 1
  • 2. About textbook usage 2 This material is licensed under the Creative Commons License BY-NC-SA 4.0. ・This textbook is licensed under the Creative Commons License BY-NC-SA 4.0. It is prohibited to use this material for commercial use otherwise you are OESF member or OESF education consortium member. ・This training program including all the provided documents are provided without any warranty from OESF. OESF assume no responsibility whatsoever for any damages/ occurrence of legal action resulting from the use or misuse of this course content/ detailed information of course.
  • 3. • To learn the practical knowledge, technology in developing Android application – Component of Android – Practical development • To bring up the power of execution in application development through seminar. – The main purpose is the developing skill 3 This material is licensed under the Creative Commons License BY-NC-SA 4.0. Purpose of training course
  • 4. Training schedule • The 1st day – Chapter 1 Introduction – Chapter 2 Android component – Chapter 3 Practical development • The 2nd day – Chapter 4 Practical development 2 – Chapter 5 Outside solidarity – Chapter 6 Practical debug – Chapter 7 Summary 4 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 5. The necessary skills for attending this course • Unless attended OESFcertificated Android application development basic training course, need following skills: – Precondition: having the basic skills of Android application – Be able to create the a simple application with several screens – Understand the syntax of JavaSE briefly and have actual experience – Understand the basic Eclipse operations 5 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 6. 1. Introduction 6 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 7. Chapter 1 - Outline • Development environment • Practice used in this course • Practice outline 7 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 8. 1.1. Development environment • In this training course, the following development tools will be used • They are installed already • The path is ready for running on the tools of SDK 8 Software Version Integrated development environment Eclipse 3.5 (Galileo) Java SDK JDK 6 Update 21 Android SDK 2.2 Android Plug-in Android Development Tools (ADT) Ver.0.9.6 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 9. 1.1. Development environment • Eclipse workspace Specify C:android_training_appliedworkspace • Emulator The emulator used for practicing will be WVGA-normal-hdpi if no particular one is specified • SDK path C:android_trainingtoolsandroid-sdk-windows This material is licensed under the Creative Commons License BY-NC-SA 4.0. 9
  • 10. 1.2. Application used in practice • In the 1st day of practice, the RSS reader created in Android application development basic training course will be added with extension 10 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 11. • Outline of screens & functions of RSS reader – This includes 3 screens This material is licensed under the Creative Commons License BY-NC-SA 4.0. 11 Start up # Screen name Function outline 1 Menu • Start up List view • Display option menu • When open menu is clicked, get RSS feed from Internet and register to database • After getting RSS feed, display the finish message by dialog 2 List • Display the RSS feed registered in database in list type 3 Detail • Display title, distributed date time, distributor name, detailed content of the RSS feed selected in list view 1.2. Application used in this course RSS reader ・・・ Direction of screen transition ① Menu screen ② List screen ③ Detail screen
  • 12. 1.3. Practice outline This material is licensed under the Creative Commons License BY-NC-SA 4.0. 12 Internet Database Get RSS feed from Internet Register RSS feed to database Search RSS feed from database Click List displaying button Select list data Display dialog after registering to database Get with service Start the processing with broadcast receiver Access with content provider Display notification of getting finished Multi resolution Support multi-language Menu screen List screen Detail screen
  • 13. 1.3. Practice outline Table layout – RSS_FEED table This material is licensed under the Creative Commons License BY-NC-SA 4.0. 13 String name type remarks _id INTEGER • Primary key • Auto increment GUID TEXT • Identifier allocated to RSS fee TITLE TEXT • Title PUBLISH_DATE TEXT • Distributed date time DESCRIPTION TEXT • Detailed content LINK TEXT • Link SENDER_NAME TEXT • Name of distributor
  • 14. 2. Android component 14 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 15. Chapter 2 - Outline • Activity • Intent • Service • Broadcast receiver • Content provider ※ Only consolidate on Activity and Intent The others will be practiced after the lecture 15 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 16. 2.1. Activity • What is activity? – The Android application screen is created by placing many parts such as Button, Checkbox, … on Activity – 1 screen is constructed based on 1 activity – Activity has 2 status: running and pausing 16 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 17. • Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 17 package jp.oesf.mtgeduwg.training.rssreader; import android.app.Activity; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; public class RssReaderActivity extends Activity implements OnClickListener { public void onClick(View view) { Log.v("RssReaderActivity","Clicked"); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); View listButton = findViewById(R.id.list_button); listButton.setOnClickListener(this); } } • Set Activity class as super class • Execute call back method if needed 2.1. Activity
  • 18. • Sample code of AndroidManifest.xml This material is licensed under the Creative Commons License BY-NC-SA 4.0. 18 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="jp.oesf.mtgeduwg.training.rssreader" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true"> ・・・ <activity android:label="@string/app_name" android:name="RssListActivity"></activity> </application> <uses-sdk android:minSdkVersion=“7" /> <uses-permission android:name="android.permission.INTERNET"></uses-permission> </manifest> •Creates the tag name as activity tag •Specify attribute android:name=“activity name” 2.1. Activity
  • 19. • [Ref] Life cycle which includes the notified events 19 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 2.1. Activity
  • 20. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 20 • [Ref] It is possible to set AndroidManifest.xml with resource editor 2.1. Activity
  • 21. 2.2. Intent • What is intent? – The mechanism for requesting process or exchanging message between components • The components which can use intent are activity, broadcast receiver, service – Intent use cases • Start up activity B from activity A(screen transition) • Request telephone call to the application of calling from Address book application 21 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 22. 2.2. Intent • When component is called by intent, in the intent the calling destination component information will be added and request to Android – Example of calling component B from component A 22 This material is licensed under the Creative Commons License BY-NC-SA 4.0. B is started up
  • 23. 2.2. Intent • Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 23 package jp.oesf.mtgeduwg.training.rssreader; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; public class RssReaderActivity extends Activity implements OnClickListener { ・・・・・・・・ public void onClick(View view) { if (R.id.list_button == view.getId()) { Intent intent = new Intent(this, RssListActivity.class); startActivity(intent); } } } •Generate object of intent •Pass intent
  • 24. 2.3. Service • What is service? – The mechanism for the processing by the independent thread – Service is implemented by the thread different with activity of foreground. Therefore, even the interruption occurs by other activity the processing can be continued 24 This material is licensed under the Creative Commons License BY-NC-SA 4.0. Play music (not use Service) Play music (use Service) The difference in operating when Activity interrupt occurred by receiving mail in case of playing music directly from Activity or through service.
  • 25. 2.3. Service • How to implement service – Create newly service – Register the created service to AndroidManifest.xml – Start the created service by startService method This material is licensed under the Creative Commons License BY-NC-SA 4.0. 25
  • 26. 2.3. Service • How to implement service 1. Create new service class • Create the service class inherited from Service base class • It is necessary to implement abstract onBind method. Binding is not used here, so null is returned Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 26 import android.app.Service; import android.content.Intent; import android.os.IBinder; public class SampleService extends Service { @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } } ・・・1
  • 27. 2.3. Service 2. Implement call back method if needed • There are 3 methods: onCreate, onStart, onDestroy • Recognize life cycle and implement appropriately • onStart will be called each time when starting • The other 2 methods will be called once when creating and destroying object This material is licensed under the Creative Commons License BY-NC-SA 4.0. 27 # Events name Content 1 onCreate The event occurs in the first startup 2 onStart The event occurs just before the Service is started 3 onDestroy The event occurs just before the Service is destroyed
  • 28. 2.3. Service • Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 28 @Override public void onCreate() { super.onCreate(); Log.v(“SampleService", "onCreate"); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Thread t = new Thread() { @Override public void run() { try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { Log.e("RegisterService", e.toString()); } } }; t.start(); } @Override public void onDestroy() { super.onDestroy(); Log.v(“SampleService", "onDestroy"); } ・・・2
  • 29. 2.3. Service 2. Register the created service in AndroidManifest.xml • Creating steps i. Open AndroidManifest.xml and select Application tab ii. Click [Add] button of Application Nodes This material is licensed under the Creative Commons License BY-NC-SA 4.0. 29 i ⅱ
  • 30. 2.3. Service iii. Select Service from the displayed screen, click 「OK」 button ※ In case cursor is in the registered node, the layer will be checked, so please select upon radio button This material is licensed under the Creative Commons License BY-NC-SA 4.0. 30 ⅲ ※
  • 31. 2.3. Service iv. After checking that the added service is selected, input name of class of the service created in [Name] field This material is licensed under the Creative Commons License BY-NC-SA 4.0. 31 ⅳ Clicking Browse button, browsing is convenient
  • 32. 2.3. Service ※ The following will be added to AndroidManifest.xml The class of service becomes registered by this Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 32 ・・・ <application ・・・> ・・・ <service android:name=“SampleService"></service> ・・・ </application> ・・・
  • 33. 2.3. Service 3. Start up the created service by startService method i. Create new intent object by setting to the argument of Intent the calling source object and the class of calling destination service ii. Execute Context#startService. Set Intent object created in i. to argument of method • Sample code (extracted from code of activity) This material is licensed under the Creative Commons License BY-NC-SA 4.0. 33 Intent intent = new Intent(this, SampleService.class); startService(intent); ・・・ⅰ ・・・ⅱ
  • 34. Practice 2.3. Service Practice 1 • Practice theme – In menu screen, create the processing of starting RSS getting method with service when pushing 「menu」 button => 「Get RSS」 button This material is licensed under the Creative Commons License BY-NC-SA 4.0. 34 Screen can be operated as it is Started as service No affect to screen
  • 35. Practice 2.3. Service Practice 1 • Steps: 1. Create new service RegisterService class 2. Get RSS with onStart method of RegisterService 3. Output log of starting/ending to RegisterService#onStart • Tag:「 RegisterService 」 • Message:when starting 「onStart start」 and when ending 「onStart end」 4. Delete logic of RSS getting existed in onOptionsItemSelected method of RssReaderActivity, use Intent to call RegisterService 5. Output log of starting/ending to RssReaderActivity#onOptionsItemSelected • Tag: 「 RssReaderActivity 」 • Message:「onOptionsItemSelected start」 and 「onOptionsItemSelected end」 6. Add setting of RegisterService to AndroidManifest.xml This material is licensed under the Creative Commons License BY-NC-SA 4.0. 35
  • 36. Practice 2.3. Service Practice 1 – Setting information 1 • Execute the following class, method This material is licensed under the Creative Commons License BY-NC-SA 4.0. 36 Target Class Method Outline Service RegisterService • Create newly • Package is jp.oesf.mtgeduwg.training.rssreader onStart • Get RSS • Output starting & ending log Menu screen RssReaderActivity onOptionsItemSelected • Delete the existed RSS getting log • Start RegisterService • Output starting & ending log
  • 37. Practice 2.3. Service Practice 1 – Setting information 2 • Edit the following file This material is licensed under the Creative Commons License BY-NC-SA 4.0. 37 File name Outline AndroidManifest.xml • Register RegisterService as service
  • 38. Practice 2.3. Service Practice 1 • How to check – When pushing 「Get RSS」 button, the following log output will be checked with LogCat • RegisterService#onStart – Starting log 「onStart start 」 – Ending log 「 onStart end」 • RssReaderActivity#onOptionsItemSelected – Starting log 「onOptionsItemSelected start 」 – Ending log 「 onOptionsItemSelected end」 – Close log of RssReaderActivity#onOptionsItemSelected will be checked with the output after close log of RegisterService#onStart This material is licensed under the Creative Commons License BY-NC-SA 4.0. 38
  • 39. Practice 2.3. Service Practice 1 • Answer of Practice – RegisterService This material is licensed under the Creative Commons License BY-NC-SA 4.0. 39 package jp.oesf.mtgeduwg.training.rssreader; import jp.oesf.mtgeduwg.training.rssreader.helper.RssFeedRegister; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class RegisterService extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Log.v("RegisterService", "onStart start"); new RssFeedRegister(this).registration("http://www.oesf.jp/modules/news/index.php?page=rss"); Log.v("RegisterService", "onStart end"); } }
  • 40. Practice 2.3. Service Practice 1 • Answer of Practice – RssReaderActivity (Only the corresponding part extracted) This material is licensed under the Creative Commons License BY-NC-SA 4.0. 40 ・・・ @Override public boolean onOptionsItemSelected(MenuItem item) { Log.v("RssReaderActivity", "onOptionsItemSelected start"); if (item.getItemId() == R.id.main_menu_add) { // new RssFeedRegister(this).registration("http://www.oesf.jp/modules/news/index.php?page=rss"); // new AlertDialog.Builder(this).setTitle(R.string.ok_dialog_label).show(); Intent intent = new Intent(this, RegisterService.class); startService(intent); Log.v("RssReaderActivity", "onOptionsItemSelected end"); return true; } return false; } ・・・
  • 41. Practice 2.3. Service Practice 1 • Answer of Practice – AndroidManifest.xml (Only the corresponding part extracted) This material is licensed under the Creative Commons License BY-NC-SA 4.0. 41 ・・・ <application> ・・・ <service android:name="RegisterService"></service> ・・・ </application> ・・・
  • 42. Practice 2.3. Service Practice 1[Supplement] • Practice theme – Use toast to notify that service processing is completed This material is licensed under the Creative Commons License BY-NC-SA 4.0. 42 Screen will be operated as it is Service logic Toast will be explained from the next page
  • 43. Practice 2.3. Service • What is toast? – The function to display message on screen for a short time – This is the function for displaying message only and can not operate combining with cursor – It is convenient if you use the component without UI such as service This material is licensed under the Creative Commons License BY-NC-SA 4.0. 43
  • 44. Practice 2.3. Service • Execute toast – Use 1 of the 2 methods as below: public static Toast makeText (Context context, CharSequence text, int duration) public static Toast makeText (Context context, int resId, int duration) + context: context + text: the displayed text resId: the resource ID of the displayed text + duration: Toast.LENGTH_SHORT (short time) or Toast.LENGTH_LONG(long time) – For the return value of the above methods, it is displayed that Toast#show method is implemented Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 44 Toast.makeText(this, “TEST", Toast.LENGTH_SHORT).show(); Toast.makeText(this, R.string.test, Toast.LENGTH_LONG).show();
  • 45. Practice 2.3. Service Practice 1[Supplement] 1. When service logic is completed, try to display the favorite message with toast 2. Change duration and check if the display time is changed or not 3. Try to use all makeText methods with the different 2nd argument This material is licensed under the Creative Commons License BY-NC-SA 4.0. 45
  • 46. 2.4. Broadcast receiver • What is broadcast receiver? – Broadcast receiver is the mechanism to response the broadcasted intent – Can inherit broadcast receiver class to create the original broadcast receiver 46 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 47. 2.4. Broadcast receiver • Use cases of broadcast receiver – Check mail when starting Android device 1. Receive broadcast intent when starting Android device completed with broadcast receiver ※ Describe IntentFilter in AndroidManifest.xml about receiving which broadcast intent 2. Call mail checking service from broadcast receiver ※ It is possible to check mail directly from broadcast receiver, but in case of long time processing it is better to use service 47 This material is licensed under the Creative Commons License BY-NC-SA 4.0. Broadcast receiver Send broadcast intent Send intent ② Execute mail checking service Intent ① Starting completed message Intent Mail checking service
  • 48. 2.4. Broadcast receiver • How to implement service – Create newly broadcast receiver class – Register the created broadcast receiver to AndroidManifest.xml This material is licensed under the Creative Commons License BY-NC-SA 4.0. 48
  • 49. 2.4. Broadcast receiver • How to implement broadcast receiver 1. Create newly broadcast receiver class • Create the class inherited from BroadcastReceiver base class • It is necessary to implement abstract onReceive method • Implement actual process which you want in onReceive method • Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 49 import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class SampleStarter extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent serviceIntent = new Intent(context, SampleService.class); context.startService(serviceIntent); } } ・・・1
  • 50. 2.4. Broadcast receiver ※ In case you want to divide the processing according to the receiving intent, check if which intent will be received by checking action caused by Intent#getAction, and describe the divided processing Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 50 import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class SampleStarter extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){ Intent serviceIntent = new Intent(context, SampleService.class); context.startService(serviceIntent); } } } ・・・※
  • 51. 2.4. Broadcast receiver 2. Register the created broadcast receiver to AndroidManifest.xml • Steps i. Open AndroidManifest.xml, select Application tab ii. Click [Add] button of Application Nodes This material is licensed under the Creative Commons License BY-NC-SA 4.0. 51 ⅰ ⅱ
  • 52. 2.4. Broadcast receiver iii. Select Receiver from the displayed screen and click 「OK」 button This material is licensed under the Creative Commons License BY-NC-SA 4.0. 52 ⅲ
  • 53. 2.4. Broadcast receiver iv. After checking if the added receiver is selected or not, input the name of the created broadcast receiver into Name field This material is licensed under the Creative Commons License BY-NC-SA 4.0. 53 ⅳ It is convenient if you click Browse button
  • 54. 2.4. Broadcast receiver v. After checking if the added receiver is selected or not, click 「Add」 button This material is licensed under the Creative Commons License BY-NC-SA 4.0. 54 ⅴ
  • 55. 2.4. Broadcast receiver vi. After checking if the lower radio button is selected on the displayed screen or not, select Intent Filter and click 「OK」 button This material is licensed under the Creative Commons License BY-NC-SA 4.0. 55 ⅵ
  • 56. 2.4. Broadcast receiver vii. After checking if the added Intent Filter is selected or not, click 「Add 」 button This material is licensed under the Creative Commons License BY-NC-SA 4.0. 56 ⅶ
  • 57. 2.4. Broadcast receiver viii. After checking if the lower radio button is selected on the displayed screen or not, select Intent Filter and click 「OK」 button This material is licensed under the Creative Commons License BY-NC-SA 4.0. 57 Ⅷ
  • 58. 2.4. Broadcast receiver ix. After checking if the added receiver is selected or not, input name of class of the created service into Name field This material is licensed under the Creative Commons License BY-NC-SA 4.0. 58 Can select by pull down ⅸ
  • 59. 2.4. Broadcast receiver ※ It is added to AndroidManifest.xml as below: In the following, broadcast intent of android.intent.action.BOOT_COMPLETED is captured and the service class – SampleServiceStart is started up Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 59 ・・・ <application ・・・> ・・・ <receiver android:name=“SampleServiceStarter"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"></action> </intent-filter> </receiver> ・・・ </application> ・・・
  • 60. Practice 2.4. Broadcast receiver Practice 2 • Practice theme – When system finished starting, create the starting processing for RSS getting method with service This material is licensed under the Creative Commons License BY-NC-SA 4.0. 60 System finished starting Start as service No impact to screen
  • 61. Practice 2.4. Broadcast receiver Practice 2 • Steps 1. Create newly RegisterServiceStarter class which is the broadcast receiver 2. Call RegisterService with onReceive method of RegisterServiceStarter#onReceive 3. Add setting of RegisterServiceStarter to AndroidManifest.xml • Register RegisterServiceStarter as broadcast receiver • As setting of Intent Filter of RegisterServiceStarter, set android.intent.action.BOOT_COMPLETED(starting completed) to Action This material is licensed under the Creative Commons License BY-NC-SA 4.0. 61
  • 62. Practice 2.4. Broadcast receiver Practice 2 – Setting information • Execute the following class, method This material is licensed under the Creative Commons License BY-NC-SA 4.0. 62 Target Class Method Outline Broadcast receiver RegisterServiceStart er • Create newly • Package is jp.oesf.mtgeduwg.training.rssreader onReceive • Start up RegisterService
  • 63. Practice 2.4. Broadcast receiver Practice 2 – Setting information 2 • Edit the following file This material is licensed under the Creative Commons License BY-NC-SA 4.0. 63 File name Outline AndroidManifest.x ml • Register RegisterServiceStarter as service • As setting of Intent Filter, set android.intent.action.BOOT_COMPLETED (starting completed) to Android
  • 64. Practice 2.4. Broadcast receiver Practice 2 • How to check – After starting application once, close emulator once, and re-start. Check if the log at that time output or not • RegisterService#onStart – Starting log 「onStart start 」 – Ending log 「 onStart end」 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 64
  • 65. Practice 2.4. Broadcast receiver Practice 2 • Answer of Practice – RegisterServiceStarter This material is licensed under the Creative Commons License BY-NC-SA 4.0. 65 package jp.oesf.mtgeduwg.training.rssreader; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class RegisterServiceStarter extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){ Intent serviceIntent = new Intent(context, RegisterService.class); context.startService(serviceIntent); } } } ※This case only 1 intent will come, so it is ok with non-if statement
  • 66. Practice 2.4. Broadcast receiver Practice 2 • Answer of Practice – AndroidManifest.xml (Only the corresponding part extracted) This material is licensed under the Creative Commons License BY-NC-SA 4.0. 66 ・・・ <application> ・・・ <receiver android:name="RegisterServiceStarter"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"></action> </intent-filter> </receiver> ・・・ </application>
  • 67. Practice 2.4. Broadcast receiver Practice 2[Supplement] 1. Check code of SendBroadcast project, check if the broadcast of the given action will be thrown or not when pushing button of this application. 2. For that action, modify the file of RssReader project in order to start RegisterServiceStarter 3. After starting RssReader, check with log if service of RssReader started or not when starting SendBroadcast and pushing button This material is licensed under the Creative Commons License BY-NC-SA 4.0. 67
  • 68. 2.5. Content provider • What is content provider? – The mechanism which can access (search, add, update, delete the data kept by application※ from other application – Detailed example: • Refer the telephone call log from application • Add Website from application to bookmark of browser • Refer the address book from application • Refer calendar from application ※Data is the information shown by application in file, database permanently 68 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 69. 2.5 Content provider • Content provider will decide interface in order to execute the safe accessing – Main interface 69 Content provider query insert update delete External application Interface is decided# Event name Content 1 Search (query) Search data, return searching result 2 Add (insert) Add data 3 Update (update) Update data 4 Delete (delete) Delete data This material is licensed under the Creative Commons License BY-NC-SA 4.0. ■Refer to development guide for Android Developers http://developer.android.com/intl/ja/reference/android/content/ContentProvider.html
  • 70. 2.5 Content provider • How to implement content provider – Create newly class of content provider – Implement the abstract method of content provider if needed – Register the created content provider to AndroidManifest.xml This material is licensed under the Creative Commons License BY-NC-SA 4.0. 70
  • 71. 2.5 Content provider • How to implement content provider 1. Create new content provider class • Create the content provider class inherited from ContentProvider base class • The following 6 methods are defined as the abstract methods of ContentProvider class, so all methods are supposed to be implemented This material is licensed under the Creative Commons License BY-NC-SA 4.0. 71 Method Return value type Outline onCreate boolean • Run when starting content provider • When provider initialization is stopped abnormally, true will be returned getType String • Return the handling text string in MIME type query cursor • Search • Return result as Cursor object Insert int • Insert • Return the inserted number update int • Update • Return the updated number delete int • Delete • Return the deleted number
  • 72. 2.5 Content provider This material is licensed under the Creative Commons License BY-NC-SA 4.0. 72 import android.content.ContentProvider; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; public class SampleProvider extends ContentProvider { @Override public int delete(Uri uri, String selection, String[] selectionArgs) { return 0; } @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri, ContentValues values) { return null; } ・Sample code
  • 73. 2.5 Content provider This material is licensed under the Creative Commons License BY-NC-SA 4.0. 73 @Override public boolean onCreate() { return false; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { return null; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; } } ・Sample code (continue)
  • 74. 2.5 Content provider 2. Implement the abstract method of content provider if needed i. Generate object of normal SQLiteOpenHelper with onCreate and save as instance variable The context specified to argument of constructor will use getContext method ii. With 4 methods operate database, get object of SQLiteDatabase from SQLiteOpenHelper object Use the gotten SQLiteDatabase object to operate for database ※ SQLiteDatabase object can be got by the one who implement with onCreate also. iii. onType is the method of returning MIME type, and in case of dividing type with the specified URI, it will be implemented as a means to inform that type to user In not complicated case, it is OK with usual-unused (return null;) This material is licensed under the Creative Commons License BY-NC-SA 4.0. 74
  • 75. 2.5 Content provider • Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 75 ・・・ private SampleSqliteOpenHelper sqliteOpenHelper; private SQLiteDatabase db; @Override public boolean onCreate() { sqliteOpenHelper = new DatabaseOpenHelper(getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { db = sqliteOpenHelper.getReadableDatabase(); return db.query("RSS_FEED", projection, selection, selectionArgs, null, null, sortOrder); } ・・・ ・・・1 ・・・2
  • 76. 2.5 Content provider 3. Register the created content provider to AndroidManifest.xml • Steps i. Open AndroidManifest.xml and select Application tab ii. Click [Add] button of Application Nodes This material is licensed under the Creative Commons License BY-NC-SA 4.0. 76 i ⅱ
  • 77. 2.5 Content provider iii. Select Provider from the displayed screen, click 「OK」 button ※ In case cursor is in the registered node, the layer will be checked, so please select upon radio button This material is licensed under the Creative Commons License BY-NC-SA 4.0. 77 ⅲ ※
  • 78. 2.5 Content provider iv. After checking that the added Provider is selected, input name of class of the Provider created in [Name] field This material is licensed under the Creative Commons License BY-NC-SA 4.0. 78 ⅳ It is convenient to browse if clicking Browse button
  • 79. 2.5 Content provider v. Scroll down Attribute for Provider, specify the unique content provider name to Authorities tag Normally it is the same with package name This material is licensed under the Creative Commons License BY-NC-SA 4.0. 79 ⅴ
  • 80. 2.5 Content provider ※ It is added to AndroidManifest.xml as below: By doing this, it could be registered as class of content provider Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 80 ・・・ <application ・・・> ・・・ <provider android:authorities="jp.oesf.sample.sampleprovider“ android:name=“SampleProvider"> </provider> ・・・ </application> ・・・
  • 81. 2.5 Content provider 3. The created content provider will use ContentResolver object i. Pass URI for accessing to content provider to parse method of Uri object to generate Uri object The specified URI is content:// the value of Authorities of content provider ii. Use Context#getContentResolver method to get ContentResolver object In ContentResolver, query, Insert, update, delete, getType methods are prepared in the same form with ContentProvider • Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 81 Uri uri = Uri.parse("content:// jp.oesf.sample.sampleprovider”); Cursor cursor = getContentResolver().query(uri, null, null, null, null); ・・・ⅰ ・・・ⅱ
  • 82. 2.5 Content provider • Reference – In case of diverging the processing according to value of URI (for example: specifying table name, simple authentication), it is necessary to check URI with logic At that time, it is better to use android.content.UriMatcher class This material is licensed under the Creative Commons License BY-NC-SA 4.0. 82 import android.content.UriMatcher; private static final UriMatcher uriMatcher; static{ uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);uriMatcher.addURI("jp.oesf.mtgeduwg.traini ng.rssreader", "FOO", 1); uriMatcher.addURI("jp.oesf.mtgeduwg.training.rssreader", “FOO/#", 2); } Inside method switch(uriMatcher.match(uri)){ case 1: ・・・ case 2: ・・・ default: ・・・ Sample code
  • 83. Practice 2.5 Content provider Practice 3 • Practice theme – Create content provider in RssReader, make it is possible to search information of RSS_FEED table from external application. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 83 Click button
  • 84. Practice 2.5 Content provider Practice 3 • Practicing steps 1. Create newly RssProvider which is content provider 2. With onCreate of RssProvider, get SQLiteOpenHelper object 3. With query method of RssProvider, get SQLiteDatabase object with SQLiteOpenHelper#getReadableDatabase method 4. With query method of RssProvider, call SQLiteDatabase#query, return the recorded Cursor 5. Add setting of RssProvider to AndroidManifest.xml 6. Check Main# onClickGetList method of TestContentProvider project (It is implemented already so check only) This material is licensed under the Creative Commons License BY-NC-SA 4.0. 84
  • 85. Practice 2.5 Content provider Practice 3 – Setting information 1 • Execute the following class, method This material is licensed under the Creative Commons License BY-NC-SA 4.0. 85 Target Class Method Outline Content Provider RssProvider • Create newly • Package is jp.oesf.mtgeduwg.training.rssreader onCreate • Get SQLiteOpenHelper object query • Search the condition of argument as it is from RSS_FEED table, and return that result
  • 86. Practice 2.5 Content provider Practice 3 – Setting information 2 • Edit the following file This material is licensed under the Creative Commons License BY-NC-SA 4.0. 86 File name Outline AndroidManifest.xml • Register RssProvider as content provider • Set jp.oesf.mtgeduwg.training.rssreader to android:authorities
  • 87. Practice 2.5 Content provider Practice 3 • How to check – When launching TestContentProvider application, and pushing 「GET LIST」 button, get the value from database via content provider and make it display list on screen This material is licensed under the Creative Commons License BY-NC-SA 4.0. 87 Click button
  • 88. Practice 2.5 Content provider Practice 3 • Answer of Practice – RssProvider.java This material is licensed under the Creative Commons License BY-NC-SA 4.0. 88 package jp.oesf.mtgeduwg.training.rssreader; import jp.oesf.mtgeduwg.training.rssreader.helper.DatabaseOpenHelper; import android.content.ContentProvider; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; public class RssProvider extends ContentProvider { private DatabaseOpenHelper databaseOpenHelper; private SQLiteDatabase db;
  • 89. Practice 2.5 Content provider Practice 3 • Answer of Practice – RssProvider (continue) This material is licensed under the Creative Commons License BY-NC-SA 4.0. 89 @Override public boolean onCreate() { databaseOpenHelper = new DatabaseOpenHelper(getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { db = databaseOpenHelper.getReadableDatabase(); return db.query("RSS_FEED", projection, selection, selectionArgs, null, null, sortOrder); } ・・・
  • 90. Practice 2.5 Content provider Practice 3 • Answer of Practice – AndroidManifest.xml This material is licensed under the Creative Commons License BY-NC-SA 4.0. 90 ・・・ <application> ・・・ <provider android:authorities="jp.oesf.mtgeduwg.training.rssreader" android:name="RssProvider"></provider> ・・・ </application> ・・・
  • 91. Practice 2.5 Content provider Practice 3[Supplement] • Practice theme – Try to implement as below: • Make it specifies with URI, not writing without spaces in code content://jp.oesf.mtgeduwg.training.rssreader/RSS_FEED This material is licensed under the Creative Commons License BY-NC-SA 4.0. 91 There is no answer, please refer to sample
  • 92. 3. Practical development 92 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 93. Chapter 3 - Outline • Notification • Support multi-resolution • Support multi-language • adb tool 93 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 94. 3.1. Notification • What is notification? – The function to display information in a given time on status bar of the upper part of screen – When opening status bar, the list screen of notification will be displayed, and then it is possible to start up activity 94 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 95. 3.1. Notification • How to implement notification – Get NotificationManager class which handles notification – Generate Notification object – Generate the pending intent which started when notification list is clicked – Set event information in Notification object – Display notification This material is licensed under the Creative Commons License BY-NC-SA 4.0. 95
  • 96. 3.1. Notification • How to implement notification 1. Get NotificationManager class which handles notification – Can get NotificationManager by invoking Context#getSystemService – Specify constant of Context.NOTIFICATION_SERVICE to argument of the above method – Return value is Object type so typecast in NotificationManager type Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 96 import android.app.NotificationManager; import android.content.Context; ・・・ NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); ・・・1
  • 97. 3.1. Notification 2. Generate Notification object • Call constructor and generate object • Specify resource ID of icon, message displayed on status bar in argument of constructor, and time (milliseconds) displayed in list Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 97 import android.app.Notification; ・・・ Notification notification = new Notification(R.drawable.icon,“Could get RSS", System.currentTimeMillis()); ・・・2
  • 98. 3.1. Notification 3. Generate the pending intent which started when notification list is clicked • Generate PendingIntent by getActivity method (static method) of PendingIntent • There are 4 arguments of getActivity, so specify context, request code (now it is unused, so it is usually 0), intent, flag (it is 0 in case of not used ) Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 98 import android.app.PendingIntent; import android.content.Intent; ・・・ PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,RssListActivity.class), 0); About flag: PendingIntent.FLAG_UPDATE_CURRENT,… Refer to: http://developer.android.com/reference/android/app/PendingIntent.html ・・・3
  • 99. 3.1. Notification 4. Set event information in Notification object • Set event information with Notification#setLatestEventInfo • There are 4 arguments of setLatestEventInfo, so specify context, title, ticker text, pending intent Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 99 notification.setLatestEventInfo(this, "RssReader", “RSS got", pendingIntent); ・・・4
  • 100. 3.1. Notification 5. Display notification • Display notification actually with NotificationManager#notify • There are 2 arguments of notifying, so specify id(the number unified with that notification inside application), Notification object Sample code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 100 nm.notify(0,notification); ・・・5
  • 101. 3.1. Notification The sample code until 1-5 are summarized and shown as below: This material is licensed under the Creative Commons License BY-NC-SA 4.0. 101 import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; ・・・ NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.icon,“Could get RSS", System.currentTimeMillis()); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,RssListActivity.class), 0); notification.setLatestEventInfo(this, "RssReader", “RSS got", pendingIntent); nm.notify(0,notification); ・・・
  • 102. Practice 3.1. Notification Practice 4 • Practice theme – Use notification to create the processing to notify the ending when logic of getting RSS with service is ended – Click to the applicable notification on screen of notification list, it will transit to list screen (RssListActivity) This material is licensed under the Creative Commons License BY-NC-SA 4.0. 102 Logic ended Start as service Click
  • 103. Practice 3.1. Notification Practice 4 • Practicing steps 1. Execute the following steps after logic of getting RSS of RegisterService#onStart i. Get NotificationManager ii. Generate Notification object iii. Generate PendingIntent like transiting to list screen(RssListActivity) iv. Set event information to Notification object v. Display notification This material is licensed under the Creative Commons License BY-NC-SA 4.0. 103
  • 104. Practice 3.1. Notification Practice 4 – Setting information 1 • Execute the following class, method This material is licensed under the Creative Commons License BY-NC-SA 4.0. 104 Target Class Method Outline Get RSS RegisterService onStart • Display notification • Flag of PendingIntent is 0 Supplemental notes In case of specifying text string to display by strings.xml without describing directly to Java, CharSequence will be required as argument in Java, so it is OK if using Context#getText(int resId) Eg: getText(R.string.app_name)
  • 105. Practice 3.1. Notification Practice 4 – Setting information 2 • It should be displayed as below: This material is licensed under the Creative Commons License BY-NC-SA 4.0. 105 Display image of R.drawable.icon Display 「could get RSS」 Display 「RSS getting completed」 Display 「RssReader」 Display time at displaying timing
  • 106. Practice 3.1. Notification Practice 4 • How to check – When getting RSS by pushing 「Get RSS」 button…, the following notification will be displayed – Tap to the applicable notification from list of notification, it will transit to list screen of RSS reader This material is licensed under the Creative Commons License BY-NC-SA 4.0. 106 Click
  • 107. Practice 3.1. Notification Practice 4 • Practice answers – RegisterService This material is licensed under the Creative Commons License BY-NC-SA 4.0. 107 import jp.oesf.mtgeduwg.training.rssreader.helper.RssFeedRegister; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; ・・・ @Override public void onStart(Intent intent, int startId) { ・・・ NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.icon,getText(R.string.notification_ticker_text), System.currentTimeMillis()); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,RssListActivity.class), 0); notification.setLatestEventInfo(this, getText(R.string.notification_title), getText(R.string.notification_text), pendingIntent); nm.notify(0,notification); ・・・
  • 108. Practice 3.1. Notification Practice 4 • Answer of Practice – strings.xml This material is licensed under the Creative Commons License BY-NC-SA 4.0. 108 ・・・ <resources> ・・・ <string name="notification_title">RssReader</string> <string name="notification_ticker_text">Could not get RSS</string> <string name="notification_text">RSS getting finished</string> ・・・ </resources> ※ In answer example, the displaying text is defined in resource file of text string The correct answer is the value of String written directly to code of Java Or key name of resource(notification_title…)
  • 109. Practice 3.1. Notification Practice 4[Supplement] • Practice theme – Delete notification when transiting to list screen This material is licensed under the Creative Commons License BY-NC-SA 4.0. 109 There is no answer example Please refer to sample
  • 110. 3.2. Support multi-resolution • Support multi-resolution – Android support multi-resolution officially from version 1.6 – In case the version installed to Android terminal is unknown, if the application doesn’t support multi-resolution, it may display incorrectly – It is necessary to know how one Android application can support multi-resolution 110 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 111. 3.2. Support multi-resolution • Density and screen server • DIP (Density Independent Pixel) • Scaling • Multi-resolution-supported Tips This material is licensed under the Creative Commons License BY-NC-SA 4.0. 111
  • 112. 3.2. Support multi-resolution • Density and screen size – In Android, devices are categorized according to Density and screen size – Density is divided according to value of DPI (Dots Per Inch/ Number of dots per inch) to 3 types as below – According to 3 types, the directory of the photo file to be called will be divided and it is possible to display the photo suitable to that Density. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 112 Density DPI range Deemed DPI value Supported photo file directory Low-Density 100dpi-140dpi 120dpi res/drawable-ldpi Medium-Density 140dpi-180dpi 160dpi res/drawable-mdpi High-Density 190dpi-250dpi 240dpi res/drawable-hdpi ※ Deemed DPI value Eg: In Low-Density device, all DPI are 120dpi
  • 113. 3.2. Support multi-resolution – Screen sizes are divided into 3 types according size of screen – By dividing the layout directory to be called according to 3 types, the layout suitable to that screen size can be called out. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 113 Name Screen size Supported layout file directory Small Screen - 3.0 inch res/layout-small Normal Screen 3.0 inch – 4.0 inch res/layout Large Screen 4.0 inch- res/layout-large Low-Density Medium-Density High-Density Small Screen QVGA (240x320), 2.6"-3.0" inch Normal Screen WQVGA (240x400), 3.2"-3.5" inch FWQVGA (240x432), 3.5"-3.8" inch HVGA (320x480), 3.0"-3.5" inch WVGA (480x800), 3.3"-4.0" inch FWVGA (480x854), 3.5"-4.0" inch Large Screen WVGA (480x800), 4.8"-5.5" inch FWVGA (480x854), 5.0"-5.8" inch – The following table is the result of summarizing 2 types Refer to: http://developer.android.com/intl/ja/guide/topics/resources/providing-resources.html#AlternativeResources
  • 114. 3.2. Support multi-resolution • DIP (Density Independent Pixel) – When specifying size directly, normally Pixel/px is used, but in case of pixel the UI will be not intended by Density – In Android the concept of DIP(Density Independent Pixel) _ the virtual pixel unit is introduced, and it can be supported for that. – Unit of DIP is described as dip or dp, but dp is suggested. – It is calculated with the formula: pixels = dips * (density / 160) It means with 160dpi= Medium-Density, 1px=1dp – Scale-independent Pixels (sp) is a concept like DIP, but it is the value added by not only Density but also font size of user. But currently in Android, there is no 「User font size setting」, so it is 1dp=1sp – [Supplement] In all methods of Java prepared in Android, only pixel can be used. Therefore, it is necessary to convert with the above formula in code of Java This material is licensed under the Creative Commons License BY-NC-SA 4.0. 114
  • 115. 3.2. Support multi-resolution • Scaling – 3 directories to be called according to Photo file Density are prepared, but sometimes only res/drawable not all of them are prepared. – In the above case, Scale Density of Medium-Density will be 1, and the scaling function to enlarge/reduce the size of photo according to Density will be prepared. – If the photo which no need to scale is stored in res/drawable-nodpi, it will be displayed with that resolution as it is without scaling. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 115 Density Scale Density High-Density 1.5 Medium-Density 1 Low-Density 0.75 Scale Density
  • 116. 3.2. Support multi-resolution • Multi-resolution-supported Tips – Use wrap_content or fill_parent (match_parent from 2.2) to specify size of width/height of layout In case it is necessary to specify numeric value, use dp not px – Photo file is prepared suitable with Density – Recognize the different of screen size in order not to fill over in horizontal direction In case of filling by force, prepare layout file for Small Screen separately – Convert the pixel value in Java code to DIP which do not hard code This material is licensed under the Creative Commons License BY-NC-SA 4.0. 116
  • 117. 3.2. Support multi-resolution • Multi-resolution-supported Tips (continue) – When the screen not supported is set in the 3 types of screen size, it is no problem if describing the setting of supports-screens of AndroidManifest.xml Sample of AndroidManifest.xml (Not support Small Screen) This material is licensed under the Creative Commons License BY-NC-SA 4.0. 117 ・・・ <application> ・・・ <supports-screens android:largeScreens=“true”> android:normalScreens=“true”> android:smallScreens=“false” /> ・・・ </application> ・・・
  • 118. Practice 3.2. Support multi-resolution Practice 5 • Practice theme – Run the application of Multi Resolution project on each emulator which is different in screen size and Density, and check that screen and source. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 118 ldpi mdpi hdpi
  • 119. Practice 3.2. Support multi-resolution Practice 5 • Checking point of practice – Check in Small-Screen if buttons are 2-stage group or not => res/layout-small/main.xml is read – Check if R.drawable.droid is displayed by other photo prepared for each resolution or not => res/drawable-Xdpi/droid.jpg is displayed – Check if R.drawable.droid_nodpi is displayed by one photo without scaling or not => res/drawable-nodpi/droid_nodpi.jpg is displayed This material is licensed under the Creative Commons License BY-NC-SA 4.0. 119
  • 120. Practice 3.2. Support multi-resolution • Checking point of practice (continue) – Check if R.drawable.droid_scaling is scaled and displayed with enlarged/reduced size combining with resolution or not => res/drawable/droid_scaling.jpg is scaled and displayed – The displayed text is specified as px for the upper one, dp for the lower, so that check if the lower text ‘s size is changed combining with the resolution or not. => res/layout/main.xml is read – The margin of photo is dp specified, so check if the size is changed combining with resolution or not. => res/layout/main.xml is read This material is licensed under the Creative Commons License BY-NC-SA 4.0. 120
  • 121. Practice 3.2. Support multi-resolution This material is licensed under the Creative Commons License BY-NC-SA 4.0. 121 R.drawable.droid Different photo is prepared for each Density R.drawable.droid_nodpi All are displayed with the same resolution without scaling R.drawable.droid_scaling scaled to be displayed In Small-Screen buttons are divided into 2 stage to be displayed Upper is px specified Lower is dp specified Lower will be changed according to resolution Margin of photo is dp specified
  • 122. Practice 3.2. Support multi-resolution Practice 5 • Practice steps 1. The following 3 emulators are prepared, so start up that, launch application Multi Resolution project and check the displayed screen and source This material is licensed under the Creative Commons License BY-NC-SA 4.0. 122 Emulator name Screen size and Density QVGA-small-ldpi Small Screen, Low-Density HVGA-normal-mdpi Normal Screen, Medium-Density WVGA-normal-hdpi Normal Screen, High-Density
  • 123. Practice 3.2. Support multi-resolution Practice 5 • How to check – Check the checking point of practice This material is licensed under the Creative Commons License BY-NC-SA 4.0. 123
  • 124. 3.3. Support multi-language • Support multi-language – Android application would be used in many countries on the world, so it should support multi-language. – If the text string is described in Android as resource file in advance, the mechanism to support multi-language will be prepared simply. – Combining with language setting in device, the resource file under directory of res/values-[language code] or res/values-[language code]- r[region code] can be read – In case device has no directory for language setting, it will be read under res/values 124 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 125. 3.3. Support multi-language • In case of English(Australia): values-en- rAU • In case of English (not Australia: values-en • In case of Japanese: values-ja • In the cases other than above: values will be read This material is licensed under the Creative Commons License BY-NC-SA 4.0. 125 Example Specify language code ISO 639-1 form http://www.loc.gov/standards/iso639-2/php/code_list.php Specify region code ISO 3166-1-alpha-2 form http://www.iso.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_elements.htm
  • 126. Practice 3.3. Support multi-language Practice 6 • Practice theme – When changing language setting of emulator, check if the text string resource file called corresponded to that is changed or not This material is licensed under the Creative Commons License BY-NC-SA 4.0. 126
  • 127. Practice 3.3. Support multi-language Practice 6 • Practice steps 1. Create res/values-en, res/values-en-rAU, res/values-ja 2. Copy res/values/strings.xml to the created 3 directories 3. Change strings.xml/go_to_list_page_button_label key value of each strings.xml as below: 4. Start up emulator, check if the display of changing language setting is changed or not This material is licensed under the Creative Commons License BY-NC-SA 4.0. 127 Target Key Value res/values/strings.xml go_to_list_page_button_label List displaying (Default) res/values-en/strings.xml go_to_list_page_button_label List displaying (English) res/values-en-rAU/strings.xml go_to_list_page_button_label List displaying (Australia) res/values-ja/strings.xml go_to_list_page_button_label List displaying (Japan)
  • 128. Practice 3.3. Support multi-language Practice 6 • How to check – Launch RssReader on emulator Change language setting and check if the displaying text of button in menu screen is changed or not This material is licensed under the Creative Commons License BY-NC-SA 4.0. 128 Language Displaying text string Value Japan go_to_list_page_button_label List displaying (Japan) English(Australia) go_to_list_page_button_label List displaying (Australia) English ※not Australia go_to_list_page_button_label List displaying (English) All above go_to_list_page_button_label List displaying (Default)
  • 129. Practice 3.3. Support multi-language Practice 6 • How to set up language i. In Home screen, 「menu」 button =>Push 「Setting」 ii. In Setting screen, push 「Language & Keyboard」 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 129 ⅰ ⅱ
  • 130. Practice 3.3. Support multi-language iii. On Language & Keyboard setting screen, push 「Select language」 iv. Push target language on Locale screen This material is licensed under the Creative Commons License BY-NC-SA 4.0. 130 ⅲ ⅳ
  • 131. Practice 3.3. Support multi-language Practice 6 • Answer of Practice (only the applicable part) – res/values/strings.xml – res/values-en/strings.xml – res/values-en-rAU/strings.xml – res/values-ja/strings.xml This material is licensed under the Creative Commons License BY-NC-SA 4.0. 131 <string name=“go_to_list_page_button_label”>List displaying (Default)</string> <string name=“go_to_list_page_button_label”>List displaying (English)</string> <string name=“go_to_list_page_button_label”>List displaying (Australia)</string> <string name="go_to_list_page_button_label">List displaying (Japan)</string>
  • 132. 3.4.adb tool • What is adb tool? – This is the tool to manage the status of device of emulator which belong to SDK – Input command by command prompt to use – In case of passing path in <SDK_ROOT>/tools, recognize adb command in every directory 132 This material is licensed under the Creative Commons License BY-NC-SA 4.0.
  • 133. Practice 3.4.adb tool Practice 7 • Practice theme – Operate actually what described in explanation to learn how to use adb tool 1. adb -help Help of adb tool is displayed This material is licensed under the Creative Commons License BY-NC-SA 4.0. 133
  • 134. Practice 3.4.adb tool Practice 7 2. adb devices Display the list of the running emulator and real device 3. adb uninstall <Package name> Uninstall the application applicable to package name 4. adb install <apk path> Install application This material is licensed under the Creative Commons License BY-NC-SA 4.0. 134
  • 135. Practice 3.4.adb tool Practice 7 5. adb push <local path> <remote path> Copy <remote path> of <local path> 6. adb pull <Remote path> <local path> Copy <remote path> file to <local path> 7. adb shell Connect with Terminal(emulator) and launch shell This material is licensed under the Creative Commons License BY-NC-SA 4.0. 135
  • 136. Practice 3.4.adb tool Practice 7 (Shell operation is as below:) 8. cd <direct path> Direct to current directory 9. ls Display information of file or directory 10.rm <Target file path> Delete file This material is licensed under the Creative Commons License BY-NC-SA 4.0. 136
  • 137. Practice 3.4.adb tool Practice 7 (sqlite3 command is as below:) 11.sqlite3 <Database file path> Direct to current directory 12. .help Display Help 13..dump Display dump file This material is licensed under the Creative Commons License BY-NC-SA 4.0. 137
  • 138. Practice 3.4.adb tool Practice 7 11..schema Display CREATE sentence 12. <SQL sentence>; Issue SQL sentence 13..exit Exit sqlite3 command This material is licensed under the Creative Commons License BY-NC-SA 4.0. 138
  • 139. 3.5.JUnit • What is JUnit? – It is the testing framework to carry out unit test of Java program – It can create test code for confirming the behavior of the created program runs as expected or not, and carry out verification by executing test code – Testing is made to a program, and can be executed many times mechanically, so it is helpful for securing quality 139 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 139
  • 140. 3.5.JUnit • What is JUnit for Android? – In Android, the JUnit is customized from JUnit3 – It is able to issue user’s screen operation and event( onCreate, etc) of Life cycle => It reaches beyond unit test partially to able to use in scenario test – Normal JUnit will run in Java VM on development machine, but Android JUnit runner implements testing by installing and running testing application on Emulator and real machine. 140 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 140
  • 141. 3.5.JUnit • Structure of JUnit base class – It is necessary to make test class extended from junit.framework.TestCase base class – In Android, the class inherited from TestCase class above is prepared after matching to test target – It is up to purpose for using this inherited class 141 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 141
  • 142. 3.5.JUnit – The relation of TestCase class and class for testing being provided by Android junit.framework.TestCase InstrumentationTestCase ActivityTestCase ActivityInstrumentationTestCase2 ActivityUnitTestCase SingleLaunchActivityTestCase AndroidTestCase ServiceTestCase ProviderTestCase2 ApplicationTestCase 142 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 142
  • 143. 3.5.JUnit – Outline of each basis class • ActivityInstrumentationTestCase2 – Screen operation such as push button is possible • ActivityUnitTestCase – It is possible to execute event( such as onCrete) on Life cycle of Activity • ServiceTestCase – It is possible to execute service • ProviderTestCase2 – It is possible to execute Content Provider • ApplicationTestCase – It is possible to use it in testing application 143 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 143
  • 144. 3.5.JUnit • JUnit real code sample – At first, general JUnit code without relation with Android 144 public class Foo { public int add(int x, int y){ return x + y; } } • Code of test target Method that returns after adding 2 arguments This material is licensed under the Creative Commons License BY-NC-SA 4.0. 144
  • 145. 3.5.JUnit • Test code 145 import junit.framework.TestCase; public class FooTest extends TestCase { private Foo foo = null; protected void setUp() throws Exception { super.setUp(); foo = new Foo(); } protected void tearDown() throws Exception { super.tearDown(); } public void testAdd(){ int actual = foo.add(4, 5); assertEquals(9, actual); } } ・・・1 ・・・2 ・・・3 ・・・4 ・・・5 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 145
  • 146. 3.5.JUnit 1. Inherit junit.framework.TestCase, and create class Class name is usually 「Class name of test target」 + “Test” 2. setUp method is executed before test is started Prepare testing( arrange data, generate object, etc.) by this method 3. tearDown method is run when testing finishes Clean-up( such as restore data) by this method after test 4. Method name of test method is testXXX, and assumed no argument with public void 5. assertEquals method is to confirm the behavior of Test target code is correct or not. By setting the acquired value according to expectation value in the first argument, and actual testing in the second argument, if both are right, testing passed, if not it is error Besides, there are assertTrue, assertFalse, etc. 146 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 146
  • 147. 3.5.JUnit • Sample of ActivityInstrumentationTestCase2 147 public class FooctivityTest extends ActivityInstrumentationTestCase2<FooActivity> { public FooActivityTest() { super("jp.oesf.mtgeduwg.training.rssreader", FooActivity.class); } public void testUrlFieldKeyInput() { // Transmission of key ("T","E","S","T", and input) sendKeys(KeyEvent.KEYCODE_T, KeyEvent.KEYCODE_E KeyEvent.KEYCODE_S, KeyEvent.KEYCODE_T); assertEquals(“test”, urlField.getText().toString()); } } 1: Package of test target class 2: Class information of test target class Input key Activity of test target This material is licensed under the Creative Commons License BY-NC-SA 4.0. 147
  • 148. 3.5.JUnit • Sample of ActivityInstrumentationTestCase2 148 package jp.oesf.mtgeduwg.training.test; public class AddActivityTest extends ActivityInstrumentationTestCase2<AddActivity> { public AddActivityTest() { super("jp.oesf.mtgeduwg.training.rssreader", AddActivity.class); } public void testAddButtonClick() { getActivity().runOnUiThread(new Runnable() { public void run() { urlField.setText("http://www.oesf.jp/modules/news/index.php?page=rss"); addButton.performClick(); }}); getInstrumentation().waitForIdleSync(); assertTrue(existsUrlAddressById(10)); Run button clicking Request processing to UI thread Activity of test target Wait closing process of UI thread This material is licensed under the Creative Commons License BY-NC-SA 4.0. 148
  • 149. 3.5.JUnit • Sample of ActivityInstrumentationTestCase2 (Screen transition) 149 public void testAddButtonClick() { ActivityMonitor monitor = new ActivityMonitor("jp.oesf.mtgeduwg.training.rssreader.RssListActivity", null, false); getInstrumentation().addMonitor(monitor); getActivity().runOnUiThread(new Runnable() { public void run() { addButton.performClick(); }}); Activity rssListActivity = getInstrumentation().waitForMonitor(monitor); if(rssListActivity != null){ rssListActivity.finish(); } } Monitor transition target Activity Get transition target Activity Finish transition target Activity This material is licensed under the Creative Commons License BY-NC-SA 4.0. 149
  • 150. 3.5.JUnit • Sample of ActivityUnitTestCase 150 package jp.oesf.mtgeduwg.training.test; public class AddActivityUnitTest extends ActivityUnitTestCase<AddActivity> { public AddActivityUnitTest() { super(AddActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); } public void testSendResumeEvent() throws Exception { Intent intent = new Intent(Intent.ACTION_MAIN); startActivity(intent, null, null); getInstrumentation().callActivityOnResume(getActivity()); } Activity of Test target Run onResume This material is licensed under the Creative Commons License BY-NC-SA 4.0. 150
  • 151. 3.5.JUnit • Sample of ServiceTestCase 151 package jp.oesf.mtgeduwg.training.test; public class AddServiceTest extends ServiceTestCase <AddService> { public AddServiceTest() { super(AddSer viceclass); } @Override protected void setUp() throws Exception { super.setUp(); } public void testService() { Intent intent = new Intent(AddService.class.getName()); int result = startService(intent); ・・・ } Activity of test target Create Intent, then start up Server based on that This material is licensed under the Creative Commons License BY-NC-SA 4.0. 151
  • 152. 3.5.JUnit • Memo 152 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 152
  • 153. 3.5.JUnit • How to create JUnit project 1. Select “New”->”Other” from menu “File” of Eclipse 153 1 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 153
  • 154. 3.5.JUnit 2. Select “Android Test Project” in Android folder, then push “Next” button 3. Default value for specifying Test target project in the column of An Exisiting Android Project of TestTarget is input, so if there is no change reason, click “Finish” button 154 2 3 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 154
  • 155. 3.5.JUnit 4. Next, select “File”, then “New”->”Other” to create TestCase 5. Select 「JUnit Test Case」 in JUnit folder, then press “Next” button 155 4 5 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 155
  • 156. 3.5.JUnit 6. Confirm the buttons being selected in New JUnit 3, and input parent class in Superclass, then push “Finish” button 156 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 156
  • 157. 3.5.JUnit • AndroidManifest.xml – When creating Test project by using Eclipse, the following bold-faced type is added in 2 places automatically( it is required for test execution) 157 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="jp.oesf.mtgeduwg.training.rssreader.test" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <uses-library android:name="android.test.runner" /> </application> <uses-sdk android:minSdkVersion="7" /> <instrumentation android:targetPackage="jp.oesf.mtgeduwg.training.rssreader" android:name="android.test.InstrumentationTestRunner" /> </manifest> This material is licensed under the Creative Commons License BY-NC-SA 4.0. 157
  • 158. 3.5.JUnit – How to execute test • Right-click on Test project, then select Run as -> Android JUnit Test It is necessary to connect with emulator or real device 158 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 158
  • 159. 3.5.JUnit – Check testing succeed/fail • It is possible to check by JUnit view 159 Success Failure This material is licensed under the Creative Commons License BY-NC-SA 4.0. 159
  • 160. Practice 3.5.JUnit Practice 8 • Practice theme – Create real test case of JUnit practically – Create 2 test cases – Study the way to do unit test in Android through what above mentioned 160 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 160
  • 161. Practice 3.5.JUnit Practice 8 • Practice steps 1. Create RssReaderTest project that assumes RssReader is test target 2. Create class for testing RssReaderActivity and RegisterService separately 3. Implement test method one by one for each one i. In testing RssReaderActivity, push “Display list)” button, then check item quantity of ListView being displayed in the “Display list” screen is bigger than 0 Describe testing done Hint: It is possible to get item quantity of ListView by ListView#getCount() ii. In testing RegisterService Check data quantity being stored in RSS_FEED table of DB before and after executing ResigsterService is increasing Hint: It is possible to get data quantity of Cursor by Cursor#getCount() 161 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 161
  • 162. Practice 3.5.JUnit Practice 8 • How to confirm – Execute testing to be green 162 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 162
  • 163. Practice 3.5.JUnit Practice 8 • Answer of Practice – RssReaderActivityTest.java 163 package jp.oesf.mtgeduwg.training.rssreader.test; import jp.oesf.mtgeduwg.training.rssreader.R; import jp.oesf.mtgeduwg.training.rssreader.RssReaderActivity; import android.app.Activity; import android.app.Instrumentation.ActivityMonitor; import android.test.ActivityInstrumentationTestCase2; import android.widget.Button; import android.widget.ListView; public class RssReaderActivityTest extends ActivityInstrumentationTestCase2<RssReaderActivity>{ public RssReaderActivityTest(){ super("jp.oesf.mtgeduwg.training.rssreader", RssReaderActivity.class); } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 163
  • 164. Practice 3.5.JUnit – RssReaderActivityTest.java (Continue) 164 public void testOnClickListButton(){ ActivityMonitor monitor = new ActivityMonitor("jp.oesf.mtgeduwg.training.rssreader.RssListActivity", null, false); getInstrumentation().addMonitor(monitor); final Button button = (Button) getActivity().findViewById(R.id.list_button); getActivity().runOnUiThread(new Runnable() { @Override public void run() { button.performClick(); } }); getInstrumentation().waitForIdleSync(); Activity rssListActivity = getInstrumentation().waitForMonitor(monitor); ListView listView = (ListView) rssListActivity.findViewById(android.R.id.list); assertTrue(listView.getCount() > 0); if(rssListActivity != null){ rssListActivity.finish(); } } } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 164
  • 165. Practice 3.5.JUnit – RegisterServiceTest.java 165 package jp.oesf.mtgeduwg.training.rssreader.test; import jp.oesf.mtgeduwg.training.rssreader.RegisterService; import jp.oesf.mtgeduwg.training.rssreader.helper.DatabaseOpenHelper; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.test.ServiceTestCase; public class RegisterServiceTest extends ServiceTestCase<RegisterService> { public RegisterServiceTest() { super(RegisterService.class); } public void testRegisterService() { int before; int after; Intent intent = new Intent(RegisterService.class.getName()); before = countDb(); startService(intent); after = countDb(); assertTrue(after - before > 0); } This material is licensed under the Creative Commons License BY-NC-SA 4.0. 165
  • 166. Practice 3.5.JUnit – RegisterServiceTest.java (Continue) 166 private int countDb() { int result = 0; Cursor cursor = null; DatabaseOpenHelper databaseOpenHelper = new DatabaseOpenHelper(getContext()); SQLiteDatabase database = null; try { database = databaseOpenHelper.getReadableDatabase(); cursor = database.query(“RSS_FEED”, null, null, null, null, null, null); result = cursor.getCount(); } finally { if (database != null) { database.close(); } if(cursor != null){ cursor.close(); } } return result; } } it will be an exception if not close Cursor explicitly in JUnit This material is licensed under the Creative Commons License BY-NC-SA 4.0. 166
  • 167. Practice 3.5.JUnit Practice 8[Supplement] • Practice Theme – Test other method 167 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 167
  • 168. 4. Practical development 2 168 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 168
  • 169. Outline of Chapter 4 • Activity and Task – Task – Affinity – Start-up mode • Task management 169 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 169
  • 170. 4.1.Activity and Task • The task of Application – The task of Android is a mechanism of managing Activities – The task is managing Activities by Stack structure – Even when activity of other application is started up, that activity will be handled as same task 170 Task Task Task Start up Start up Start up Back BackBack Root activity This material is licensed under the Creative Commons License BY-NC-SA 4.0. 170
  • 171. 4.1.Activity and Task • Affinity – It means 親和性(Affinity) if literal translation – All activities in application have Affinity that all is the same task in default – Normally, activity in the same application has the same affinity, but it is also possible to set affinity separately by setting affinity in individual activity 171 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 171
  • 172. 4.1.Activity and Task • The setting and the behavior of Affinity – The value of affinity could be registered in AndroidManifest.xml – In the default behavior, activities will be the same task even if affinity is set – In case of starting up by other task, it is necessary to describe the setting of flag in intent that delivers to startActivity method => Even if taskAffinity is specified, if there is no flage, it will be the same task AndroidManifest.xml sample code 172 ・・・ <activity android:name=“TestActivity" android:taskAffinity=“jp.sample.test"></activity> ・・・ This material is licensed under the Creative Commons License BY-NC-SA 4.0. 172
  • 173. 4.1.Activity and Task • Flag of intent – Flag of intent is prepared in android.content.Intent – It is ok to deliver the value of flag to Intent#setFlags – In case of starting up by other task, it is necessary to describe the setting of flag to intents that delivers to startActivity method – The task linkage flag is as below FLAG_ACTIVITY_NEW_TASK start up new task based on Affinity FLAG_ACTIVITY_MULTIPLE_TASK start up new task in the multiple by using the flag mentioned above at the same time 173 ・・・ Intent intent = new Intent(this, NextActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); ・・・ This material is licensed under the Creative Commons License BY-NC-SA 4.0. 173
  • 174. B:yyyTask:foo X:xxx Task:foo 4.1.Activity and Task – FLAG_ACTIVITY_NEW_TASK 174 A:foo Task:foo A:xxxTask:bar B:bar Task:bar B:yyyTask:foo A:foo X:foo Task:bar B:bar Y:bar Task:bar B:yyy Y:yyy B:yyyTask:foo A:foo X:foo C:foo B X Y C The activity which started up newly is allocated into new task, and in case there is a task that has the same affinity, it is allocated into that task. This material is licensed under the Creative Commons License BY-NC-SA 4.0. 174
  • 175. Task:foo 4.1.Activity and Task – FLAG_ACTIVITY_NEW_TASK 175 A:foo Task:foo A:xxxTask:bar B:bar B C B However, in case the same activity has been allocated as root activity of task, new task is not started, and the task that has that activity will move to foreground Task:foo A:xxxTask:bar B:bar Task:foo A:xxxTask:bar B:bar C:bar C:bar This material is licensed under the Creative Commons License BY-NC-SA 4.0. 175
  • 176. Task:foo 4.1. Activity and Task 176 A:foo Task:foo A:xxxTask:bar B:bar B C B If setting together with FLAG_ACTIVITY_NEW_TASK, Task will be started newly even if the same affinity Task exists. Task:foo A:xxxTask:bar B:bar Task:foo A:xxxTask:bar B:barTask:bar C:bar Task:bar Task:bar B:bar – FLAG_ACTIVITY_MULTIPLE_TASK This material is licensed under the Creative Commons License BY-NC-SA 4.0. 176
  • 177. 4.1.Activity and Task 177 • android:allowTaskReparenting attribute – There is no application element of AndroidManifest.xml, and it is possible to specify this as attribute of activity element – In case of application element, and in case of activity element in the entire of that application, this has effect on that activity – In case of specifying the value as ”true”, when a certain task moves to foreground, the activities that have affinity same as that task are absorbed by that task, and reallocated – Disable Root activity ( Rearrangement is not done) Task:foo A:foo X:bar Task:bar B:bar Start up C: bar Task:foo A:foo Task:bar B:bar Foreground Foreground X:bar C:bar This material is licensed under the Creative Commons License BY-NC-SA 4.0. 177
  • 178. 4.1. Activity and Task • Activity and Start-up mode android:launchMode – It is possible to specify as attribute of activity element of AndroidManifest.xml 178 Start-up Mode Allocated task Multiple generation of same activity Whether to able to include other activities in task The way to process new intent when instance of same activity exists Standard (Default) Started task Multiple generation Possible To be processed newly( new instance is generate) singleTop Reuse or process newly when same activity exists in the top of stack singleTask New task( be root activity always) Only one task is generated In case it exists in the current task, this task will move to foreground( In case there is no activity concerning to the top position, intent will drop) singleInstance Impossible (only itself) To be processed newly Reference http://developer.android.com/intl/ja/guide/topics/fundamentals.html#lmodesThis material is licensed under the Creative Commons License BY-NC-SA 4.0. 178
  • 179. 4.1.Activity and Task • Memo column 179 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 179
  • 180. 4.2.Task management 180 • Clear Task – After a certain period of time without application operation, when Application is started up again from Launcher, excepting for root activity, others will be destroyed –The behavior above is default, and it is possible to change the behavior by changing attribute of activity element Task:foo A:foo B:bar Start up App C:foo D:bar Task:foo A:foo B:bar C:foo D:bar Destroy 3 After a certain period of time This material is licensed under the Creative Commons License BY-NC-SA 4.0. 180
  • 181. 4.2.Task management 181 –android:alwaysRetainTaskState – In case it is specified as “true”, task is not cleared – The setting is active for Root activity only Task:foo A:foo B:bar Start up App C:foo D:bar Task:foo A:foo B:bar C:foo D:bar This material is licensed under the Creative Commons License BY-NC-SA 4.0. 181
  • 182. 4.2.Task management 182 – android:clearTaskOnLaunch – In case it is specified as “true”, status of task is always cleared even though a certain period of time has not elapsed, and excepting for root activity, others will be destroyed – Exactly, it is destroyed at the time of moving to background – The setting is active for Root activity only Task:foo A:foo B:bar Start up App C:foo D:bar Task:foo A:foo B:bar C:foo D:bar Destroy 3 Always This material is licensed under the Creative Commons License BY-NC-SA 4.0. 182
  • 183. 4.2. Task management 183 –android:finishOnTaskLaunch – In case it is specified as “true”, status of task is cleared even if a certain period of time has not elapsed, excepting for root activity, others will be destroyed – Exactly, it is destroyed at the time of moving to background – The setting is only active for root activity Task:foo A:foo B:bar Start up App C:foo D:bar Task:foo A:foo B:bar C:foo D:bar Destroy 3 Always This material is licensed under the Creative Commons License BY-NC-SA 4.0. 183
  • 184. 4.2.Task management 184 • Task and Intent flag – FLAG_ACTIVITY_CLEAR_TOP – When starting up an activity, if the same activities have been allocated, destroy the activities upper than the started up one –In case Start-up mode is ”standard”, destroy the display activities to generate new instance Task A B Start up A C Task A B C Destroy A If Start-up mode is not “standard”, A is not destroyedThis material is licensed under the Creative Commons License BY-NC-SA 4.0. 184
  • 185. 4.2.Task management 185 – FLAG_ACTIVITY_REORDER_TO_FRONT – When starting up an activity, if the same activities have been allocated, move the started up one to the head of task – In case Start-up Mode is ”standard”, also destroy the displayed activity to generate new instance Task A B Start up A C Task B C A This material is licensed under the Creative Commons License BY-NC-SA 4.0. 185
  • 186. 4.2.Taks management 186 – FLAG_ACTIVITY_NO_HISTORY – If activity which started up after setting is moved to background, activity will close –The same behavior is done even if setting android:noHistory attribute of activity as ”true” Task A B Start up C Task A C This material is licensed under the Creative Commons License BY-NC-SA 4.0. 186
  • 187. 4.2.Task management 187 – FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS – If activity which started up after setting this flag is moved to background, activity will close –The same behavior is done even if setting android:noHistory attribute of activity as ”true” Task A B Start up C Task A C This material is licensed under the Creative Commons License BY-NC-SA 4.0. 187
  • 188. Practice 4.3. Practice Practice 9 • Practice theme – Confirm behavior of FLAG_ACTIVITY_NEW_TASK – Set flags above to all transitions, and confirm as follows 188 B:yyyTask:foo X:xxx Task:foo A:foo Task:foo A:xxxTask:bar B:bar Task:bar B:yyyTask:foo A:foo X:foo Task:bar B:bar Y:bar Task:bar B:yyy Y:yyy B:yyyTask:foo A:foo X:foo C:foo B X Y C This material is licensed under the Creative Commons License BY-NC-SA 4.0. 188
  • 189. Practice 4.3. Practice Practice 9 • Practice steps 1. Modify the following points of Affinity project to complete i. Confirm file composition of stub project ii. Implement onClickGoTo?Button to each activity( exclude C.java) Try to set flag FLAG_ACTIVITY_NEW_TASK of all intents when screen transition iii. Edit AndroidManifest.xml so that activities A,X,C become the same affinity iv. Similarly, try to make so that acitivities B, Y also become the same affinity 189 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 189
  • 190. Practice 4.3. Practice Practice 9 – Setting information 1 • Implement the following class, method 190 Object Class Method Outline - Each activity onClickGoTo?Button • Refer to screen transition This material is licensed under the Creative Commons License BY-NC-SA 4.0. 190
  • 191. Practice 4.3. Practice Practice 9 – Setting information 2 • Edit the following file 191 File name Outline AndroidManifest.xml • Set android:taskAffnity to each activity • If group could be divided like steps, the value is decided properly This material is licensed under the Creative Commons License BY-NC-SA 4.0. 191
  • 192. Practice 4.3. Practice Practice 9 • How to confirm – Confirm the transition: A=>B=>X=>Y=>C when you push a button of screen – After it is transited to C, check the transition :C=>X=>A=>Y=>B when you push Back button [Supplement] You understand that the task can be done to be 2 tasks even if you long-push Home button 192 B:yyyTask:foo X:xxx Task:foo A:foo Task:foo A:xxxTask:bar B:bar Task:bar B:yyyTask:foo A:foo X:foo Task:bar B:bar Y:bar Task:bar B:yyy Y:yyy B:yyyTask:foo A:foo X:foo C:foo B X Y C This material is licensed under the Creative Commons License BY-NC-SA 4.0. 192
  • 193. Practice 4.3. Practice Practice 9 • Answer of Practice – A.java (Solution for other activity is omitted) 193 ・・・ public void onClickGoToBButton(View v){ Intent intent = new Intent(this, B.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } ・・・ This material is licensed under the Creative Commons License BY-NC-SA 4.0. 193
  • 194. Practice 4.3. Practice Practice 9 • Answer of Practice – AndroidManifest.xml 194 ・・・ <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".A" android:label="@string/app_name"> ・・・・ <activity android:name="B" android:taskAffinity="jp.oest.mtgeduwg.training.affinity.b"></activity> <activity android:name="X"></activity> <activity android:name="Y" android:taskAffinity="jp.oest.mtgeduwg.training.affinity.b"></activity> <activity android:name="C"></activity> ・・・ ※ Because the value of the affinity is one example, anything is good This material is licensed under the Creative Commons License BY-NC-SA 4.0. 194
  • 195. Practice 4.3. Practice Practice 9[Supplement 1] • Practice theme – Similarly, try to set other FLAG_ACTIVITY_NEW_TASK flag in screen C transited from screen B which is the last transition target to do transition – If you do in that way, screen Y will be displayed without transition from Screen C to Screen B – Screen B is root activity, so the tasks that belong to Screen B only move to foreground 195 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 195
  • 196. Practice 4.3. Practice Practice 9 [Supplement 2] • Practice theme – Change Affinity project freely, then confirm the change of behavior by setting other flag, attribute – Confirming from FLAG_ACTIVITY_XXXXX which is used at relatively- high frequency in actual work is recommended. 196 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 196
  • 197. 5. Outside solidarity 197 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 197
  • 198. The outline of chapter 5 • Outside solidarity outline and method • JSON analyzing • [Supplemental practice] XML analyzing 198 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 198
  • 199. 5.1.Outside solidarity outline and method • The feature of Android is able to unite with outside • The application that connects with Cloud server( server side) can be made on the assumption of being able to connect with network at all times • XML and JSON are used mostly for data transaction between Cloud server and terminal Cloud • It is necessary to do to be able parse XML, JSON on Terminal • Further, there are many samples implemented with JSON 199 Cloud Service This material is licensed under the Creative Commons License BY-NC-SA 4.0. 199
  • 200. 5.1.Outside solidarity outline and method • A sample of service – Most of famous services have been providing XML and JSON 200 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 200
  • 201. 5.1.Outside solidarity outline and method • What is XML? • Extensible Markup Language • A format that surrounds beginning and ending data by tag to add meaning • Tag can be nested, so the hierarchical structure can be expressed, but the cyclic structure can not be expressed, so it is specified by attribute • It is used widely and it is possible to specify character code also • There is tag as well as attribute in that, so it is a fault that the redundancy readability is not good 201 <?xml version="1.0" encoding="UTF-8"?> <statuses type="array"> <status> <created_at>Thu Oct 21 19:13:18 +000 <id>28052969836</id> <user> <id>20536157</id> <name>A Googler</name> ・・・・ This material is licensed under the Creative Commons License BY-NC-SA 4.0. 201
  • 202. 5.1. Outside solidarity outline and method • What is JSON? • JavaScript Object Notation • Originally it was the method of describing object in JavaScript, and the specification of data format is made from that without change • It is very simple and easy to understand • Basically, character code is only UTF-8 • The faults are function is restrictive (「Numerical value」「Character string」「Truth value(true、false)」「Array」「Object」「null」), show-able data is restricted, and cycled data can not be handled 202 Reference:http://www.json.org/json-ja.html/ [ { "created_at": "Thu Oct 21 19:13:18 +0000 2010", "id": 28052969836, "user": { "id": 20536157, “name”: “A Googler”,・・・ This material is licensed under the Creative Commons License BY-NC-SA 4.0. 202
  • 203. 5.1. Outside solidarity outline and method • HTTP communication on Android • It is ok with the method same as HTTP connection in Java • Use java.net class Explanation about implementation Sample 1. Generate URL object based on URL of access target 2. Get HttpURLConnection object and set method of HTTP also 3. Connect actually, and get resource as InputStream Then, keep InputStream as byte[] 4. Write out byte[] to ByteArrayOutputStream 5. Settle HTTP communication 203 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 203
  • 204. 5.1.Outside solidarity outline and method 204 import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.StringReader; import java.net.HttpURLConnection; import java.net.URL; ・・・ private void getHttp() { HttpURLConnection http = null; InputStream in = null; ByteArrayOutputStream out = null; byte[] byteArray = null; Int size = 0; try { URL url = new URL(“http://www.oesf.jp”); http = (HttpURLConnection) url.openConnection(); http.setRequestMethod("GET"); http.connect(); in = http.getInputStream(); byteArray = new byte[in.available()]; ・・・1 ・・・2 ・・・3 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 204
  • 205. 5.1.Outside solidarity outline and method 205 out = new ByteArrayOutputStream(); while ((size = in.read(byteArray)) } != -1) { out.write(byteArray, 0, size); } catch (Exception e) { } finally { try { in.close(); } catch (Exception e) { } try { http.disconnect(); } catch (Exception e) { } } } ・・・4 ・・・5 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 205
  • 206. 5.2.JSON analyzing • JSON analyzing – Data which is got by communication with HTTP is character string in JSON format – It is necessary to handle that character string as an object to be able to use data – JSONObject and JSONArray class of org.json package are used for that 206 This material is licensed under the Creative Commons License BY-NC-SA 4.0. 206

Notas del editor

  1. ・章全体の説明を一言でする ・各節の内容には触れない(後の説明と重複する為)
  2. プロセス破棄という状態は後ほど説明
  3. アプリケーション=アクティビティ、ブロードキャストレシーバ、サービスを含めたもの アプリケーション間でデータ交換を行う為の仕組みです。 その時に使われるパラメータもインテントと呼びます。 インテントと呼ばれる非同期メッセージによってアクティブ化されます。インテントは、メッセージのコンテンツを保持する Intent オブジェクトです。
  4. アプリケーション=アクティビティ、ブロードキャストレシーバ、サービスを含めたもの アプリケーション間でデータ交換を行う為の仕組みです。 その時に使われるパラメータもインテントと呼びます。 インテントと呼ばれる非同期メッセージによってアクティブ化されます。インテントは、メッセージのコンテンツを保持する Intent オブジェクトです。
  5. 他にマルチスレッドプログラミング(UIへはHandler利用)にAsyncTaskがある http://itpro.nikkeibp.co.jp/article/COLUMN/20100302/345249/?ST=android-dev 処理はなるべく複数のスレッドに分散させたいが、前述のようにAndroidの画面描画は全てメインスレッドで行われ、別スレッドでは処理できない。そこで、Handlerというクラスを使ってメインスレッドで実行させる。だがそのための手続きはやや煩雑で、ソースコードの可読性を下げてしまう。  そこでAsyncTaskを使う。HandlerはAsyncTaskのクラス内部で隠蔽されるため、煩雑になりがちなAndroidでのスレッド処理を比較的簡単に、また適切に扱うことができる。
  6. 外部アプリケーションの情報を直接参照できない事は、次のページで説明する
  7. リンクは画像に限らずリソース全般の代替え読み込みの説明 layout-854*400 の説明をしても良い
  8. その他、テストのしづらい単体テストができるようになったので、品質の納期に良い結果となった。
  9. テスト対象のアプリとパッケージ分けないとだめ
  10. Genericの説明
  11. addButtonはfinalインナークラスからアクセスされるローカル変数はfinal
  12. Class under Testを入力するとスタブが作れる
  13. Class under Testを入力するとスタブが作れる
  14. Class under Testを入力するとスタブが作れる
  15. すでに同じアクティビティがタスクのルートアクティビティとして配置されている場合はこのフラグを設定しても新しいタスクは開始されず、 そのタスクがフォアグラウンドに移動する。
  16. たとえ、別アプリケーションで定義され別アプリケーションプロセスで実行されていたとしても、ユーザにとってはまるで、マップViewerがあたかもあなたのアクティビティと同じアプリケーション内にあるかのように見えることでしょう。Androidでは、両方のアクティビティを同じタスク内に保持し続けることにより、このようなユーザ操作を実現しています。簡潔に言えば、タスクとはユーザがアプリケーションとして経験するもの、そのものということになるでしょう。スタックに配置された関連するアクティビティのグループと言い換えてもいいでしょう。
  17. すでに同じアクティビティがタスクのルートアクティビティとして配置されている場合はこのフラグを設定しても新しいタスクは開始されず、 そのタスクがフォアグラウンドに移動する。
  18. FLAG_ACTIVITY_NEW_TASKと共にでないとダメ
  19. http://developer.android.com/intl/ja/guide/topics/fundamentals.html#afftask
  20. http://developer.android.com/intl/ja/guide/topics/fundamentals.html#afftask
  21. http://developer.android.com/intl/ja/guide/topics/fundamentals.html#afftask http://webcache.googleusercontent.com/search?q=cache:rDtB2ZZvJsgJ:www.techdoctranslator.com/android/guide/manifest/activity-element+alwaysRetainTaskState&amp;cd=1&amp;hl=ja&amp;ct=clnk&amp;gl=jp&amp;client=firefox-a
  22. http://developer.android.com/intl/ja/guide/topics/fundamentals.html#afftask http://webcache.googleusercontent.com/search?q=cache:rDtB2ZZvJsgJ:www.techdoctranslator.com/android/guide/manifest/activity-element+alwaysRetainTaskState&amp;cd=1&amp;hl=ja&amp;ct=clnk&amp;gl=jp&amp;client=firefox-a
  23. http://developer.android.com/intl/ja/guide/topics/fundamentals.html#afftask http://webcache.googleusercontent.com/search?q=cache:rDtB2ZZvJsgJ:www.techdoctranslator.com/android/guide/manifest/activity-element+alwaysRetainTaskState&amp;cd=1&amp;hl=ja&amp;ct=clnk&amp;gl=jp&amp;client=firefox-a
  24. http://developer.android.com/intl/ja/guide/topics/fundamentals.html#afftask
  25. http://developer.android.com/intl/ja/guide/topics/fundamentals.html#afftask FLAG_ACTIVITY_NEW_TASK, FLAG_ACTIVITY_CLEAR_TOPが優先
  26. http://developer.android.com/intl/ja/guide/topics/fundamentals.html#afftask FLAG_ACTIVITY_NEW_TASK, FLAG_ACTIVITY_CLEAR_TOPが優先
  27. http://developer.android.com/intl/ja/guide/topics/fundamentals.html#afftask FLAG_ACTIVITY_NEW_TASK, FLAG_ACTIVITY_CLEAR_TOPが優先
  28. すでに同じアクティビティがタスクのルートアクティビティとして配置されている場合はこのフラグを設定しても新しいタスクは開始されず、 そのタスクがフォアグラウンドに移動する。
  29.  オブジェクトは{}で全体を囲み、キーと値のペアをコロン(:)で区切って記述します。カンマ(,)で複数のキーと値を記述することも可能です。キーには文字列のみ使用可能です。リスト3にオブジェクトの記述例を示します(図2)。  配列は繰り返し項目を表現する際に使用します。全体を[]で囲み、値をカンマ(,)で区切って列挙します。リスト4に配列の記述例を示します(図2)。  構造化されたデータを表現するために、オブジェクトと配列を自由にネストさせることができます。 JSONでは「数値」「文字列」「真偽値(true、false)」「配列」「オブジェクト」「null」
  30. new String(byteArrayOutputStream.troByteArray[]); でStringになる
  31. 頭から一つずつ(階層を意識せず)回していくならXmlPullParserが早い
  32. get は型指定なし(型がわからないときとか)
  33. get は型指定なし(型がわからないときとか)
  34. get は型指定なし(型がわからないときとか)
  35. すでに同じアクティビティがタスクのルートアクティビティとして配置されている場合はこのフラグを設定しても新しいタスクは開始されず、 そのタスクがフォアグラウンドに移動する。
  36. GOOGLE の部分を好きなユーザーIDに変更しても良い
  37. res/rawの中にも入っているので気になる方は見てみる or ブラウザで直接アクセスしてDL
  38. (1)DOM (Document Object Model) --- ツリー・ベースのAPI (2)SAX (Simple API for XML) --- イベント・ベースのAPI(Push型) (3)StAX (Streaming API for XML) --- イベント・ベースのAPI(Pull型) http://itpro.nikkeibp.co.jp/article/COLUMN/20100302/345249/?ST=android-dev