-
-
2012
681.3.06
32.973.26-018.2
61
61
. .
Google Android: . .:
-, 2012. 384 .: . ( )
ISBN 978-5-9775-0666-3
Android.
Android, , , Wi-Fi.
Android: , , , , . Google : , , Geocoding, Google Map.
: ftp://85.249.45.166/9785977506663.zip
www.bhv.ru.
681.3.06
32.973.26-018.2
:
.
.
ISBN 978-5-9775-0666-3
. ., 2011
, "-", 2011
............................................................................................................................ 1
........................................................................................... 1
..................................................................................................... 2
................................................................................................ 5
................................................................................................................... 5
I. .................................................................................. 7
1.
.................................................................................... 9
Android SDK .................................................................................... 9
....................................... 10
USB...................................................................... 11
USB ............................................................................................ 12
DDMS ...................................................... 12
IDE Eclipse ..................... 13
.............................................................................................................................. 14
2. ...................... 15
Android ....................................................................................... 15
......................................................................................................... 15
Intent ................................................................................................................. 18
Intent- ................................................................................................................. 18
- ................................................................................... 19
............................................................................................... 19
....................................................... 20
.............................................................................................................................. 21
IV
II.
................................................................ 23
3. .................... 25
................................................................................................. 25
................................................... 25
........................................................... 27
.................................................................................. 28
.......................................................................... 28
TelephonyManager ........................................ 28
SIM- ......................................................................................................... 34
C SIM- ................................................................................................. 35
SIM- .......................................................................... 35
................................................ 37
.............. 38
......................................................................................... 39
.............................................................. 40
...................................................... 40
.................. 41
...................................... 46
.............................................................................................................................. 48
4. ................................................................ 49
........ 49
DDMS ................................................................. 49
Android ..................... 51
................................................................................................... 52
Intent .......................... 53
.............................................................. 54
........................................................................................ 58
.............................................................................................................................. 61
5. SMS .............................................. 62
SMS .............................................................. 62
SMS ....................................................................................... 64
SMS ........................................................................................... 65
SMS ....................................................................................... 65
SMS................................................................... 65
SMS ................................................................................. 66
SMS- ........................................................................................ 70
SMS- ................................................... 71
SMS .................................................................... 74
SMS ............................................................................................ 74
SMS- ............................................................................... 79
.............................................................................................................................. 82
III. .......................................................... 83
6. .................................................................................. 85
....................................................................................... 85
................................................................................. 85
............................................................................... 86
......................................................... 86
...................................................................................... 89
............................................................................ 89
..................................................... 90
....................................................................................................... 92
WebView .......................................................................................................... 93
WebView .............................................................................. 93
WebView .......................................................................... 95
................................................................... 97
............................................................................................................................ 106
7. Wi-Fi ............................................................. 107
Wi-Fi .................................................................................. 107
Wi-Fi .................................................................................... 107
................................................................................................................. 108
.............................................................................................. 108
..................................................................... 108
Wi-Fi
........................................................................................................... 110
Wi-Fi .............................................................. 115
........................................................................................ 118
IP- ............................................................................................................... 118
Wi-Fi ............................................. 119
Wi-Fi ................................................................................ 123
....................................................................................... 128
............. 133
............................................................................................................................ 137
VI
VII
V.
.......................................................... 195
11. ........................................................ 197
................................................................... 197
Android ........................................................................................... 198
Android ............................................................................... 199
.............................................................................. 202
SD- ................................................................... 203
............................................................................................................................ 212
12. ................................................................. 213
.................................................................................. 213
.................................................................................................... 214
....................................................... 214
................................................................... 216
Intent .............................................. 221
............................................................................ 224
........................................................................................ 227
.................................................................................................... 231
...................................................................................................... 236
.......................................................................................... 241
............................................................................................................................ 246
13. ................................................................................ 247
........................................................................... 247
............................................................................................. 247
......................................... 249
............................... 251
.............................................................................. 252
............................................................................................... 252
..................................................................................................... 256
.................................................................................................... 258
............................................................................................................. 263
.............................................................................. 267
, Android ........................ 269
Android .................................................. 269
............................................................................................................................ 271
VIII
IX
, ,
"Google Android: ", . , Android ,
, ""
Android.
, SMS-, , ,
Google .
"" :
, , , ,
, Android.
Java, Android. ,
, ,
Android Eclipse.
Android, , , ,
Android.
, , Android. ,
, . ,
, ,
Android, , , .
Android 2.3.3 (API Level 10). Android 2.3.3.
, , Android 2.1
Android 1.6, , Android, , , Android SDK,
.
6 , 20 , . .
" ".
Android,
.
1.
,
. , , Android SDK, Eclipse.
2.
Android.
. , Android , Google .
" ".
Android
: ,
SMS-.
3.
.
, .
4.
,
. ,
,
.
5. SMS
, SMS. Android SMS, SMS-
.
" ".
Wi-Fi:
, , .
6.
. . WebKit .
7. Wi-Fi
Wi-Fi
. ,
, ,
Wi-Fi.
" ".
Google Maps Geocoding: ,
, Google Maps
.
8.
Location anager
. , ,
.
9. Geocoding
Geocoding , .
,
.
10. Google Maps
Google API
. Maps API Key
Google Maps , MapView
.
" ".
: , , , "" .
11.
,
.
, , .
12.
,
: , , .
13.
, Android. .
, ,
, , , , , . , , .
14.
.
.
15.
, , , .
16.
. , .
" ".
Android,
, , ,
.
17.
Android: , , . Android, .
18.
,
.
19.
. , , ,
.
20. API
, Text To
Speech .
ftp://85.249.45.166/9785977506663.zip
, 1. . Android SDK 2.3.3 Eclipse.
, ,
. , ,
. ,
, .
, .
, Android.
, ,
.
, "-",
.
www.bhv.ru.
,
, , Android. Android ,
.
Android SDK
Android,
. Eclipse (
Eclipse Helios 3.6.2) ADT (Android Developer
Tools) . ADT 10.0.1 , ,
, .
Android
SDK 2.3.3 (API Level 10). Android SDK 3.0 (API Level 11) , Android, PC .
Android SDK, . SDK Manager , Android SDK, Android SDK and AVD Manager
Installed Packages. , . 1.1.
Android SDK 2.3.3, Google API
Google. Android
SDK .
Google API Level 10 (. 1.1).
, ,
.
, , .
I.
10
Android . , [1],
Android,
,
Adnroid. Android, [1], , , ,
Android .
1.
11
Android ,
. , ,
Android. ,
Android ,
. ,
, Wi-Fi, Bluetooth,
, ,
, ,
.
Android
, Android.
,
, :
USB.
, , USB
, .
DDMS
(Dalvik Debug Monitor Server).
USB
Settings (
Home Screen, ).
Applications | Development | USB debugging
Debug mode when USB is connected, . 1.2.
, , USB, , ,
.
I.
12
USB
, , USB-,
. :
USB, Android SDK;
USB,
.
USB Windows Android SDK. USB ,
Android SDK, android-sdk-windows\google-usb_driver.
,
USB, .
, USB.
USB , , .
DDMS
USB
Android. Dalvik Debug Monitor Server
tools Android SDK IDE Eclipse,
Devices ( Window | Show View | Other | Android | Devices).
. 1.3. DDMS
1.
13
IDE Eclipse
, Eclipse : Android
. Android Device Chooser, (. 1.4), , Android.
, .
. 1.4.
I.
14
Android ,
, . Android, .
Android.
, , Wi-Fi ( 7), ( 12),
( 13), ( 15) ( 16), Android .
, , Android .
, Android,
.
Android .
Android
, Android,
Android. :
Activity;
Broadcast Receiver;
Service;
Content Provider.
[1] ,
, , . Android , ,
. ,
Android.
,
,
, . ,
, Google, , Google Maps, Street View .
Android ,
. ,
3.0 35.
16
I.
Android , , Android.
Android
.
:
Wallpaper Service "", Home
Screen ( ) ;
Layout Inflater Service ;
UI Mode Service ,
.
Android ,
:
Input Method Service , .
. , , SMS;
Accessibility Service , , , , ;
Clipboard Service . Android, ,
, . . , ;
Search Service ;
Keyguard Service .
Android ,
,
, :
Notification Service (,
SMS-), ;
Alarm Service (,
) , , ;
Window Service ;
Activity Service Activity,
. , Activity Service
Activity, , ;
2.
17
Dropbox Service
.
, , Android
Audio Service.
Android
, "" :
Power Service . . ,
( );
Battery Manager .
, , ;
Sensor Service , , , , ;
Storage Service : ;
Vibrator Service ,
.
, Android
:
Telephony Service . ,
SMS-;
Connectivity Service ;
Download Service HTTP;
Wifi Service Wi-Fi;
Location Service . Google;
NFC Service NFC (Near Field Communication).
, , . ,
.
Android , :
Account Service
, -, Gmail, Facebook .;
I.
18
Device_policy Service
, , , .
Android SDK
. , , .
, , Power Service Power
Manager, Telephony Service Telephony Manager . .
Android , ,
, .
Intent
, , Android Activity,
, Intent. Android
.
Intent :
Activity Action Intent Activity, .
Activity.
, (, )
Activity,
;
Broadcast Intent ,
- , .
, SMS-
Android Broadcast Intent.
Intent,
.
Intent-
Broadcast Intent
, , . Broadcast Intent, ,
, ,
.
,
.
Broadcast Intent , ,
2.
19
.
Intent (Intent Filter). , , .
-
Android :
SQLite ,
Android;
- , .
- , . ,
.
Android , -.
-, , android.provider. , Android, :
ContactsContract ;
CallLog :
, ;
Browser , ;
Mediastore : , ;
Settings
, , , , , . .;
UserDictionary , .
- Android .
SMS-. - SMS
Android SDK, 5, SMS-.
20
I.
, , . , -, Browser, WebviewCache ,
Alarms.
,
. , , SMS, ,
.
. ,
, .
, <uses-permission> , , , (
, ),
, Permissions.
Add
User Permissions, . 2.1.
. 2.1. AndroidManifest.xml
2.
21
. 2.2.
Permissions Attributes
for Uses Permission. Name (. 2.2), .
AndroidManifest.xml.
. , .
Android Android, .
,
Android, .
II
,
. Android
, SMS-, .
.
TelephonyManager, android.telephony.
.
. TelephonyManager getSystemService(), Context.TELEPHONY_SERVICE:
TelephonyManager manage = (TelephonyManager)getSystemService(
Context.TELEPHONY_SERVICE);
TelephonyManager
. ,
, SIM .
, TelephonyManager
Telephony Service .
TelephonyManager getPhoneType() getNetworkType().
, .
26
II.
getPhoneType()
:
PHONE_TYPE_GSM GSM (Global System for Mobile communications, ). , , . ETSI 80- . GSM
;
PHONE_TYPE_CDMA CDMA (Code Division Multiple Access, ). , , ;
PHONE_TYPE_SIP SIP (Session Initiation Protocol, ). , IP-, SIP Android ,
Android SDK 2.3 (API Level 9);
PHONE_TYPE_NONE , -
.
getNetworkType(), , ,
, getPhoneType():
NETWORK_TYPE_GPRS GPRS (General Packet Radio Service,
). GSM
. GPRS GSM , .
. GPRS ,
GSM-;
NETWORK_TYPE_CDMA CDMA (
);
NETWORK_TYPE_1xRTT 1xRTT (One Times Radio Transmission Technology).
, CDMA, ;
NETWORK_TYPE_EDGE EDGE (Enhanced Data Rates for Global Evolution, GSM). EDGE
;
NETWORK_TYPE_EHRPD EHRPD (Evolved High-Rate Packet Data,
);
NETWORK_TYPE_LTE LTE (Long Term Evolution). LTE
CDMA UMTS (4G);
NETWORK_TYPE_EVDO_0, NETWORK_TYPE_EVDO_A, NETWORK_TYPE_EVDO_B
EVDO (Evolution-Data Optimized). , CDMA.1X;
3.
27
);
NETWORK_TYPE_HSDPA HSDPA (High Speed Downlink Packet Access).
HSPA ;
NETWORK_TYPE_HSUPA HSUPA (High Speed Uplink Packet Access). , HSDPA,
, ;
NETWORK_TYPE_IDEN IDEN (Integrated Digital Enhanced Network). ,
- . Motorola
;
NETWORK_TYPE_UMTS UMTS (Universal Mobile Telecommunications System).
GSM WCDMA.
ETSI;
NETWORK_TYPE_UNKNOWN , , .
, ,
android.telephony , . .
Android . , TelephonyManager, ,
: Android SDK -
.
TelephonyManager getCellLocation().
CellLocation.
CellLocation ,
, , ,
:
GsmCellLocation GSM;
CdmaCellLocation CDMA.
GsmCellLocation
:
getCid() ;
getLac() LAC (Location Area Code). ,
;
getPsc() PSC (Primary Scrambling Code). UMTS. getPsc() GsmCellLocation
, Android SDK 2.3.1 (API Level 9).
II.
28
TelephonyManager
getCallState(). , :
CALL_STATE_IDLE ;
CALL_STATE_OFFHOOK ;
CALL_STATE_RINGING .
, .
, . TelephonyManager
isNetworkRoaming(), boolean, , .
TelephonyManager
, TelephonyManager, Telephony
Service, . , TelephonyManager. IDE Eclipse , New Android Project:
Project name: PhoneInfo;
Application name: Phone info;
Package name: com.samples.telephony.phoneinfo;
Create Activity: PhoneInfoActivity.
-
Ch03_PhoneInfo.
3.
29
AndroidManifest.xml READ_PHONE_STATE,
Android , ACCESS_COARSE_LOCATION
, 3.1 ( ),
.
3.1. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.telephony.phoneinfo"
android:versionCode="1" android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity
android:name="PhoneInfoActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission
android:name="android.permission.READ_PHONE_STATE" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
</manifest>
main.xml
android:id="@+id/text". . main.xml 3.2.
TextView,
3.2. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="@+id/text"
II.
30
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5px"
android:textStyle="bold"/>
</LinearLayout>
PhoneInfoActivity TelephonyMa
. PhoneInfoActivity 3.3.
nager,
3.3. PhoneInfoActivity.java
package com.samples.telephony.phoneinfo;
import
import
import
import
import
import
import
android.app.Activity;
android.content.Context;
android.os.Bundle;
android.telephony.TelephonyManager;
android.telephony.cdma.CdmaCellLocation;
android.telephony.gsm.GsmCellLocation;
android.widget.TextView;
3.
text.append("\nNetwork Type:\t" +
convertNetworkTypeToString(manager.getNetworkType()));
text.append("\nNetwork Country ISO:\t" +
manager.getNetworkCountryIso());
text.append("\nNetwork Operator:\t" +
manager.getNetworkOperator());
text.append("\nNetwork Operator Name:\t" +
manager.getNetworkOperatorName());
text.append("\nPhone Type:\t" +
convertPhoneTypeToString(manager.getPhoneType()));
text.append("\nData Activity:\t" +
convertDataActivityToString(manager.getDataActivity()));
text.append("\nData State:\t" +
convertDataStateToString(manager.getDataState()));
text.append("\nSubscriber ID:\t" +
manager.getSubscriberId());
text.append("\nVoice Mail Alpha Tag:\t" +
manager.getVoiceMailAlphaTag());
text.append("\nVoice Mail Number:\t" +
manager.getVoiceMailNumber());
text.append("\nIcc Card:\t" +
manager.hasIccCard());
text.append("\nNetwork Roaming:\t" +
manager.isNetworkRoaming());
GsmCellLocation gsmCell =
(GsmCellLocation)manager.getCellLocation();
if (gsmCell != null) {
text.append("\nGSM Cell Location:");
text.append("\n\tCID:\t" + gsmCell.getCid());
text.append("\n\tLAC:\t" + gsmCell.getLac());
}
}
private String convertCallStateToString(int callState) {
switch (callState) {
case TelephonyManager.CALL_STATE_IDLE:
return "IDLE";
case TelephonyManager.CALL_STATE_OFFHOOK:
return "OFFHOOK";
case TelephonyManager.CALL_STATE_RINGING:
return "RINGING";
default:
return "Not defined";
}
}
private String convertNetworkTypeToString(int networkType) {
31
II.
32
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_1xRTT:
return "1xRTT";
case TelephonyManager.NETWORK_TYPE_CDMA:
return "CDMA";
case TelephonyManager.NETWORK_TYPE_EDGE:
return "EDGE";
case TelephonyManager.NETWORK_TYPE_EVDO_0:
return "EVDO revision 0";
case TelephonyManager.NETWORK_TYPE_EVDO_A:
return "EVDO revision A";
//case TelephonyManager.NETWORK_TYPE_EVDO_B:
// return "EVDO revision B";
case TelephonyManager.NETWORK_TYPE_GPRS:
return "GPRS";
case TelephonyManager.NETWORK_TYPE_HSDPA:
return "HSDPA";
case TelephonyManager.NETWORK_TYPE_HSPA:
return "HSPA";
case TelephonyManager.NETWORK_TYPE_HSUPA:
return "HSUPA";
//case TelephonyManager.NETWORK_TYPE_IDEN:
// return "iDen";
case TelephonyManager.NETWORK_TYPE_UMTS:
return "UMTS";
case TelephonyManager.NETWORK_TYPE_UNKNOWN:
return "Unknown";
default:
return "Not defined";
}
}
private String convertDataActivityToString(int dataActivity) {
switch (dataActivity) {
case TelephonyManager.DATA_ACTIVITY_DORMANT:
return "Dormant";
case TelephonyManager.DATA_ACTIVITY_IN:
return "In";
case TelephonyManager.DATA_ACTIVITY_INOUT:
return "In-out";
case TelephonyManager.DATA_ACTIVITY_NONE:
return "None";
case TelephonyManager.DATA_ACTIVITY_OUT:
return "Out";
default:
return "Not defined";
}
3.
33
}
private String convertDataStateToString(int dataState) {
switch (dataState) {
case TelephonyManager.DATA_CONNECTED:
return "Data connected";
case TelephonyManager.DATA_CONNECTING:
return "Data connecting";
case TelephonyManager.DATA_DISCONNECTED:
return "Data suspended";
case TelephonyManager.DATA_SUSPENDED:
return "Data suspended";
default:
return "Not defined";
}
}
private String convertPhoneTypeToString(int phoneType) {
switch (phoneType) {
case TelephonyManager.PHONE_TYPE_GSM:
return "GSM";
case TelephonyManager.PHONE_TYPE_CDMA:
return "CDMA";
case TelephonyManager.PHONE_TYPE_NONE:
return "NONE";
default:
return "Not defined";
}
}
}
. ,
. , 3.1
, .
, Android
. . Android . 3.2.
,
Android , . . Dalvik Debug Monitor
Server , , .
, SIM- .
34
II.
. 3.1.
. 3.2.
Android
SIM-
TelephonyManager,
SIM- . TelephonyManager :
getSimCountryIso() , SIM .
ISO 3166 2- (alpha-2)
, , ru, sw . .;
getSimOperator() MCC+MNC (Mobile Country Code +
Mobile Network Code, SIM). ;
getSimOperatorName() SPN (Service Provider Name, );
getSimSerialNumber() SIM- ,
;
getSimState() ,
SIM-.
, SIM- ,
TelephonyManager, . .
3.
35
C SIM-
getSimState()
SIM-. , getSimState(), ,
SIM-, , , TelephonyManager:
SIM_STATE_READY SIM- ;
SIM_STATE_ABSENT SIM- ;
SIM_STATE_PIN_REQUIRED SIM- , PIN- ;
SIM_STATE_PUK_REQUIRED SIM- , PUK- (8- ) ;
SIM_STATE_NETWORK_LOCKED SIM- , PIN- ;
SIM_STATE_UNKNOWN SIM- .
, SIM-, , SMS.
SIM-
,
SIM- .
IDE Eclipse Android New Android Project:
Project name: SimInfo;
Application name: SIM Card info;
Package name: com.samples.telephony.siminfo;
Create Activity: SimInfoActivity.
-
Ch03_SimInfo.
AndroidManifest.xml
READ_PHONE_STATE, 3.1.
main.xml, 3.2.
SimInfoActivity
PhoneInfoActivity . SimInfoActivity 3.4.
3.4. SimInfoActivity.java
package com.samples.telephony.siminfo;
import android.app.Activity;
II.
36
import
import
import
import
android.content.Context;
android.os.Bundle;
android.telephony.TelephonyManager;
android.widget.TextView;
3.
37
}
text.setText(
"\nSim CountryIso: " + simCountryIso +
"\nSim Operator: " + simOperator +
"\nSim OperatorName: " + simOperatorName +
"\nSim SerialNumber: " + simSerialNumber +
"\nSim SubscriberId: " + simSubscriberId +
"\nSim StateString: " + sSimStateString);
}
}
. Android SIM-, ,
Android, SIM- (. 3.3).
. 3.3. SIM-
.
, , .
android.telephony
PhoneStateListener.
38
II.
, .
, PhoneStateListener:
onCallStateChanged() , ,
. , ( CALL_STATE_IDLE,
CALL_STATE_OFFHOOK, CALL_STATE_RINGING),
;
onCellLocationChanged() ;
onDataActivity() ;
onDataConnectionStateChanged() ;
onServiceStateChanged()
;
onSignalStrengthsChanged()
;
onCallForwardingIndicatorChanged()
, ;
onMessageWaitingIndicatorChanged()
, SMS-.
, PhoneStateListener
.
PhoneStateListener PhoneStateListener ( ), :
private PhoneStateListener listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(
final int state, final String incomingNumber) {
//
}
@Override
public void onDataConnectionStateChanged(int state, int networkType) {
//
}
...
};
3.
39
TelephonyManager
. TelephonyManager listen(), :
PhoneStateListener, ;
, , .
PhoneStateListener. :
LISTEN_CALL_FORWARDING_INDICATOR;
LISTEN_CALL_STATE;
LISTEN_CELL_LOCATION;
LISTEN_DATA_ACTIVITY;
LISTEN_DATA_CONNECTION_STATE;
LISTEN_MESSAGE_WAITING_INDICATOR;
LISTEN_SERVICE_STATE;
LISTEN_SIGNAL_STRENGTHS.
, , PhoneStateListener,
. ,
LISTEN_CELL_LOCATION onCellLocationChanged().
:
TelephonyManager manager = (TelephonyManager)getSystemService(
Context.TELEPHONY_SERVICE);
manager.listen(cellLocationListener,
PhoneStateListener.LISTEN_CELL_LOCATION);
,
, :
manager.listen(cellLocationListener,
PhoneStateListener.LISTEN_CELL_LOCATION |
PhoneStateListener.LISTEN_SIGNAL_STREIGHT);
LISTEN_NONE.
, listen() :
PhoneStateListener
manager.listen(cellLocationListener, PhoneStateListener.LISTEN_NONE);
. , .
,
onSignalStrengthsChanged(), .
40
II.
SignalStrength, . SignalStrength :
getCdmaDbm() RSSI (Received Signal Strength Indication,
). RSSI dBm (
).
1 . , 30 dBm
1 ( ).
;
getEvdoDbm() RSSI EVDO;
getCdmaEcio() / (Ec/Io)
dB * 10 CDMA;
getEvdoEcio() / (Ec/Io)
EVDO;
getEvdoSnr() /,
0 8, 8 ;
getGsmSignalStrength() GSM Signal
Strength;
getGsmBitErrorRate() GSM Error Rate. Error Rate
/.
GSM Signal Strength, GSM Error Rate
GSM TS 27.007 8.5. , GSM
Signal Strength 0 31 99. 0
113 dBm , 1 111 dBm, 2 30 109
53 dBm, 31 51 dBm , 99
.
. onCellLocationChanged()
CellLocation. C .
,
ACCESS_COARSE_LOCATION,
:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
,
, ,
.
3.
41
onServiceStateChanged(),
ServiceState
ServiceState.
.
ServiceState getState(), :
STATE_IN_SERVICE ;
STATE_EMERGENCY_ONLY ;
STATE_OUT_OF_SERVICE ;
STATE_POWER_OFF .
Airplane Mode.
ServiceState :
getOperatorAlphaLong() ;
getOperatorAlphaShort() ;
getOperatorNumeric() .
, ServiceState
getRoaming() getIsManualSelection(),
true, , false
.
,
. , . IDE
Eclipse Android, New
Android Project:
Project name: PhoneChangeStateInfo;
Application name: com.samples.telephony.phonechangestateinfo;
Package name: com.samples.telephony.phonechangestateinfo;
Create Activity: PhoneChangeStateInfoActivity.
-
Ch03_PhoneChangeStateInfo.
Start Stop bStart
bStop. TextView text .
main.xml 3.5.
II.
42
3.5. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_margin="5px">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<Button
android:id="@+id/bStart"
android:layout_height="wrap_content"
android:text="Start"
android:layout_width="fill_parent"
android:layout_weight="1"/>
<Button
android:id="@+id/bStop"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="Stop"
android:layout_weight="1"/>
</LinearLayout>
<TextView
android:id="@+id/text"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"/>
</LinearLayout>
3.
3.6. PhoneChangeStateInfoActivity.java
package com.samples.telephony.phonechangestateinfo;
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.content.Context;
android.os.Bundle;
android.telephony.PhoneStateListener;
android.telephony.ServiceState;
android.telephony.TelephonyManager;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.TextView;
43
II.
44
text.append("\nMessageWaitingIndicator:\t" + mwi);
}
@Override
public void onServiceStateChanged(ServiceState serviceState) {
text.append("\nService State:\t" +
convertServiceStateToString(serviceState.getState()));
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
Button bStart = (Button)findViewById(R.id.bStart);
Button bStop = (Button)findViewById(R.id.bStop);
text = (TextView)findViewById(R.id.text);
bStart.setOnClickListener(this);
bStop.setOnClickListener(this);
// TelephonyManager
manager = (TelephonyManager)getSystemService(
Context.TELEPHONY_SERVICE);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bStart:
//
manager.listen(listener,
PhoneStateListener.LISTEN_CALL_STATE |
PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR |
PhoneStateListener.LISTEN_DATA_ACTIVITY |
PhoneStateListener.LISTEN_DATA_CONNECTION_STATE |
PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR |
PhoneStateListener.LISTEN_SERVICE_STATE);
text.setText("Start phone info listener...");
break;
case R.id.bStop:
//
manager.listen(listener,
PhoneStateListener.LISTEN_NONE);
text.setText("Listener is stopped");
break;
}
}
// ServiceState
private String convertServiceStateToString(int serviceState) {
switch (serviceState) {
3.
45
case ServiceState.STATE_EMERGENCY_ONLY:
return "Emergensy Only";
case ServiceState.STATE_IN_SERVICE:
return "In Service";
case ServiceState.STATE_OUT_OF_SERVICE:
return "Out of Service";
case ServiceState.STATE_POWER_OFF:
return "Power OFF";
default:
return "Not defined";
}
}
...
}
.
. 3.4.
. 3.4.
. Start.
: ?
, . ,
, . Dalvik Debug Monitor Server.
46
II.
TelephonyManager
. Android Dalvik Debug Monitor Server
.
DDMS Android SDK (
tools\ddms.bat) Eclipse (,
ADT). Eclipse Window | Show View | Other
Devices Emulator Control (. 3.5).
Devices Android.
, ,
DDMS. . ,
AVD1 5554:AVD1. ,
Devices, . 3.6.
Emulator Control.
. Emulator Control Eclipse . 3.7.
3.
47
. 3.6. Devices
Emulator Control :
Telephony Status (GPRS, EDGE, UTMS, . .);
Telephony Actions
SMS ;
Location Controls ( IV ).
II.
48
c
Incoming number (5554).
Emulator Control.
,
Start.
, . 3.8.
. 3.8.
.
.
SMS .
TelephonyManager
Android
. ,
. , , .
, Android.
. Android
.
:
DDMS;
Android.
Android DDMS
, .
DDMS
DDMS . , ,
, .
,
Devices IDE Eclipse,
50
II.
. 4.1. Eclipse
, . 4.2.
. 4.2. Android
4.
51
Android
Android
.
Eclipse Devices, . 4.3.
,
. ,
, , , 5554.
, . . Android Virtual Device,
, 2: 5556, 5558 . .
Android
: Android Debug Bridge ( Android, Android SDK). ,
, ,
c 5554 5555 Android Debug Bridge.
Android
, 5556, 5557 , 5558, 5559 . . 16 ,
.
52
II.
,
5556 5554. 5556
, 5554
. 5554 .
, :
"1-555-521-" ""
, . 4.4.
Android
, .
, , . ,
, .
CALL_PHONE
;
CALL_PRIVILEGED
,
;
PROCESS_OUTGOING_CALLS
Broadcast Intent ;
READ_PHONE_STATE
( );
MODIFY_PHONE_STATE
.
4.
53
,
, CALL_PHONE AndroidManifest.xml:
<uses-permission android:name="android.permission.CALL_PHONE" />
, , .
Intent
Android , ,
.
, Intent. Intent , :
ACTION_DIAL;
ACTION_CALL;
ACTION_CALL_BUTTON.
, ACTION_CALL_BUTTON, ,
:
Intent intent = new Intent(Intent.ACTION_CALL_BUTTON);
startActivity(intent);
, . 4.5.
. 4.5.
ACTION_CALL_BUTTON
, . , .
II.
54
ACTION_DIAL ACTION_CALL
, Intent Extra () .
Extra- Intent , URI, :
tel:_
,
, URI Intent, , :
String phoneNum = "5554"
Uri uri = Uri.parse("tel:" + phoneNum);
Intent intent = new Intent(Intent.ACTION_DIAL, uri);
startActivity(intent);
. IDE Eclipse
Android New Android
Project:
Project name: PhoneCall;
Application name: Phone Call;
Package name: com.samples.telephony.phonecall;
Create Activity: PhoneCallActivity.
-
Ch04_PhoneCall.
. AndroidManifest.xml
4.1.
android.permission.CALL_PHONE
4.1. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.telephony.phonecall"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".PhoneCallActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
4.
55
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.CALL_PHONE" />
</manifest>
main.xml EditView
Call bCall. 4.2.
4.2. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number:"/>
<EditText android:id="@+id/textNumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="true"
android:editable="true"
android:singleLine="true"/>
</LinearLayout>
<Button android:id="@+id/bCall"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Call"/>
</LinearLayout>
PhoneCallActivity
onClick() Intent Extra-, URI .
PhoneCallActivity 4.3.
II.
56
4.3. PhoneCallActivity.java
package com.samples.telephony.phonecall;
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.content.Intent;
android.net.Uri;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.EditText;
android.widget.Toast;
4.
57
Android.
. 4.6.
.
. 5556.
"" Android
(5556) Call. : 5556, . 4.7.
. 4.6.
. 4.7.
ACTION_DIAL .
, . 5556 Android
, , . 4.4.
, ACTION_CALL. onClick() , Intent Intent.ACTION_DIAL Intent.ACTION_CALL,
4.4.
4.4. onClick() PhoneCallActivity
@Override
public void onClick(View arg0) {
try {
Uri uri = Uri.parse("tel:" + textNumber.getText().toString());
58
II.
startActivity(new Intent(Intent.ACTION_CALL, uri));
}
catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
Android 5554.
, , , (. 4.8).
. 4.8. 5556
,
.
, ,
BroadcastReceiver.
,
, BroadcastReceiver, onReceive(). :
Context Intent. Intent
4.
59
, , getExtras(). ,
:
public void onReceive(final Context context, final Intent intent) {
...
String phoneNumber = intent.getExtras().getString(
Intent.EXTRA_PHONE_NUMBER);
...
}
.
. IDE Eclipse
Android New Android
Project:
Project name: OutgoingCall;
Application name: Outgoing Call;
Package name: com.samples.outgoingcall;
Create Activity: ,
.
-
Ch04_OutgoingCall.
AndroidManifest.xml
Broadcast Receiver. <receiver>
android:name="OutgoingCallReceiver". -.
<receiver> Intent-, <intent-filter>. Intent- <action>
c android:name="android.intent.action.NEW_OUTGOING_CALL",
, ,
Broadcast Receiver.
,
PROCESS_OUTGOING_CALLS ,
4.5.
4.5. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.outgoingcall"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
II.
60
<receiver android:name="OutgoingCallReceiver">
<intent-filter>
<action android:name=
"android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
</receiver>
</application>
<uses-permission
android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-sdk android:minSdkVersion="9" />
</manifest>
android.content.BroadcastReceiver;
android.content.Context;
android.content.Intent;
android.widget.Toast;
Android.
5556 ( Android).
, , , . 4.9.
4.
61
. 4.9.
Android . ,
Android
, ,
.
,
Android, SMS- SMS- .
SMS
SMS
SMS
.
Android .
SMS
,
, .
DDMS Emulator Control
Telephony Actions Incoming Number
: 5554.
Voice/SMS SMS Message, . 5.1.
SMS. , SMS,
Emulator Control (. 5.2).
SMS
Messaging. New
message SMS-.
Android, (5554).
SMS- Message
Send. Android 5554
SMS- 5556 (. 5.3).
5. SMS
. 5.2. SMS-,
Android
. 5.3. SMS-
63
64
II.
SMS
Android SDK
SMS c SmsManager.
SmsManager, ,
SMS SMS-. SmsManager
SMS- .
TelephonyManager, , SmsManager getDefault(), :
SmsManager manager = SmsManager.getDefault();
SmsManager SMS-.
sendTextMessage().
:
destinationAddress SMS-;
scAddress SMS;
parts : ArrayList<string> String,
;
sentIntent PendingIntent ,
;
deliveryIntent PendingIntent ,
.
sentIntent
Activity.RESULT_OK
:
RESULT_ERROR_NO_SERVICE SMS ;
RESULT_ERROR_NULL_PDU PDU (Protocol Description Unit,
SMS-);
RESULT_ERROR_RADIO_OFF
(, Airplane Mode);
RESULT_ERROR_GENERIC_FAILURE -
SMS.
SMS- , sentIntent
deliveryIntent null.
SMS-,
SmsManager SMS ,
SMS, PendingIntent.
SmsManager sendTextMessage().
SMS- :
public class SendSmsActivity extends Activity {
...
SmsManager manager = SmsManager.getDefault();
PendingIntent intent = PendingIntent.getActivity(
5. SMS
65
SMS
SMS c sendDataMessage().
,
sendTextMessage().
destinationAddress scAddress , sendDataMessage(). :
destinationPort ;
data , ;
sentIntent PendingIntent
.
SMS
SMS 160 .
, ,
.
sendMultipartTextMessage().
sendTextMessage() ,
ArrayList<string> ArrayList<PendingIntent> sentIntent deliveryIntent.
sendMultipartTextMessage()
SMS-.
PendingIntent, SMS-.
SMS
SMS
, SMS :
RECEIVE_SMS ;
WRITE_SMS ;
SEND_SMS .
II.
66
, SMS
AndroidManifest.xml :
<uses-permission android:name="android.permission.SEND_SMS" />
SMS
, SMS-
. IDE Eclipse Android New Android Project:
Project name: SmsSender;
Application name: Send SMS;
Package name: com.samples.telephony.sendsms;
Create Activity: SendSmsActivity.
-
Ch05_SmsSender.
AndroidManifest.xml
SMS- : WRITE_SMS SEND_SMS. 5.1.
5.1. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.telephony.sendsms"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity
android:name=".SendSmsActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-sdk android:minSdkVersion="10" />
</manifest>
5. SMS
67
main.xml :
EditText number
;
EditText text -
;
Button Send bSend -
SMS;
TextView Number: Text:.
main.xml 5.2.
5.2. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number:"
android:layout_margin="5px"
android:textStyle="bold"/>
<EditText
android:id="@+id/number"
android:layout_width="150dip"
android:layout_height="wrap_content"
android:text=""
android:layout_margin="5px"/>
<Button
android:id="@+id/bSend"
android:layout_height="wrap_content"
android:layout_margin="5px"
android:layout_width="wrap_content"
android:text="Send"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent">
II.
68
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text:"
android:layout_margin="5px"
android:textStyle="bold"/>
<EditText
android:id="@+id/text"
android:text=""
android:layout_width="fill_parent"
android:layout_margin="5px"
android:layout_height="fill_parent"/>
</LinearLayout>
</LinearLayout>
SendSmsActivity onClick()
intent PendingIntent.getActivity(), sendTextMessage().
SendSmsActivity 5.3.
5.3. SendSmsActivity.java
package com.samples.telephony.sendsms;
import
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.app.PendingIntent;
android.content.Intent;
android.os.Bundle;
android.telephony.PhoneNumberUtils;
android.telephony.SmsManager;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.EditText;
android.widget.Toast;
EditText textSms;
EditText textNumber;
Button bSend;
SmsManager manager;
PendingIntent intent;
5. SMS
69
@Override
public void onCreate(final Bundle icicle) {
super.onCreate(icicle);
this.setContentView(R.layout.main);
textNumber = (EditText) findViewById(R.id.number);
textSms = (EditText) findViewById(R.id.text);
bSend = (Button) findViewById(R.id.bSend);
manager = SmsManager.getDefault();
bSend.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
String dest = textNumber.getText().toString();
try {
if (PhoneNumberUtils.isWellFormedSmsAddress(dest)) {
intent = PendingIntent.getActivity(
this, 0, new Intent(this, SendSmsActivity.class), 0);
manager.sendTextMessage("5556", null,
textSms.getText().toString(), intent, null);
Toast.makeText(SendSmsActivity.this,
"SMS sent", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(SendSmsActivity.this,
"Error formed SMS adress", Toast.LENGTH_LONG).show();
}
}
catch (Exception e) {
Toast.makeText(SendSmsActivity.this, e.toString(),
Toast.LENGTH_LONG).show();
}
}
}
Android.
: Number (
5556), Text Send.
, . 5.4.
70
II.
. 5.4. SMS
SMS-
SMS- SmsMessage.
SMS-:
getMessageBody() SMS- ;
getDisplayMessageBody() SMS- E-mail-.
SMS , getMessageBody();
getOriginatingAddress() null,
;
getDisplayOriginatingAddress() SMS
E-mail. SMS- ,
getOriginatingAddress();
getServiceCenterAddress() SMS;
getIndexOnIcc() ICC (Integrated
Circuit Card, . . SIM-);
getMessageClass() ;
getPdu() PDU (Protocol Data Unit)
. PDU SMS- GSM;
getProtocolIdentifier() Protocol Identifier,
PDU. SMS;
getStatus() SMS SMS-STATUSREPORT ( PDU);
getTimestampMillis() timestamp SMS
currentTimeMillis();
5. SMS
71
getUserData()
;
getStatusOnIcc() ICC ( SIM-).
, SmsManager:
STATUS_ON_ICC_READ , ;
STATUS_ON_ICC_UNREAD , ;
STATUS_ON_ICC_SEND ;
STATUS_ON_ICC_UNSENT ;
STATUS_ON_ICC_FREE , SIM-,
, .
, SMS ,
,
, .
SMS-
SMS- BroadcastReceiver.
SMS SMS , .
IDE Eclipse Android New Android Project:
Project name: SMSReceiver;
Application name: SMS Receiver;
Package name: com.samples.telephony.receiversms;
Create Activity: , . .
.
-
Ch05_SmsReceiver.
II.
72
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="9" />
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<receiver android:name="SmsReceiver">
<intent-filter>
<action
android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
</manifest>
java-, SmsReceiver.
BroadcastReceiver,
Broadcast Receiver. SmsReceiver
onReceive, BroadcastReceiver,
SMS.
SmsReceiver 5.5.
5.5. SmsReceiver.java
package com.samples.telephony.receiversms;
import
import
import
import
import
import
android.content.BroadcastReceiver;
android.content.Context;
android.content.Intent;
android.os.Bundle;
android.telephony.SmsMessage;
android.widget.Toast;
5. SMS
73
Android.
SMS-
, . . 5.5.
74
II.
. 5.5. SMS
SMS
SMS-, , , SMS. , , , URI.
SMS- URI SMS:
Inbox: content://sms/inbox;
Sent: content://sms/sent;
Draft: content://sms/draft;
Outbox: content://sms/outbox;
Failed: content://sms/failed;
Queued: content://sms/queued;
Undelivered: content://sms/undelivered;
Conversations: content://sms/conversations.
, .
SMS .
SMS
SMS-, URI, . , Cursor Inbox SMS :
Uri uri = Uri.parse("content://sms/inbox");
// Cursor,
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
startManagingCursor(cursor);
5. SMS
75
.
SMS, READ_SMS:
<uses-permission android:name="android.permission.READ_SMS"/>
, , SMS-, .
IDE Eclipse Android
New Android Project:
Project name: SmsFoldersInfo;
Application name: SMS folders Info;
Package name: com.samples.telephony.smsfoldersinfo;
Create Activity: SmsFolderInfoActivity.
-
Ch05_SmsFoldersInfo.
AndroidManifest.xml
android.permission.READ_SMS SMS.
, ,
Activity. (SmsFoldersListActivity)
SMS-, (SmsFolderInfoActivity) SMS.
5.6.
5.6. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.telephony.smsfoldersinfo"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".SmsFoldersListActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SmsFolderInfoActivity"
android:label="@string/app_name">
II.
76
</activity>
</application>
<uses-permission android:name="android.permission.READ_SMS"/>
</manifest>
, . .
android.R.layout.simple_list_item_1
.
SmsFoldersListActivity
SMS- . 5.7.
5.7. SmsFoldersListActivity.java
package com.samples.telephony.smsfoldersinfo;
import
import
import
import
import
import
android.app.ListActivity;
android.content.Intent;
android.os.Bundle;
android.view.View;
android.widget.ArrayAdapter;
android.widget.ListView;
5. SMS
77
SMS,
: , SMS, . c row.xml,
, .
row.xml 5.8.
5.8. SMS- row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_marginLeft="5px"/>
<TextView
android:id="@+id/body"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:paddingRight="10px"
android:layout_marginLeft="5px"/>
</LinearLayout>
android.app.ListActivity;
android.database.Cursor;
android.net.Uri;
android.os.Bundle;
android.widget.ListAdapter;
android.widget.SimpleCursorAdapter;
II.
78
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// URI
Bundle extras = this.getIntent().getExtras();
Uri uri = Uri.parse(extras.getString("uri"));
this.setTitle(uri.toString());
// Cursor,
Cursor cursor =
getContentResolver().query(uri, null, null, null, null);
startManagingCursor(cursor);
String[] columns = new String[] { "address", "body" };
int[] rows = new int[] { R.id.address, R.id.body };
ListAdapter adapter = new SimpleCursorAdapter(
this, R.layout.row, cursor, columns, rows);
setListAdapter(adapter);
}
}
Android.
SMS.
SMS .
SMS . 5.6.
5. SMS
79
SMS-
SMS : address body. ,
SMS-, . Android SDK public API Android.
SMS-
android.provider.Telephony.TextBasedSmsColumns.
:
_id SMS SMS MMS ;
thread_id ;
address ( ), ;
person SMS null, ;
date ( long);
protocol SMS;
read , , ;
status TP-Status 1, TP-Status . TP Transfer Protocol ( );
type ;
reply_path_present , , TP-Reply-Path
;
subject , subject E-mail;
body ;
service_center SMS, ;
locked ;
error_code , 0 , .
.
SMS Cursor, ,
SMS, getColumnName() Cursor.
, SMS
:
Cursor cursor;
...
cursor = getContentResolver().query(uri, null, null, null, null);
startManagingCursor(cursor);
...
// ,
//
cursor.moveToPosition(pos);
// StringBuilder,
//
StringBuilder data = new StringBuilder();
II.
80
// ,
for (int i = 0; i < cursor.getColumnCount(); i++) {
data.append(cursor.getColumnName(i) + ":\t" +
cursor.getString(i) + "\n");
}
SMS,
, ,
SMS-.
-
Ch05_SmsFoldersInfoDetails.
SmsFolderInfoActivity onListItemClick(),
SMS .
SmsFolderInfoActivity 5.10.
5.10. SmsFolderInfoActivity.java
package com.samples.telephony.smsfoldersdetailsinfo;
import
import
import
import
import
import
import
import
import
import
android.app.AlertDialog;
android.app.ListActivity;
android.content.DialogInterface;
android.database.Cursor;
android.net.Uri;
android.os.Bundle;
android.view.View;
android.widget.ListAdapter;
android.widget.ListView;
android.widget.SimpleCursorAdapter;
5. SMS
81
this.setTitle(uri.toString());
// Cursor,
cursor = getContentResolver().query(uri, null, null, null, null);
startManagingCursor(cursor);
String[] columns = new String[] { "address", "body" };
int[] rows = new int[] { R.id.address, R.id.body };
ListAdapter adapter = new SimpleCursorAdapter(
this, R.layout.row, cursor, columns, rows);
setListAdapter(adapter);
}
public void onListItemClick(ListView parent, View v, int pos, long id)
{
//
cursor.moveToPosition(pos);
StringBuilder data = new StringBuilder();
// Cursor StringBuilder
for (int i = 0; i < cursor.getColumnCount(); i++) {
data.append(cursor.getColumnName(i) + ":\t" +
cursor.getString(i) + "\n");
}
//
// SMS-
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("SMS Details");
builder.setMessage(data.toString());
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
});
builder.show();
}
}
II.
82
. 5.7. SMS
Android
SMS-, , .
SMS- SmsManager SmsMessage android.telephony.
SMS-
SMS, .
, .
,
Wi-Fi.
III
, ,
.
Android .
Android SDK , WebKit . .
Android
Java, java.net. , Android : android.net android.net.http, .
,
,
.
ConnectivityManager android.net. ,
.
ConnectivityManager
getSystemService() Context Context.CONNECTIVITY_SERVICE:
ConnectivityManager manager = (ConnectivityManager)getSystemService(
Context.CONNECTIVITY_SERVICE);
ConnectivityManager
:
getActiveNetworkInfo();
getNetworkInfo(int networkType);
getAllNetworkInfo().
III.
86
, getAllNetworkInfo(), NetworkInfo.
getAllNetworkInfo() NetworkInfo.
NetworkInfo , , .
NetworkInfo . :
getType() , .
ConnectivityManager:
TYPE_MOBILE ( ), TYPE_WIFI ( Wi-Fi) . .;
getSubtype() , ;
getTypeName() , , "WIFI" "MOBILE";
getSubtypeName() .
NetworkInfo :
isAvailable() . true, ;
isConnectedOrConnecting() true,
;
isConnected() true, ;
isRoaming() true,
.
Android, .
, , .
IDE Eclipse Android New Android Project:
Project name: NetworkStateInfo;
Application name: Network state info;
Package name: com.samples.network.networkstateinfo;
Create Activity: NetworkStateInfoActivity.
-
Ch06_NetworkStateInfo.
6.
87
TextView .
ConnectivityManager. , getAllNetworkInfo(), NetworkInfo,
.
NetworkStateInfoActivity
6.2.
6.2. NetworkStateInfoActivity.java
package com.samples.network.networkstateinfo;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
III.
88
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.TextView;
Android. . 6.1.
. 6.1.
6.
89
,
, Android 5 ,
, Wi-Fi, . , Android. Wi-Fi ,
.
,
, , , .
.
Android SDK
TrafficStats android.net. TrafficStats ,
.
, , TrafficStats :
getMobileRxBytes() ,
;
getMobileRxPackets() ,
;
getMobileTxBytes() ,
;
getMobileTxPackets() ,
.
TrafficStats , , , , , Wi-Fi.
TrafficStats :
getTotalRxBytes() ,
;
getTotalRxPackets() ,
;
getTotalTxBytes() ,
;
getTotalTxPackets() , .
III.
90
, .
TrafficStats
:
getUidRxBytes() , UID;
getUidTxBytes() , UID.
.
, , , , , . . ,
,
, .
, TrafficStats
. IDE Eclipse Android
New Android Project:
Project name: TrafficStatsInfo;
Application name: Network Traffic info;
Package name: com.samples.network.trafficstatsinfo;
Create Activity: TrafficStatsActivity.
-
Ch06_TrafficStatsInfo.
AndroidManifest.xml
android.permission.INTERNET
(
, . 6.1).
TrafficStatsActivity
TrafficStats. TrafficStatsActivity 6.3.
android.permission.ACCESS_NETWORK_STATE
6.3. TrafficStatsActivity.java
package com.samples.network.trafficstatsinfo;
import
import
import
import
android.app.Activity;
android.net.TrafficStats;
android.os.Bundle;
android.widget.TextView;
6.
91
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView text = (TextView)findViewById(R.id.text);
text.append("Total:");
text.append("\n\tRX Bytes:\t" +
text.append("\n\tRX Packets:\t"
text.append("\n\tTX Bytes:\t" +
text.append("\n\tTX Packets:\t"
TrafficStats.getTotalRxBytes());
+ TrafficStats.getTotalRxPackets());
TrafficStats.getTotalTxBytes());
+ TrafficStats.getTotalTxPackets());
text.append("\nMobile:");
text.append("\n\tRX Bytes:\t" + TrafficStats.getMobileRxBytes());
text.append("\n\tRX Packets:\t" +
TrafficStats.getMobileRxPackets());
text.append("\n\tTX Bytes:\t" + TrafficStats.getMobileTxBytes());
text.append("\n\tTX Packets:\t" +
TrafficStats.getMobileTxPackets());
}
}
Android. . 6.2.
. 6.2.
III.
92
, , , .
Android WebKit.
- Android , , , .
, . . 6.3 -
.
. 6.3.
- WebKit , , ,
. , .
6.
93
WebView
. WebView android.webkit. ,
- .
WebView -. WebView WebKit - , , ,
, -.
WebView
WebView loadUrl().
loadUrl().
URL - URL.
loadUrl() - URL, , , .
WebView -. IDE Eclipse
Android New Android
Project:
Project name: WebKit;
Application name: WebKit browser;
Package name: com.samples.network.webkit;
Create Activity: WebKitActivity.
-
Ch06_WebKit.
AndroidManifest.xml
android.permission.INTERNET.
6.4.
6.4. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.network.webkit"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
III.
94
<activity android:name=".WebKitActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk android:minSdkVersion="10" />
</manifest>
main.xml
WebView. main.xml 6.5.
6.5. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView
android:id="@+id/browser"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
URL, ,
, Google.
WebKitActivity 6.6.
loadUrl()
6.6. WebKitActivity.java
package com.samples.network.webkit;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class WebKitActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
6.
95
setContentView(R.layout.main);
WebView myBrowser=(WebView)findViewById(R.id.browser);
myBrowser.getSettings().setJavaScriptEnabled(true);
String url = "http://google.com";
myBrowser.loadUrl(url);
}
}
. 6.4. WebView
WebView
WebView . WebView :
loadData();
loadDataWithBaseURL().
III.
96
loadData() ,
, MIME . , WebView:
WebView webKit;
...
String html "<html><body><h3>This is web page content</h3></body></html>";
webKit.loadData(html, "text/html", "UTF-8");
-
Ch06_WebKit_v2.
6.7. WebKitActivity.java
package com.samples.web.webkit2;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class WebKitActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView webKit = (WebView)findViewById(R.id.browser);
String html = "<html><body>" +
"<a href=\"http://translate.google.com/?hl=en&tab=iT#\">" +
"Go to Google Translate Service</a></body></html>";
webKit.loadData(html, "text/html", "UTF-8");
}
}
Android.
- Google Translate Service,
-, . 6.5.
6.
97
. 6.5. WebView
WebView JavaScript
, ,
.
WebSettings.
WebView:
: setTextSize()
setFixedFontFamily(), setCursiveFontFamily(), setMinimumLogicalFontSize(),
setMinimumFontSize(), setDefaultFixedFontSize(), setDefaultFontSize();
: setDefaultZoom(), setDisplayZoomControls(), setBuiltInZoomControls(), setSupportZoom();
: setCacheMode(), setAppCachEnabled() . .
,
Preference, .
, , WebView, .
IDE Eclipse Android New Android Project:
Project name: WebKitSettings;
Application name: Browser with menu;
III.
98
-
Ch06_WebKitSettings.
:
URL bar / URL;
Reload ;
Back ;
Forward ;
Settings ;
Exit .
. , :
URL ;
;
JavaScript ;
.
AndroidManifest.xml
android.permission.INTERNET. , , WebKitPreferencesActivity. <activity>
android:name=".WebKitPreferencesActivity".
AndroidManifest.xml 6.8.
6.8. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.web.webkitmenu"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".WebKitActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
6.
99
<activity android:name=".WebKitPreferencesActivity"
android:label="@string/app_name">
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk android:minSdkVersion="10" />
</manifest>
main.xml,
EditText URL URL .
main.xml 6.9.
WebView,
6.9. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="@+id/url_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:layout_gravity="center">
<EditText
android:id="@+id/text_url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="http://" android:layout_gravity="center"/>
<Button
android:id="@+id/button_load"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tx_load"
android:layout_gravity="center"/>
</LinearLayout>
<WebView
android:id="@+id/browser"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
III.
100
, strings.xml, res/values/.
strings.xml 6.10.
6.10. strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Browser with menu</string>
<string name="tx_url">URL:</string>
<string name="tx_load">Load</string>
<string
<string
<string
<string
<string
<string
name="mn_urlbar">URL bar</string>
name="mn_back"><<</string>
name="mn_refresh">Reload</string>
name="mn_forward">>></string>
name="mn_pref">Settings</string>
name="mn_exit">Exit</string>
<string name="hd_options">Options</string>
<string name="pk_url">url</string>
<string name="pr_url">Startup URL</string>
<string name="sm_url">Set startup URL</string>
<string name="pk_images">images</string>
<string name="pr_images">Load images</string>
<string name="sm_images">
Enable/disable images for faster page loading</string>
<string name="hd_security">Security</string>
<string name="pk_jscript">jscript</string>
<string name="pr_jscript">Enable Java Script</string>
<string name="sm_jscript">Enable/disable Java Script in browser</string>
<string name="pk_popup">popup</string>
<string name="pr_popup">Block pop-up windows</string>
<string name="sm_popup">
Enable/disable pop-up windows in browser</string>
</resources>
WebKitActivity , , onResume().
6.
WebKitActivity 6.11.
6.11. WebKitActivity.java
package com.samples.web.webkitmenu;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.content.Intent;
android.content.SharedPreferences;
android.os.Bundle;
android.preference.PreferenceManager;
android.view.Menu;
android.view.MenuItem;
android.view.View;
android.webkit.WebSettings;
android.webkit.WebView;
android.webkit.WebViewClient;
android.widget.Button;
android.widget.EditText;
android.widget.LinearLayout;
android.widget.TableLayout;
android.widget.Toast;
LinearLayout layoutBar;
WebView browser;
EditText textUrl;
Button buttonUrl;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layoutBar
browser =
textUrl =
buttonUrl
= (LinearLayout)findViewById(R.id.url_bar);
(WebView)findViewById(R.id.browser);
(EditText)findViewById(R.id.text_url);
= (Button)findViewById(R.id.button_load);
buttonUrl.setOnClickListener(buttonUrlOnClick);
101
III.
102
browser.setWebViewClient(new WebViewClient());
}
@Override
public void onResume() {
super.onResume();
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(this);
//
String url = prefs.getString(getString(R.string.pk_url), "http://");
browser.loadUrl(url);
//
boolean allowImages =
prefs.getBoolean(getString(R.string.pk_images), true);
// Java-
boolean allowJScript =
prefs.getBoolean(getString(R.string.pk_jscript), true);
//
boolean allowPopup =
prefs.getBoolean(getString(R.string.pk_popup), false);
//
WebSettings settings = browser.getSettings();
settings.setBlockNetworkImage(allowImages);
settings.setJavaScriptEnabled(allowJScript);
settings.setJavaScriptCanOpenWindowsAutomatically(allowPopup);
textUrl.setText(url);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, IDM_URLBAR, 0, R.string.mn_urlbar);
menu.add(0, IDM_SETTINGS, 0, R.string.mn_pref);
menu.add(0, IDM_EXIT, 0, R.string.mn_exit);
menu.add(0, IDM_BACK, 0, R.string.mn_back);
menu.add(0, IDM_REFRESH, 0, R.string.mn_refresh);
menu.add(0, IDM_FORWARD, 0, R.string.mn_forward);
return super.onCreateOptionsMenu(menu);
}
6.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case IDM_URLBAR:
if (layoutBar.getVisibility() == View.VISIBLE) {
layoutBar.setVisibility(View.GONE);
}
else {
layoutBar.setVisibility(View.VISIBLE);
}
break;
case IDM_REFRESH:
browser.reload();
break;
case IDM_BACK:
if(browser.canGoBack())
browser.goBack();
break;
case IDM_FORWARD:
if(browser.canGoForward())
browser.goForward();
break;
case IDM_SETTINGS:
Intent i = new Intent();
i.setClass(this, WebKitPreferencesActivity.class);
startActivity(i);
break;
case IDM_EXIT:
this.finish();
break;
}
return true;
}
private Button.OnClickListener buttonUrlOnClick =
new Button.OnClickListener() {
@Override
public void onClick(View v) {
browser.loadUrl(textUrl.getText().toString());
}
};
}
103
III.
104
XML-
. res/xml/. xml Android IDE Eclipse ,
XML- preferences.xml.
preferences.xml . 6.12.
6.12. preferences.xml
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="@string/hd_options">
<EditTextPreference
android:key="@string/pk_url"
android:title="@string/pr_url"
android:summary="@string/sm_url"
android:defaultValue="http://"
android:dialogTitle="@string/pr_url"/>
<CheckBoxPreference
android:key="@string/pk_images"
android:title="@string/pr_images"
android:summary="@string/sm_images"
android:defaultValue="true"/>
</PreferenceCategory>
<PreferenceCategory
android:title="@string/hd_security">
<CheckBoxPreference
android:key="@string/pk_jscript"
android:title="@string/pr_jscript"
android:summary="@string/sm_jscript"
android:defaultValue="true"/>
<CheckBoxPreference
android:key="@string/pk_popup"
android:title="@string/pr_popup"
android:summary="@string/sm_popup"
android:defaultValue="false"/>
</PreferenceCategory>
</PreferenceScreen>
WebKitPreferencesActivity . PreferenceActivity,
6.
105
onCreate(),
addPreferencesFromResource()
.
6.13.
6.13.
WebKitPreferencesActivity.java
package com.samples.web.webkitmenu;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class WebKitPreferencesActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Android. . 6.6.
. 6.6. WebView
106
III.
. 6.7.
Settings , . 6.7.
, Android, . , Android, .
Wi-Fi , Wi-Fi.
Wi-Fi-
Wi-Fi
Android.
, Wi-Fi-,
.
Wi-Fi- .
Ad-hoc,
, Wi-Fi.
Wi-Fi
Wi-Fi Android SDK android.net.wifi. WifiManager
Wi-Fi-
.
Wi-Fi-
WifiManager, ,
getSystemService():
WifiManager manager = getSystemService(Context.WIFI_SERVICE);
WifiManager Wi-Fi-,
, Wi-Fi.
WifiManager
Wi-Fi-,
.
III.
108
, , c
Wi-Fi :
ACCESS_WIFI_STATE Wi-Fi;
CHANGE_WIFI_STATE Wi-Fi.
WifiManager
setWifiEnabled(). , ,
true :
manager.setWifiEnabled(true);
false
manager.setWifiEnabled(false);
WifiManager
. Wi-Fi :
WIFI_STATE_ENABLING;
WIFI_STATE_ENABLED;
WIFI_STATE_DISABLING;
WIFI_STATE_DISABLED;
WIFI_STATE_UNKNOWN.
,
WIFI_STATE_ENABLING WIFI_STATE_DISABLING
Wi-Fi, . . .
Wi-Fi
. ,
Wi-Fi Intent.
Intent WifiManager:
WIFI_STATE_CHANGED_ACTION Broadcast Intent, Wi-Fi-. . Extra- EXTRA_WIFI_STATE .
Extra- EXTRA_PREVIOUS_WIFI_STATE
, ;
NETWORK_STATE_CHANGED_ACTION Broadcast Intent, . Extra- EXTRA_NETWORK_INFO
7. Wi-Fi-
109
NetworkInfo. , Extra-
EXTRA_BSSID BSSID Wi-Fi. BSSID
(Basic Service Set Identifier) Wi-Fi,
;
SUPPLICANT_CONNECTION_CHANGE_ACTION Broadcast Intent, , : ( Wi-Fi)
. Extra- EXTRA_SUPPLICANT_CONNECTED ;
SUPPLICANT_STATE_CHANGED_ACTION Broadcast Intent,
(, ). SupplicantState,
. Extra-: EXTRA_NEW_STATE, ,
EXTRA_SUPPLICANT_ERROR, .
, Wi-Fi :
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int wifiState = intent.getIntExtra(
WifiManager.EXTRA_WIFI_STATE,
WifiManager.EXTRA_PREVIOUS_WIFI_STATE);
switch(wifiState){
case WifiManager.WIFI_STATE_ENABLING:
...
break;
case WifiManager.WIFI_STATE_ENABLED:
...
break;
case WifiManager.WIFI_STATE_DISABLING:
...
break;
case WifiManager.WIFI_STATE_DISABLED:
...
break;
case WifiManager.WIFI_STATE_UNKNOWN:
...
break;
}
}
}
III.
110
Wi-Fi, registerReceiver() :
registerReceiver(
receiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
unregisterReceiver(),
BroadcastReceiver:
unregisterReceiver(receiver);
Wi-Fi
, Wi-Fi-
.
, Android Wi-Fi-,
. ,
WI-Fi .
-
Ch07_ManageWiFiConnection.
AndroidManifest.xml
android.permission.CHANGE_WIFI_STATE. 7.1.
7.1. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.network.wifimanagement"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name="WiFiChangeActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
7. Wi-Fi-
111
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
<uses-permission
android:name="android.permission.CHANGE_WIFI_STATE" />
</manifest>
main.xml
.
main.xml 7.2.
7.2. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<Button
android:id="@+id/bEnable"
android:layout_height="wrap_content"
android:text="Enable Wi-Fi"
android:layout_width="fill_parent"
android:layout_weight="1"
android:layout_margin="5px"/>
<Button
android:id="@+id/bDisable"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="Disable Wi-Fi"
android:layout_weight="1"
android:layout_margin="5px"/>
</LinearLayout>
<TextView
android:id="@+id/text"
III.
112
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_margin="5px"/>
</LinearLayout>
WiFiChangeActivity
BroadcastReceiver Wi-Fi.
onClick() .
WiFiChangeActivity 7.3.
7.3. WiFiChangeActivity.java
package com.samples.network.wifimanagement;
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.content.BroadcastReceiver;
android.content.Context;
android.content.Intent;
android.content.IntentFilter;
android.net.wifi.WifiManager;
android.os.Bundle;
android.view.View;
android.widget.Button;
android.widget.TextView;
7. Wi-Fi-
case WifiManager.WIFI_STATE_ENABLED:
text.append("Wi-Fi state enabled");
break;
case WifiManager.WIFI_STATE_DISABLING:
text.append("Wi-Fi state disabling");
break;
case WifiManager.WIFI_STATE_DISABLED:
text.append("Wi-Fi state disabled");
break;
case WifiManager.WIFI_STATE_UNKNOWN:
text.append("Wi-Fi state unknown");
break;
default:
text.append("Not defined");
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.text);
Button bEnable = (Button)findViewById(R.id.bEnable);
Button bDisable = (Button)findViewById(R.id.bDisable);
text.append("Current Wi-Fi state:");
bEnable.setOnClickListener(this);
bDisable.setOnClickListener(this);
manager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
//
//
this.registerReceiver(this.receiver,
new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bEnable:
// Wi-Fi
113
III.
114
manager.setWifiEnabled(true);
text.append("\nStart enable Wi-Fi...");
break;
case R.id.bDisable:
// Wi-Fi
manager.setWifiEnabled(false);
text.append("\nStart disable Wi-Fi...");
break;
}
}
}
, Wi-Fi,
.
Wi-Fi- Enable Wi-Fi Disable Wi-Fi.
. 7.1.
. 7.1. , Wi-Fi-
Android Wi-Fi-,
Wi-Fi. , ,
Wi-Fi-, ,
.
, .
,
Wi-Fi (. 7.2).
7. Wi-Fi-
115
. 7.2. Wi-Fi
Android
Android
, , Wi-Fi.
.
Wi-Fi-
Android Activity Wi-Fi-. Settings :
ACTION_WIFI_SETTINGS /
Wi-Fi-, ;
ACTION_WIFI_IP_SETTINGS IP-,
;
ACTION_WIRELESS_SETTINGS : Wi-Fi, Bluetooth, .
, WifiManger ACTION_PICK_WIFI_NETWORK, ACTION_WIFI_SETTINGS
Settings.
Activity Intent:
Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
startActivity(intent);
III.
116
, .
.
IDE Eclipse Android New Android Project:
Project name: WiFiSettings;
Application name: Standard WiFi Settings;
Package name: com.samples.network.wifisettings;
Create Activity: WiFiChangeActivity.
-
Ch07_WiFiSettings.
AndroidManifest.xml
7.1 .
main.xml , . .
, ListActivity.
WiFiSettingsActivity 7.4.
android.permission.CHANGE_WIFI_STATE,
7.4. WiFiSettingsActivity.java
package com.samples.network.wifisettings;
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.app.ListActivity;
android.content.Intent;
android.os.Bundle;
android.provider.Settings;
android.view.View;
android.widget.ArrayAdapter;
android.widget.ListView;
android.widget.Toast;
7. Wi-Fi-
117
android.R.layout.simple_list_item_1, actions));
}
catch (Exception e) {
Toast.makeText(this, e.toString(), 3000).show();
}
}
public void onListItemClick(ListView parent, View v, int pos, long id)
{
try {
Intent intent = new Intent(actions[pos]);
startActivity(intent);
}
catch (Exception e) {
Toast.makeText(this, e.toString(), 3000).show();
}
}
}
. 7.3. Wi-Fi-
,
saveConfiguration() .
118
III.
, Wi-Fi-.
Wi-Fi . .
SSID (Service Set Identifier). ,
SSID. ,
. SSID
32 .
Wi-Fi .
SSID,
.
WifiInfo :
getSSID() Wi-Fi.
SSID;
getBSSID() BSSID (Basic Service Set Identifier,
) . BSSID
, ,
.
WifiInfo getRssi() RSSI (. 3, " ") getLinkSpeed(), . LINK_SPEED_UNITS
WifiInfo, "Mbps".
IP-
IP-, DHCP
Wi-Fi,
, getDhcpInfo() WifiManager.
getDhcpInfo() DhcpInfo android.net.
DhcpInfo , :
ipAddress;
gateway;
dns1;
dns2;
netmask;
serverAddress.
, integer,
IP-
.
7. Wi-Fi-
119
Wi-Fi
.
Wi-Fi . IDE Eclipse Android
New Android Project:
Project name: WiFiInfo;
Application name: Wi-Fi info;
Package name: com.samples.network.wifiinfo;
Create Activity: WiFiInfoActivity.
-
Ch07_WiFiInfo.
AndroidManifest.xml
ACCESS_NETWORK_STATE, CHANGE_WIFI_STATE ACCESS_WIFI_STATE, -
7.5.
7.5. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.network.wifiinfo"
android:versionCode="1"
android:versionName="1.0">
III.
120
main.xml
CheckBox cbEnable
TextView text Wi-Fi-.
main.xml 7.6.
7.6. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<CheckBox
android:id="@+id/cbEnable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enable Wi-Fi"
android:layout_margin="5px"
android:textSize="18sp"/>
<TextView
android:id="@+id/text"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_margin="5px"/>
</LinearLayout>
WiFiInfoActivity printWifiInfo(),
( WIFI_STATE_ENABLED).
WiFiInfoActivity 7.7.
7.7. WiFiInfoActivity.java
package com.samples.network.wifiinfo;
import
import
import
import
android.app.Activity;
android.content.BroadcastReceiver;
android.content.Context;
android.content.Intent;
7. Wi-Fi-
import
import
import
import
import
import
import
import
import
android.content.IntentFilter;
android.net.DhcpInfo;
android.net.wifi.WifiInfo;
android.net.wifi.WifiManager;
android.os.Bundle;
android.widget.CheckBox;
android.widget.CompoundButton;
android.widget.TextView;
android.widget.CompoundButton.OnCheckedChangeListener;
121
III.
122
7. Wi-Fi-
123
= ipAddress / 0x1000000;
= ipAddress % 0x1000000;
= tmp / 0x10000;
%= 0x10000;
= tmp / 0x100;
= tmp % 0x100;
Android.
. 7.4.
. 7.4. Wi-Fi-
Wi-Fi-
WifiConfiguration.
getConfiguredNetworks().
List<WifiConfiguration>:
WifiManager
manager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> configs = manager.getConfiguredNetworks();
III.
124
WifiConfiguration , Wi-Fi:
SSID SSID;
BSSID BSSID;
hiddenSSID SSID.
, , ;
networkId , ,
, ;
status ;
priority ,
, Wi-Fi.
WifiConfiguration ,
:
allowedProtocols()
;
allowedAuthAlgorithms() ;
allowedGroupCiphers()
;
allowedKeyManagement()
;
wepKeys() WEP (Wired Equivalent Privacy,
Wi-Fi). 4 ;
wepTxKeyIndex() WEP .
0 3, ;
allowedPairwiseCiphers() WPA. WPA (Wi-Fi Protected Access,
Wi-Fi) WEP. WPA AES (Advanced Encryption Standard, );
preSharedKey() WPA
Pre-Shared Key (WPA-PSK).
, Wi-Fi . IDE Eclipse Android
New Android Project:
Project name: WiFiConfiguration;
Application name: Wi-Fi configuration;
Package name: com.samples.network.wificonfig;
Create Activity: WifiConfigActivity.
-
Ch07_WiFiConfiguration.
7. Wi-Fi-
125
AndroidManifest.xml
, 7.5.
main.xml , 7.6.
WifiConfigActivity WIFI_STATE_ENABLED
. WifiConfigActivity
printWifiConfig(),
Wi-Fi ( 7.8).
7.8. WifiConfigActivity.java
package com.samples.network.wificonfig;
import java.util.List;
import
import
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.content.BroadcastReceiver;
android.content.Context;
android.content.Intent;
android.content.IntentFilter;
android.net.wifi.WifiConfiguration;
android.net.wifi.WifiManager;
android.os.Bundle;
android.widget.CheckBox;
android.widget.CompoundButton;
android.widget.TextView;
android.widget.CompoundButton.OnCheckedChangeListener;
III.
126
case WifiManager.WIFI_STATE_ENABLED:
text.setText("Wi-Fi state enabled");
//
printWifiConfig();
break;
case WifiManager.WIFI_STATE_DISABLING:
text.setText("Wi-Fi state disabling");
break;
case WifiManager.WIFI_STATE_DISABLED:
text.setText("Wi-Fi state disabled");
break;
case WifiManager.WIFI_STATE_UNKNOWN:
text.setText("Wi-Fi state unknown");
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.text);
cbEnable = (CheckBox)findViewById(R.id.cbEnable);
manager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
this.registerReceiver(this.receiver,
new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
cbEnable.setChecked(manager.isWifiEnabled());
cbEnable.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
//
manager.setWifiEnabled(isChecked);
}
//
private void printWifiConfig() {
List<WifiConfiguration> configs = manager.getConfiguredNetworks();
for (WifiConfiguration config : configs) {
7. Wi-Fi-
127
.
. 7.5.
. 7.5. Wi-Fi
III.
128
Wi-Fi. SSID,
, 100 .
, .
startScan().
ScanResult.
, .
:
SSID, BSSID Wi-Fi;
apabilities , ,
. , : "[WPA-PSK-CCMP]";
frequency MHz;
level dBm.
,
Intent. , BroadcastReceiver.
IntentFilter
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION
BroadcastReceiver registerReceiver(), , :
WifiManager manager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
IntentFilter filter = new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(this.scanReceiver,
new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
, startScan()
WifiManager :
manager.startScan();
BroadcastReceiver,
Wi-Fi, onReceive(),
, getScanResults() WifiManager:
BroadcastReceiver scanReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent) {
List<ScanResult> results = manager.getScanResults();
for (ScanResult result : results) {
7. Wi-Fi-
129
//
...
}
}
}
.
IDE Eclipse Android
New Android Project:
Project name: ScanWifiAccessPoint;
Application name: Scan Wi-Fi network;
Package name: com.samples.network.scanwifi;
Create Activity: WiFiScanActivity.
-
Ch07_ScanWifiAccessPoint.
AndroidManifest.xml
, .
main.xml, CheckBox
TextView, android:id="@+id/bStart
Scan Wi-Fi . main.xml
7.9.
7.9. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout1"
android:orientation="horizontal"
android:gravity="left|center">
<CheckBox
android:textSize="18sp"
android:layout_height="wrap_content"
android:id="@+id/cbEnable"
android:layout_margin="5px"
android:layout_width="wrap_content"
android:text="Enable Wi-Fi"/>
III.
130
<Button
android:id="@+id/bStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5px"
android:layout_weight="1"
android:text="Scan Wi-Fi"/>
</LinearLayout>
<TextView
android:id="@+id/text"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_margin="5px"/>
</LinearLayout>
scanReceiver. .
Scan Wi-Fi .
WiFiScanActivity 7.10.
BroadcastReceiver,
7.10. WiFiScanActivity.java
package com.samples.network.scanwifi;
import java.util.List;
import
import
import
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.content.BroadcastReceiver;
android.content.Context;
android.content.Intent;
android.content.IntentFilter;
android.net.wifi.ScanResult;
android.net.wifi.WifiManager;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.CheckBox;
android.widget.CompoundButton;
7. Wi-Fi-
131
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class WiFiScanActivity extends Activity
implements OnCheckedChangeListener, OnClickListener {
private TextView text;
private CheckBox cbEnable;
private Button bStart;
private WifiManager manager;
//
private BroadcastReceiver receiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN);
switch(wifiState){
case WifiManager.WIFI_STATE_ENABLING:
text.setText("Wi-Fi state enabling");
break;
case WifiManager.WIFI_STATE_ENABLED:
text.setText("Wi-Fi state enabled.");
break;
case WifiManager.WIFI_STATE_DISABLING:
text.setText("Wi-Fi state disabling");
break;
case WifiManager.WIFI_STATE_DISABLED:
text.setText("Wi-Fi state disabled");
break;
case WifiManager.WIFI_STATE_UNKNOWN:
text.setText("Wi-Fi state unknown");
break;
}
}
};
//
private BroadcastReceiver scanReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
List<ScanResult> results = manager.getScanResults();
text.setText("Scan result: " + results.size() + " points");
//
for (ScanResult result : results) {
III.
132
.
Scan Wi-Fi , Wi-Fi
, . 7.6.
7. Wi-Fi-
133
. 7.6.
.
, Wi-Fi,
Wi-Fi,
.
Wi-Fi. BroadcastReceiver
onReceive():
BroadcastReceiver rssiReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
WifiInfo info = manager.getConnectionInfo();
...
}
};
, getRssi(),
getLinkSpeed(). 7.7, . getRssi() RSSI ,
III.
134
.
WifiManager :
calculateSignalLevel() ;
compareSignalLevel() .
calculateSignalLevel() :
, WifiInfo.getRssi(), ,
(
), :
WifiManager.calculateSignalLevel(info.getRssi(), 5));
5 :
calculateSignalLevel() 5,
. .
getLinkSpeed().
. IDE Eclipse Android New Android Project:
Project name: MonitoringRSSI;
Application name: Monitoring RSSI;
Package name: com.samples.network.monitoringrssi;
Create Activity: MonitoringRssiActivity.
-
Ch07_MonitoringRSSI.
AndroidManifest.xml
.
MonitoringRssiActivity
WifiConfigActivity 7.8 WiFiConfiguration,
, rssiReceiver BroadcastReceiver. (
: , ). onReceive() rssiReceiver
.
MonitoringRssiActivity 7.11.
7.11. MonitoringRssiActivity.java
package com.samples.network.monitoringrssi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
7. Wi-Fi-
import
import
import
import
import
import
import
import
import
135
android.content.Intent;
android.content.IntentFilter;
android.net.wifi.WifiInfo;
android.net.wifi.WifiManager;
android.os.Bundle;
android.widget.CheckBox;
android.widget.CompoundButton;
android.widget.TextView;
android.widget.CompoundButton.OnCheckedChangeListener;
switch(wifiState){
case WifiManager.WIFI_STATE_ENABLING:
text.setText("Wi-Fi state enabling");
break;
case WifiManager.WIFI_STATE_ENABLED:
text.setText("Wi-Fi state enabled");
//
startMonitoringRssi();
break;
case WifiManager.WIFI_STATE_DISABLING:
text.setText("Wi-Fi state disabling");
break;
case WifiManager.WIFI_STATE_DISABLED:
text.setText("Wi-Fi state disabled");
//
stopMonitoringRssi();
break;
case WifiManager.WIFI_STATE_UNKNOWN:
text.setText("Wi-Fi state unknown");
break;
}
};
//
private BroadcastReceiver rssiReceiver = new BroadcastReceiver(){
III.
136
@Override
public void onReceive(Context context, Intent intent) {
WifiInfo info = manager.getConnectionInfo();
// ,
//
text.append("\nChange signal in " + info.getSSID());
text.append("\n\tSignal level:\t" +
WifiManager.calculateSignalLevel(info.getRssi(), 5));
text.append("\n\tLink speed:\t" + info.getLinkSpeed() +
" " + WifiInfo.LINK_SPEED_UNITS);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.text);
cbEnable = (CheckBox)findViewById(R.id.cbEnable);
manager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
this.registerReceiver(this.receiver,
new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
cbEnable.setChecked(manager.isWifiEnabled());
cbEnable.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
manager.setWifiEnabled(isChecked);
}
//
private void startMonitoringRssi() {
this.registerReceiver(rssiReceiver,
new IntentFilter(WifiManager.RSSI_CHANGED_ACTION));
}
//
private void stopMonitoringRssi() {
if (this.rssiReceiver.isInitialStickyBroadcast())
this.unregisterReceiver(rssiReceiver);
}
}
7. Wi-Fi-
137
.
, . . , , .
WI-Fi-
. 7.7.
. 7.7. Wi-Fi-
Wi-Fi . ,
Wi-Fi , ,
Wi-Fi.
:
Google Maps Geocoding.
IV
, , .
,
Android SDK . Android
API, ,
.
Google API
Android Google API. Android Virtual Device Google API, , . 8.1.
Android Virtual Device Google API ,
.
LocationManager ,
, .
142
IV.
.
GPS (Global Positioning
System) ,
. GPS,
, , GPS:
Galileo .
.
.
GPS, Android
,
.
8.
143
Wi-Fi-. ,
, . LocationManager
: GPS_PROVIDER NETWORK_PROVIDER.
,
, , LocationManager
:
getProvider() LocationProvider (
), ,
. ;
getAllProviders() ;
getProviders() .
enabledOnly,
, ;
getProviders(Criteria criteria, boolean enabledOnly) , . Criteria,
.
LocationProvider.
:
getName() ;
getAccuracy() , ;
getPowerRequirement() ,
;
hasMonetaryCost() true,
;
meetsCriteria() true, , ;
requiresCell() true,
, ;
requiresNetwork() true, ;
requiresSatellite() true, , GPS;
supportsAltitude() true, ;
supportsSpeed() true,
.
Criteria, ( : -
IV.
144
, ) . Criteria
,
,
.
,
,
ACCESS_FINE_LOCATION GPS_PROVIDER ACCESS_COARSE_LOCATION.
ACCESS_COARSE_LOCATION
, NETWORK_PROVIDER. ACCESS_FINE_LOCATION
.
.
.
,
. IDE Eclipse Android New Android Project:
Project name: Location_FindProviders;
Application name: Location Providers Info;
Package name: com.samples.locationproviders;
Create Activity: LocationProvidersActivity.
-
Ch08_Location_FindProviders.
AndroidManifest.xml
. AndroidManifest.xml 8.1.
android.permission.ACCESS_FINE_LOCATION
8.1. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.locationproviders"
android:versionCode="1"
android:versionName="1.0">
8.
145
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".LocationProvidersActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-sdk android:minSdkVersion="7" />
</manifest>
TextView
text .
, .
LocationProvidersActivity onCreate() LocationManager,
getAllProviders() .
LocationProvidersActivity 8.2.
8.2. LocationProvidersActivity.java
package com.samples.locationproviders;
import java.util.List;
import
import
import
import
import
android.app.Activity;
android.content.Context;
android.location.LocationManager;
android.os.Bundle;
android.widget.TextView;
IV.
146
Context.LOCATION_SERVICE);
text.append("List of Location providers\n");
List<String> providers = manager.getAllProviders();
for (int i = 0; i < providers.size(); i++) {
String provider = providers.get(i);
text.append("\nProvider: " + provider);
text.append("\nEnabled: " +
manager.isProviderEnabled(provider) + "\n");
}
}
}
Android.
. 8.2.
. 8.2.
, GPS, , ,
Android.
Android . , , . ,
8.
147
. , .
.
, , , , . .
LocationProvider getBestProvider(),
, .
Criteria, .
Criteria ,
.
LocationProvider, , getAccuracy() setAccuracy(),
,
.
, , ,
Criteria:
ACCURACY_FINE ;
ACCURACY_COARSE .
Criteria :
getHorizontalAccuracy()
: ;
getVerticalAccuracy()
;
getBearingAccuracy() ;
getSpeedAccuracy() .
,
:
ACCURACY_HIGH;
ACCURACY_LOW;
ACCURACY_MEDIUM;
NO_REQUIREMENT.
Criteria
:
getPowerRequirement();
setPowerRequirement(int level).
(, , ), :
POWER_HIGH;
POWER_MEDIUM;
POWER_LOW.
IV.
148
Criteria :
isAltitudeRequired() ;
isBearingRequired() ;
isCostAllowed() ;
isSpeedRequired() .
Criteria
,
. , :
// LocationManager
LocationManager manager = (LocationManager)getSystemService(
Context.LOCATION_SERVICE);
// Criteria
Criteria criteria = new Criteria();
//
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setCostAllowed(true);
criteria.setSpeedRequired(true);
//
String bestProvider = manager.getBestProvider(criteria, true);
Criteria.
, , .
, ACCURACY_FINE
POWER_LOW.
IDE Eclipse Android New Android Project:
Project name: Location_BestProviders;
Application name: Find Best Providers;
Package name: com.samples.location.findbestproviders;
Create Activity: FindBestProvidersActivity.
-
Ch08_Location_BestProviders.
8.
149
AndroidManifest.xml
android.permission.INTERNET, 8.3.
android.permission.ACCESS_FINE_LOCATION
8.3. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.locationproviders"
android:versionCode="1"
android:versionName="1.0">
...
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.INTERNET" />
</manifest>
TextView
text . , .
FindBestProvidersActivity Criteria getBestProvider()
. FindBestProvidersActivity 8.4.
8.4. FindBestProvidersActivity.java
package com.samples.location.findbestproviders;
import java.util.List;
import
import
import
import
import
import
android.app.Activity;
android.content.Context;
android.location.Criteria;
android.location.LocationManager;
android.os.Bundle;
android.widget.TextView;
IV.
150
Android.
.
. 8.3.
,
:
GPS, , , , .
. 8.3.
8.
151
Android
, ,
, Android.
, GPS .
,
,
. ,
, , .
Emulator Control (
IDE Eclipse),
. Manual :
Longitude . , ;
Latitude .
, .
Send , (. 8.4).
Google API,
Maps, Google Maps
, . 8.5.
IV.
152
. 8.5.
Android , , ,
. ,
. , ,
Wi-Fi.
LocationManager getLastKnownLocation(), , , .
Location,
.
Location ,
. , ,
:
getLatitude() ;
getLongitude() ;
8.
153
getAltitude() ,
;
getAccuracy() .
,
, .
android.location LocationListener. , :
onLocationChanged(Location location) , Location ;
onProviderDisabled(String provider) , . ;
onProviderEnabled(String provider) , .
;
onStatusChanged(String provider, int status, Bundle extras) . , , ,
Extra-, , . :
AVAILABLE ;
TEMPORARY_UNAVAILABLE ;
OUT_OF_SERVICE .
. , , (,
).
,
,
, , .
154
IV.
LocationListener
:
LocationListener listener = new LocationListener() {
public void onLocationChanged(Location loc) {
//
}
@Override
public void onProviderDisabled(String arg0) {
//
}
@Override
public void onProviderEnabled(String arg0) {
//
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
//
}
};
, LocationListener .
LocationManager
:
requestLocationUpdates() LocationListener ;
requestSingleUpdate() LocationListener .
,
LocationListener. , LocationListener:
LocationManager manager;
...
manager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, listener);
LocationListener,
. IDE Eclipse Android (
8.
155
)
New Android Project:
Project name: Location_GetCoordinates;
Application name: Get Coordinates;
Package name: com.samples.location.getcoordinates;
Create Activity: GetCoordinatesActivity.
-
Ch08_Location_GetCoordinates.
AndroidManifest.xml ,
(. 8.3). TextView
text .
GetCoordinatesActivity LocationListener
.
GetCoordinatesActivity 8.5.
8.5. GetCoordinatesActivity.java
package com.samples.location.getcoordinates;
import
import
import
import
import
import
import
android.app.Activity;
android.content.Context;
android.location.Location;
android.location.LocationListener;
android.location.LocationManager;
android.os.Bundle;
android.widget.TextView;
IV.
156
Android.
. 8.6.
8.
157
. 8.6.
, Emulator
Control IDE Eclipse, Longitude Latitude
.
.
,
,
.
, Google.
Geocoding
c Geocoding : ,
/ , ,
, . C Geocoding .
, .
. , Geocoding , .
Geocoding
Geocoding :
Forward Geocoding ( Geocoding)
;
Reverse Geocoding ( Geocoding)
.
Geocoding Address.
Address ,
Geocoding . Address
, , .
Address ,
, ,
. :
getCountryName() , "Russia";
getCountryCode() ,
"RU";
getAdminArea() (
);
getSubAdminArea()
( );
9. Geocoding
159
getFeatureName() ,
"";
getLocality() ,
;
getPostalCode() , "94110";
getAddressLine() : , ,
;
getPhone() .
,
, getLocale().
Locale, , : 2-
(alpha-2) 3- (alpha-3) ISO. Locale :
getCountry() ;
getDisplayCountry() ;
getDisplayLanguage() ;
getDisplayName() , , ;
getISO3Country() 3- ISO;
getISO3Language() 3- ISO;
getLanguage() .
null ( Address)
( Locale),
Geocoding .
.
Reverse Geocoding
Reverse Geocoding, . .
. , getFromLocation() , ,
. ( , , ):
Geocoder geocoder = new Geocoder(getApplicationContext());
LocationManager manager = (LocationManager)getSystemService(
Context.LOCATION_SERVICE);
Location loc = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null)
{
// - 10-
List<Address> list = geocoder.getFromLocation(
IV.
160
Geocoding
, null.
,
.
.
, Geocoding . IDE Eclipse Android
New Android Project:
Project name: ReverseGeocoding;
Application name: Get geocoding;
Package name: com.samples.location.reversegeocoding;
Create Activity: GeocoderActivity.
-
Ch09_ReverseGeocoding.
Geocoding ,
. AndroidManifest.xml android.permission.INTERNET.
android.permission.ACCESS_COARSE_
LOCATION android.permission.ACCESS_FINE_LOCATION
.
main.xml
TextView text .
LocationListener
,
. printLocation() .
GeocoderActivity 9.1.
9.1. GeocoderActivity.java
package com.samples.location.reversegeocoding;
import java.io.IOException;
import java.util.List;
9. Geocoding
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.content.Context;
android.location.Address;
android.location.Geocoder;
android.location.Location;
android.location.LocationListener;
android.location.LocationManager;
android.os.Bundle;
android.widget.TextView;
android.widget.Toast;
161
IV.
162
// Geocoder
geocoder = new Geocoder(getApplicationContext());
printLocation(loc);
}
//
private void printLocation(Location loc) {
if (loc != null) {
text.setText("Longitude:\t" + loc.getLongitude() +
"\nLatitude:\t" + loc.getLatitude());
try {
//
List<Address> list = geocoder.getFromLocation(
loc.getLatitude(), loc.getLongitude(), 20);
for (int i = 0; i < list.size(); i++) {
Address address = list.get(i);
//
text.append("\nAddress# " + i +
"\n\tLocality: " + address.getLocality() +
"\n\tCountryName: " + address.getCountryName() +
"-" + address.getCountryCode() +
"\n\tFeatureName: " + address.getFeatureName() +
"\n\tPostalCode: " + address.getPostalCode()
);
}
}
catch (IOException e) {
Toast.makeText(getApplicationContext(),
e.toString(), Toast.LENGTH_LONG).show();
}
}
else {
text.setText("Location unavailable");
}
}
}
9. Geocoding
163
Google .
, . 9.1.
, . , : , ,
.
: ? ,
, Activity
(, ). Android
Activity . Intent c
Intent.ACTION_VIEW startActivity(),
Activity Google Maps. Extra- URI
.
URI :
geo: <latitude>,<longitude>
IV.
164
, Google Maps :
// URI
Uri uri = Uri.parse(String.format("geo:%f,%f",
loc.getLatitude(), loc.getLongitude()));
// Intent Activity
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
-
Ch09_ReverseGeocodingWithMap.
, TextView text,
Activity,
. bMap Show Map.
main.xml 9.2.
9.2. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<Button
android:id="@+id/bMap"
android:layout_height="wrap_content"
android:text="Show map"
android:layout_width="fill_parent"
android:layout_weight="1"/>
</LinearLayout>
<TextView
android:id="@+id/text"
9. Geocoding
165
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"/>
</LinearLayout>
GeocoderActivity
bMap_onClick() URI
Intent
Intent.ACTION_VIEW .
GeocoderActivity 9.3.
9.3. GeocoderActivity.java
package com.samples.location.reversegeocodingmap;
import java.io.IOException;
import java.util.List;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.content.Context;
android.content.Intent;
android.location.Address;
android.location.Geocoder;
android.location.Location;
android.location.LocationListener;
android.location.LocationManager;
android.net.Uri;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.TextView;
android.widget.Toast;
LocationManager manager;
TextView text;
Geocoder geocoder;
Button bMap;
Location currentLocation;
IV.
166
9. Geocoding
167
// URI
Uri uri = Uri.parse(String.format("geo:%f,%f",
currentLocation.getLatitude(),
currentLocation.getLongitude()));
// Intent Activity
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
};
//
private void printLocation(Location loc) {
if (loc != null) {
text.setText("Longitude:\t" + loc.getLongitude() +
"\nLatitude:\t" + loc.getLatitude());
try {
List<Address> list = geocoder.getFromLocation(
loc.getLatitude(), loc.getLongitude(), 20);
for (int i = 0; i < list.size(); i++) {
Address address = list.get(i);
text.append("\nAddress# " + i +
"\n\tLocality: " + address.getLocality() +
"\n\tCountryName: " + address.getCountryName() +
"-" + address.getCountryCode() +
"\n\tFeatureName: " + address.getFeatureName() +
"\n\tPostalCode: " + address.getPostalCode()
);
}
}
catch (IOException e) {
Toast.makeText(getApplicationContext(),
e.toString(), Toast.LENGTH_LONG).show();
}
}
else {
text.setText("Location unavailable");
}
}
}
Android. ,
, Show map
, . 9.2.
IV.
168
Forward Geocoding
Forward Geocoding,
.
Forward Geocoding getFromLocationName()
Geocoder. , getFromLocation(), , Address
.
:
Geocoder geocoder = new Geocoder(getApplicationContext());
List<Address> locations =
geocoder.getFromLocationName("Moscow", 10);
, , /:
for (int i = 0; i < size; i++) {
Address loc = locations.get(i);
//
int latitude = loc.getLatitude();
int longitude = loc.getLongitude();
}
9. Geocoding
169
Forward Geocoding .
IDE Eclipse Android New Android Project:
Project name: ForwardGeocodingWithMap;
Application name: Forward Geocoding;
Package name: com.samples.location.geocoderwithmap;
Create Activity: GeocoderActivity.
-
Ch09_ForwardGeocodingWithMap.
main.xml :
EditText (editSearch);
Button (bSearch);
ListView (list).
main.xml 9.4.
9.4. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:id="@+id/editSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter place name or address" />
<Button
android:id="@+id/bSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Search Geocode" />
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
IV.
170
GeocoderActivity
bSearch_onClick()
.
onListItemClick(),
Activity
.
GeocoderActivity 9.5.
9.5. GeocoderActivity.java
package com.samples.location.geocoderwithmap;
import java.io.IOException;
import java.util.List;
import
import
import
import
import
import
import
import
import
import
import
import
import
android.app.ListActivity;
android.content.Intent;
android.location.Address;
android.location.Geocoder;
android.net.Uri;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.widget.ArrayAdapter;
android.widget.Button;
android.widget.EditText;
android.widget.ListView;
android.widget.Toast;
Geocoder geocoder;
EditText editSearch;
Button bSearch;
List<Address> locations;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editSearch = (EditText) findViewById(R.id.editSearch);
bSearch = (Button) findViewById(R.id.bSearch);
// Geocoder
9. Geocoding
geocoder = new Geocoder(getApplicationContext());
bSearch.setOnClickListener(bSearch_onClick);
}
//
public OnClickListener bSearch_onClick = new OnClickListener() {
@Override
public void onClick(View v) {
//
String placeName = editSearch.getText().toString();
try {
// Location
locations = geocoder.getFromLocationName(placeName, 10);
int size = locations.size();
if (size == 0) {
editSearch.setText("");
editSearch.setHint("No results. Enter new place");
}
//
//
String[] list = new String[size];
for (int i = 0; i < size; i++) {
Address loc = locations.get(i);
list[i] = "Latitude: " + loc.getLatitude() +
"\nLongitude" + loc.getLongitude();
}
setListAdapter(
new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, list));
}
catch (IOException e) {
Toast.makeText(getApplicationContext(),
e.toString(), Toast.LENGTH_LONG).show();
}
}
};
171
IV.
172
//
//
public void onListItemClick(
ListView parent, View v, int position, long id) {
Address loc = locations.get(position);
Uri uri = Uri.parse(String.format("geo:%f,%f",
loc.getLatitude(), loc.getLongitude()));
Intent geoMap = new Intent(Intent.ACTION_VIEW, uri);
startActivity(geoMap);
}
}
, Lund, , . 9.4 ( , ,
Sony Ericsson).
9. Geocoding
173
10
Google Maps
Activity c .
Google Maps. Google
. :
http://code.google.com/android/add-ons/google-apis/reference/index.html
Google Maps
, Google
Maps API Key.
(. 10.2).
, , Maps API Key. :
http://code.google.com/android/maps-api-signup.html
. 10.1.
. 10.2.
175
IV.
176
. 10.3.
,
My certificate's MD5 fingerprint , Generate API Key, .
, Google Maps.
Google API Google Maps
com.google.android.maps.
. :
MapActivity Activity Google
Maps;
MapView , Google Maps;
MapController (, .);
GeoPoint ,
-.
177
Google Maps , ,
.
com.google.android.maps
Android SDK, ,
AndroidManifest.xml :
<uses-library android:name="com.google.android.maps" />
MapView
MapView, com.google.android.maps .
.
MapView:
setStreetView() Street View.
( 23 );
setTraffic() ;
setSatellite() ""
.
, , . . true .
:
isStreetView();
isSatellite();
isTraffic().
MapView :
getZoomLevel() ;
getMaxZoomLevel()
.
MapView .
MapController. MapView
.
setBuiltInZoomControls(), .
MapView android:apiKey,
Maps API Key:
<com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="YOUR_API_KEY"/>
IV.
178
MapActivity
MapView Activity,
MapActivity.
,
MapActivity (, , 5, Activity, ListActivity ):
public class MapViewActivity extends MapActivity {
...
}
MapView
.
OnCreate(),
MapActivity,
. . .
MapController
MapView MapController.
,
.
, MapController:
setCenter() , ,
. GeoPoint,
;
animateTo() , . .
, GeoPoint;
stopAnimation() (
), .
MapController :
setZoom() .
1 21, : ,
;
zoomIn() ;
zoomOut() ;
zoomInFixing(int xPixel, int yPixel)
,
, ;
zoomOutFixing()
;
179
zoomToSpan() ,
, , .
boolean.
, true.
( ) ,
false, .
MapController , getController() MapView :
MapView map = (MapView)findViewById(R.id.map);
MapController controller = map.getController();
MapController
:
controller.setZoom(15);
setZoom() .
. .
GeoPoint
GeoPoint . , Location, , .
GeoPoint 10-6 (), . . 1 000 000 ( ).
GeoPoint
:
getLatitudeE6() ;
getLongitudeE6() .
GeoPoint
. GeoPoint animateTo()
setCenter() MapController.
,
LocationListener ,
Location, , GeoPoint, , :
MapController controller;
...
IV.
180
MapView
Maps API Key,
Google Maps. , MapActivity. , ,
.
IDE Eclipse Android New Android Project:
Project name: MapView;
Application name: Embedded Google Map;
Package name: com.samples.location.mapview;
Create Activity: MapViewActivity.
-
Ch10_MapView.
AndroidManifest.xml
android.permission.INTERNET, android.permission.ACCESS_COARSE_LOCATION
android.permission.ACCESS_FINE_LOCATION.
com.google.android.maps.
10.1.
10.1. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.location.mapview">
<application
android:icon="@drawable/icon"
android:label="@string/app_name">
<activity
android:name=".MapViewActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
181
MapViewActivity
MapView MapController,
.
10.3.
IV.
182
10.3. MapViewActivity.java
package com.samples.location.mapview;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import
import
import
import
com.google.android.maps.GeoPoint;
com.google.android.maps.MapActivity;
com.google.android.maps.MapController;
com.google.android.maps.MapView;
import
import
import
import
import
import
import
import
import
android.content.Context;
android.location.Address;
android.location.Geocoder;
android.location.Location;
android.location.LocationListener;
android.location.LocationManager;
android.os.Bundle;
android.widget.TextView;
android.widget.Toast;
183
map = (MapView)findViewById(R.id.map);
text = (TextView)findViewById(R.id.text);
controller = map.getController();
//
controller.setZoom(17);
//
map.setSatellite(true);
map.setStreetView(true);
LocationManager locationManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 2000, 10, locListener);
printLocation(locationManager.getLastKnownLocation(
LocationManager.GPS_PROVIDER));
}
private void printLocation(Location location) {
if (location != null)
{
double lat = location.getLatitude();
double lon = location.getLongitude();
// GeoPoint
GeoPoint point = new GeoPoint(
(int)(lat * 1E6), (int)(lon * 1E6));
//
controller.animateTo(point);
//
text.setText(
String.format("Lat: %4.2f, Long: %4.2f", lat, lon));
try {
// Geocoder
//
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses =
geocoder.getFromLocation(lat, lon, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
for(int i=0; i<address.getMaxAddressLineIndex(); i++) {
text.append(", " + address.getAddressLine(i));
}
text.append(", " + address.getCountryName());
}
IV.
184
}
catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
}
else {
text.setText("Unable get location");
}
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
Android. IDE
Eclipse Emulator Control ,
Longitude: 30.31 Latitude: 59.94.
- ,
.
. 10.4.
. 10.4. MapView
185
,
. , MapView
. , setBuiltInZoomControls(),
true.
displayZoomControls().
. MapViewActivity 10.3
. onCreate()
10.4.
10.4. MapViewActivity
@Override
public void onCreate(Bundle savedInstanceState) {
...
map.setSatellite(true);
map.setStreetView(true);
//
map.setBuiltInZoomControls(true);
map.displayZoomControls(true);
...
}
, . 10.5.
. 10.5.
IV.
186
Google aps -, ,
.
, Google Maps. , , .
, . , , , , .
-
Ch10_MapView_Overlay.
187
. 10.6. ,
Android.
.
. 10.6.
SeekBar
, ,
ZoomControls , ,
Google Map -. Android SeekBar.
. IDE Eclipse
Android New Android Project
:
Project name: MapView_Zoom;
Application name: Embedded Google Map;
Package name: com.samples.location.mapzoom;
Create Activity: MapViewActivity.
-
Ch10_MapView_Zoom.
IV.
188
main.xml , , SeekBar
TextView .
10.6.
10.6. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frame"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"/>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:text="Zoom "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_gravity="center"/>
<TextView
android:id="@+id/zoom"
android:text="0.0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_gravity="center"/>
<SeekBar
android:id="@+id/seekbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:progress="0"/>
</LinearLayout>
189
<com.google.android.maps.MapView
android:id="@+id/map"
android:apiKey="YOUR_API_KEY"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"/>
</LinearLayout>
, . OnSeekBarChangeListener(),
onProgressChanged():
MapViewActivity
SeekBar.OnSeekBarChangeListener seekBarListener =
new SeekBar.OnSeekBarChangeListener(){
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
...
}
}
onProgressChanged()
setZoom() MapController.
MapViewActivity 10.7.
10.7. MapViewActivity
package com.samples.location.mapzoom;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import
import
import
import
import
com.google.android.maps.GeoPoint;
com.google.android.maps.MapActivity;
com.google.android.maps.MapController;
com.google.android.maps.MapView;
com.google.android.maps.MapView.LayoutParams;
import
import
import
import
import
import
android.content.Context;
android.location.Address;
android.location.Geocoder;
android.location.Location;
android.location.LocationListener;
android.location.LocationManager;
IV.
190
import
import
import
import
import
android.os.Bundle;
android.widget.ImageView;
android.widget.SeekBar;
android.widget.TextView;
android.widget.Toast;
MapController controller;
TextView text;
TextView zoom;
MapView map;
SeekBar seek;
191
IV.
192
@Override
protected boolean isRouteDisplayed() {
return false;
}
private void printLocation(Location location) {
if (location != null)
{
double lat = location.getLatitude();
double lon = location.getLongitude();
// GeoPoint
GeoPoint point = new GeoPoint(
(int)(lat * 1E6), (int)(lon * 1E6));
//
controller.animateTo(point);
ImageView marker = new ImageView(getApplicationContext());
marker.setImageResource(R.drawable.star);
MapView.LayoutParams markerParams = new MapView.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
point, MapView.LayoutParams.TOP_LEFT );
map.addView(marker, markerParams);
//
text.setText(
String.format("Lat: %4.2f, Long: %4.2f", lat, lon));
try {
// Geocoder
//
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses =
geocoder.getFromLocation(lat, lon, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
for(int i=0; i<address.getMaxAddressLineIndex(); i++) {
text.append(", " + address.getAddressLine(i));
}
text.append(", " + address.getCountryName());
}
193
}
catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
}
else {
text.setText("Unable get location");
}
}
}
Android. c
. 10.7.
. 10.7. SeekBar
,
, , , .
SeekBar,
194
IV.
, , , .
, 12, , .
Google Maps ,
. ,
, . . Android SDK Google API
, .
"" Android.
11
: .
, Android. ,
, ,
.
Android
, , , . Android , ,
.
Android Virtual Device . Android . Android SDK and
AVD Manager, Android
Virtual Device. Edit Android Virtual Device (AVD) SD Card
,
. 11.1.
Edit AVD. AVD
1024 M, .
198
V.
. 11.1.
Android
Android Linux, , Linux-,
, .
Android DDMS IDE Eclipse File Explorer.
,
, . Android File Explorer
. 11.2.
11.
199
. 11.2. Android
Android
Android android.os Environment. Android.
Environment
File. File java.io.File. Java , . , , isFile()
isDirectory() File.
Environment Android:
getDataDirectory() ;
getDownloadCacheDirectory() ;
getRootDirectory()
Android;
getExternalStorageDirectory()
.
,
, , . . ,
Environment, , .
getExternalStoragePublicDirectory()
(,
V.
200
.). Environment, :
DIRECTORY_ALARMS ;
DIRECTORY_DCIM , ;
DIRECTORY_DOWNLOADS ,
;
DIRECTORY_MOVIES ;
DIRECTORY_MUSIC ;
DIRECTORY_NOTIFICATIONS , (, SMS, .);
DIRECTORY_PICTURES ;
DIRECTORY_PODCASTS RSS ;
DIRECTORY_RINGTONES ,
.
,
.
IDE Eclipse Android
New Android Project:
Project name: Android Environment;
Application name: Android Environment;
Package name: com.samples.os.environment;
Create Activity: EnvironmentActivity.
-
Ch11_AndroidEnvironment.
TextView .
EnvironmentActivity Environment .
EnvironmentActivity 11.1.
11.1. EnvironmentActivity.java
package com.samples.os.environment;
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.os.Environment;
android.widget.TextView;
11.
201
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView text = (TextView)findViewById(R.id.text);
text.append(
"Root:\t" + Environment.getRootDirectory() +
"\nDownload Cache Dir:\t" +
Environment.getDownloadCacheDirectory() +
"\nExternal Storage State:\t" +
Environment.getExternalStorageState() +
"\nData Directory:\t" + Environment.getDataDirectory() +
"\nisExternal Storage Removable:\t" +
Environment.isExternalStorageRemovable() +
"\nExternal Storage Dir:\t" +
Environment.getExternalStorageDirectory() +
"\n\nExternal Storage Public Directory:\t" +
"\n\tAlarms:\t" + Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_ALARMS) +
"\n\tDCIM:\t" + Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM) +
"\n\tDownloads:\t" + Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS) +
"\n\tMovies:\t" + Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES) +
"\n\tMusic:\t" + Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MUSIC) +
"\n\tNotification:\t" +
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_NOTIFICATIONS) +
"\n\tPictures:\t" + Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES) +
"\n\tPodcasts:\t" + Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PODCASTS) +
"\n\tRingtones:\t" + Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_RINGTONES));
}
}
Android.
.
. 11.3.
202
V.
. 11.3. Android
,
. Environment
getExternalStorageState(), . String
, Environment:
MEDIA_MOUNTED ;
MEDIA_UNMOUNTED ,
;
MEDIA_BAD_REMOVAL ;
MEDIA_CHECKING ;
MEDIA_MOUNTED_READ_ONLY ;
MEDIA_NOFS , , ;
MEDIA_REMOVED ;
MEDIA_SHARED , USB (, PC);
MEDIA_UNMOUNTABLE ,
.
11.
203
, , ,
.
SD-
, Android , . , ,
,
. , .
, , .
IDE Eclipse Android
New Android Project:
Project name: SDCard_ReadWriteFiles;
Application name: Wordpad;
Package name: com.samples.sdcard.readwritefiles;
Create Activity: EditorActivity.
-
Ch11_SDCard_ReadWriteFiles.
AndroidManifest.xml
, 11.2.
android.permission.WRITE_EXTERNAL_STORAGE
11.2. AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.filesrw">
<application>
<activity android:name=".EditorActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
V.
204
,
,
strings.xml, 11.3.
11.3. strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Wordpad</string>
<string name="btn_ok">OK</string>
<string name="btn_cancel">Cancel</string>
<string name="title_open">Open document</string>
<string name="title_save">Save document</string>
<string name="menu_new">New</string>
<string name="menu_open">Open</string>
<string name="menu_save">Save</string>
<string name="menu_exit">Exit</string>
</resources>
main.xml
EditText edit,
. main.xml 11.4.
11.4. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<EditText
android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:singleLine="false"/>
</LinearLayout>
, . .
EditText .
,
res/layout/ savedialog.xml.
11.5.
11.
205
11.5. savedialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_save"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:id="@+id/edit_filename"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:hint="Enter file name"/>
</LinearLayout>
EditorActivity EditText :
New;
Save;
Open;
Exit.
EditorActivity
,
, . . , .
EditorActivity 11.6.
11.6. EditorActivity.java
package com.samples.sdcard.readwritefiles;
import
import
import
import
import
import
java.io.BufferedReader;
java.io.File;
java.io.FileInputStream;
java.io.FileOutputStream;
java.io.InputStreamReader;
java.util.ArrayList;
import
import
import
import
import
import
import
android.app.Activity;
android.app.AlertDialog;
android.content.DialogInterface;
android.os.Bundle;
android.os.Environment;
android.view.LayoutInflater;
android.view.Menu;
V.
206
import
import
import
import
android.view.MenuItem;
android.view.View;
android.widget.EditText;
android.widget.Toast;
EditText editText;
String curFileName = "";
String dir;
int pos = 0;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
editText = (EditText)findViewById(R.id.edit);
// ,
//
dir = Environment.getExternalStorageDirectory().toString() +
DIRECTORY_DOCUMENTS;
File folder = new File(dir);
// ,
if (!folder.exists()) {
folder.mkdir();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, IDM_NEW, Menu.NONE, R.string.menu_new)
.setIcon(R.drawable.menu_new)
.setAlphabeticShortcut('n');
11.
menu.add(Menu.NONE, IDM_OPEN, Menu.NONE, R.string.menu_open)
.setIcon(R.drawable.menu_open)
.setAlphabeticShortcut('o');
menu.add(Menu.NONE, IDM_SAVE, Menu.NONE, R.string.menu_save)
.setIcon(R.drawable.menu_save)
.setAlphabeticShortcut('s');
menu.add(Menu.NONE, IDM_EXIT, Menu.NONE, R.string.menu_exit)
.setIcon(R.drawable.menu_exit)
.setAlphabeticShortcut('x');
return(super.onCreateOptionsMenu(menu));
}
//
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case IDM_NEW:
curFileName = "";
editText.setText("");
this.setTitle(R.string.app_name);
break;
case IDM_OPEN:
callOpenDialog();
break;
case IDM_SAVE:
callSaveDialog();
break;
case IDM_EXIT:
finish();
break;
default:
return false;
}
return true;
}
//
private void callSaveDialog() {
LayoutInflater inflater = this.getLayoutInflater();
View root = inflater.inflate(R.layout.savedialog, null);
final EditText editFileName =
(EditText)root.findViewById(R.id.edit_filename);
editFileName.setText(curFileName);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
207
V.
208
builder.setView(root);
builder.setTitle(R.string.title_save);
//
builder.setPositiveButton(
R.string.btn_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
saveFile(editFileName.getText().toString());
}
});
//
builder.setNegativeButton(
R.string.btn_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {}
});
builder.show();
}
//
private void callOpenDialog() {
try {
final String[] files = findFiles(dir);
//
if (files.length > 0) {
pos = 0;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.title_open);
//
builder.setSingleChoiceItems(
files, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
pos = item;
}
});
// (OK)
builder.setPositiveButton(R.string.btn_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
curFileName = files[pos];
openFile(curFileName);
}
11.
});
// (Cancel)
builder.setNegativeButton(R.string.btn_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.setCancelable(false);
builder.show();
}
}
catch (Exception e) {
Toast.makeText(this, e.toString(), 3000).show();
}
}
//
private void saveFile(String fileName) {
try {
if (!fileName.endsWith(FILE_EXT)) {
fileName += FILE_EXT;
}
File file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(editText.getText().toString().getBytes());
fos.close();
}
catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
//
//
private void openFile(String fileName) {
try {
File file = new File(dir, fileName);
FileInputStream inStream = new FileInputStream(file);
if (inStream != null) {
InputStreamReader tmp =
209
V.
210
new InputStreamReader(inStream);
BufferedReader reader = new BufferedReader(tmp);
String str;
StringBuffer buffer = new StringBuffer();
while ((str = reader.readLine()) != null) {
buffer.append(str + "\n");
}
inStream.close();
editText.setText(buffer.toString());
curFileName = fileName;
// Activity
setTitle(getResources().getString(R.string.app_name) +
": " + curFileName);
}
}
catch (Exception e) {
Toast.makeText(this, e.toString(), 3000).show();
}
}
//
private String[] findFiles(String dirPath) {
ArrayList<String> items = new ArrayList<String>();
try {
File f = new File(dirPath);
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
// , ,
//
if(!file.isDirectory()) {
items.add(file.getName());
}
}
}
catch (Exception e) {
Toast.makeText(this, e.toString(), 3000).show();
}
return items.toArray(new String[items.size()]);
}
}
11.
211
Android.
, ,
, .
. 11.4.
. 11.4.
. 11.5.
212
V.
Open
document, , . (. 11.5).
, ,
, ,
Android.
,
. , .
.
12
. Android. , ,
Android.
Android, .
,
Camera. android.hardware, , ( ).
Camera Android, .
Camera :
open() Camera ;
open(int cameraId) Camera
( ,
);
release() Camera.
Camera, open() .
Camera ,
. , release(),
,
V.
214
. , :
//
Camera camera = Camera.open();
//
Camera.Parameters params = camera.getParameters();
...
// c
camera.release();
android.permission.CAMERA, .
Camera : getParameters(),
, setParameters(), .
Camera.Parameters.
Camera.Parameters , , , , ,
. , , . Camera.Parameters
,
.
,
. IDE Eclipse Android New Android Project:
Project name: CameraInfo;
Application name: Camera Information;
Package name: com.samples.camera.info;
Create Activity: CameraInfoActivity.
-
Ch12_CameraInfo.
android.permission.CAMERA,
. AndroidManifest.xml , 12.1.
12.
215
12.1. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.camera.info"
android:versionCode="1"
android:versionName="1.0">
<application
android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".CameraInfoActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.CAMERA" />
</manifest>
main.xml
text .
CameraInfoActivity onCreate() Camera, getParameters()
. CameraInfoActivity
12.2.
TextView
12.2. CameraInfoActivity.java
package com.samples.camera.info;
import
import
import
import
android.app.Activity;
android.hardware.Camera;
android.os.Bundle;
android.widget.TextView;
V.
216
.
. . 12.1.
. 12.1.
Android,
Android, ,
, , -
12.
217
. -
.
Camera.Parameters :
getSupportedColorEffects()
;
getSupportedFlashModes()
;
getSupportedFocusModes()
;
getSupportedPictureFormats() ;
getSupportedPreviewFormats() ;
getSupportedPreviewFpsRange() , .
,
;
getSupportedSceneModes()
(, , .);
getSupportedWhiteBalance()
.
, .
Camera.Parameters , :
getSupportedPictureSizes()
;
getSupportedJpegThumbnailSizes()
JPEG;
getSupportedPreviewSizes()
;
getSupportedVideoSizes()
.
. IDE Eclipse Android
New Android Project:
Project name: CameraSupportedModesInfo;
Application name: Camera Supported Modes;
Package name: com.samples.camera.supportedmodes;
Create Activity: CameraInfoActivity.
V.
218
-
Ch12_CameraSupportedModesInfo.
CameraInfoActivity, ,
onCreate(), ,
getParameters() Camera.Parameters , .
CameraInfoActivity 12.3.
12.3. CameraInfoActivity.java
package com.samples.camera.supportedmodes;
import java.util.List;
import
import
import
import
import
android.app.Activity;
android.hardware.Camera;
android.hardware.Camera.Size;
android.os.Bundle;
android.widget.TextView;
12.
}
}
else {
text.append("\nNo Supported Flash Modes");
}
List<String> antibandings = params.getSupportedAntibanding();
if (antibandings != null) {
text.append("\n\nSupported Antibanding :\n");
for (String mode : antibandings) {
text.append(String.format("%s; ", mode));
}
}
else {
text.append("\nNo Supported Antibanding");
}
List<String> colorEffects = params.getSupportedColorEffects();
if (colorEffects != null) {
text.append("\n\nSupported color effects \n");
for (String mode : colorEffects) {
text.append(String.format("%s; ", mode));
}
}
else {
text.append("\nNo Supported Color Effects");
}
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes != null) {
text.append("\n\nSupported Focus Modes \n");
for (String mode : focusModes) {
text.append(String.format("%s; ", mode));
}
}
else {
text.append("\nNo Supported Focus Modes");
}
List<Size> previewSizes = params.getSupportedPreviewSizes();
if (previewSizes != null) {
text.append("\n\nSupported Preview Sizes \n");
for (Size mode : previewSizes) {
text.append(String.format("%dx%d; ",
mode.height, mode.width));
}
}
else {
text.append("\nNo Supported Preview Sizes");
}
219
V.
220
.
, ,
. 12.2.
. 12.2. ,
12.
221
, , .
, , , , ,
, ,
, .
Intent
,
Activity, .
MediaStore android.provider.
: . Intent
:
INTENT_ACTION_STILL_IMAGE_CAMERA Intent
;
INTENT_ACTION_VIDEO_CAMERA Intent .
:
ACTION_IMAGE_CAPTURE Intent
;
ACTION_VIDEO_CAPTURE Intent
.
, Activity,
Intent :
Intent
.
IDE Eclipse Android
New Android Project:
Project name: CameraCallActions;
Application name: Call Camera Actions;
Package name: com.samples.camera.callactivities;
Create Activity: CallCameraActivity.
-
Ch12_CameraCallActions.
main.xml
Activity . 12.4.
V.
222
12.4. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="@+id/bImageCapture"
android:text="Image Capture"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
<Button
android:id="@+id/bVideoCapture"
android:text="Video Capture"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
<Button
android:id="@+id/bStillImage"
android:text="Still image mode"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
<Button
android:id="@+id/bVideoCamera"
android:text="Video Camera"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</LinearLayout>
CallCameraActivity, , onClick()
. CallCameraActivity 12.5.
12.5. CallCameraActivity.java
package com.samples.camera.callactivities;
import
import
import
import
import
import
android.app.Activity;
android.content.Intent;
android.content.pm.ActivityInfo;
android.os.Bundle;
android.provider.MediaStore;
android.view.View;
12.
import android.widget.Button;
public class CallCameraActivity extends Activity
implements View.OnClickListener {
private
private
private
private
Button
Button
Button
Button
bImageCapture;
bVideoCapture;
bStillImage;
bVideoCamera;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bImageCapture = (Button)findViewById(R.id.bImageCapture);
bVideoCapture = (Button)findViewById(R.id.bVideoCapture);
bStillImage = (Button)findViewById(R.id.bStillImage);
bVideoCamera = (Button)findViewById(R.id.bVideoCamera);
bImageCapture.setOnClickListener(this);
bVideoCapture.setOnClickListener(this);
bStillImage.setOnClickListener(this);
bVideoCamera.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bImageCapture:
startActivity(new Intent(MediaStore.ACTION_IMAGE_CAPTURE));
break;
case R.id.bVideoCapture:
startActivity(new Intent(MediaStore.ACTION_VIDEO_CAPTURE));
break;
case R.id.bStillImage:
startActivity(new Intent(
MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA));
break;
case R.id.bVideoCamera:
startActivity(new Intent(
MediaStore.INTENT_ACTION_VIDEO_CAMERA));
break;
}
}
}
223
224
V.
. . 12.3.
Activity
. , Activity. , Google
Maps, MapView,
Android SDK .
SurfaceView.
,
SurfaceView ( ).
SurfaceHolder,
getHolder().
, SurfaceView .
, ,
.
SurfaceHolder:
surfaceCreated() ;
surfaceChanged() ( Activity);
surfaceDestroyed() .
:
Camera camera;
...
@Override
public void surfaceCreated(SurfaceHolder holder) {
12.
225
//
camera = Camera.open();
//
camera.setPreviewDisplay(surHolder);
//
camera.startPreview();
}
@Override
public void surfaceChanged(
SurfaceHolder holder, int format, int width, int height) {
//
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
//
camera.stopPreview();
camera.release();
}
.
IDE Eclipse Android
New Android Project:
Project name: CameraPreview;
Application name: Camera preview;
Package name: com.samples.camera.preview;
Create Activity: CameraPreviewActivity.
-
Ch12_CameraPreview.
main.xml
SurfaceView surfaceview, 12.6.
12.6. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SurfaceView
V.
226
android:id="@+id/surfaceview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
CameraPreviewActivity
SurfaceHolder.Callback, .
CameraPreviewActivity 12.7.
12.7. CameraPreviewActivity.java
package com.samlpes.camera.preview;
import
import
import
import
import
import
android.app.Activity;
android.hardware.Camera;
android.os.Bundle;
android.view.SurfaceHolder;
android.view.SurfaceView;
android.widget.Toast;
12.
227
camera.startPreview();
}
catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
@Override
public void surfaceChanged(
SurfaceHolder holder, int format, int width, int height) { }
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
//
camera.stopPreview();
camera.release();
}
}
.
, . . 12.4.
. 12.4.
. .
.
V.
228
-
Ch12_CameraManagePreview.
main.xml,
SurfaceView, Start Stop bStart bStop.
main.xml 12.8.
12.8. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="3px">
<Button
android:layout_height="wrap_content"
android:id="@+id/bStart"
android:text="Start"
android:layout_width="wrap_content"
android:layout_weight="1"/>
<Button
android:layout_height="wrap_content"
android:id="@+id/bStop"
android:text="Stop"
android:layout_width="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
<SurfaceView
android:id="@+id/surfaceview"
12.
229
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
CameraPreviewActivity onClick() ,
.
isCameraPreview boolean, .
,
. . onClick() , surfaceDestroyed().
, ,
open() .
. isCameraPreview
surfaceDestroyed() .
12.9.
12.9. CameraPreviewActivity.java
package com.samples.camera.managepreview;
import java.io.IOException;
import
import
import
import
import
import
import
import
android.app.Activity;
android.hardware.Camera;
android.os.Bundle;
android.view.SurfaceHolder;
android.view.SurfaceView;
android.view.View;
android.widget.Button;
android.widget.Toast;
Button bStart;
Button bStop;
SurfaceView surView;
SurfaceHolder surHolder;
V.
230
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bStart = (Button)findViewById(R.id.bStart);
bStop = (Button)findViewById(R.id.bStop);
surView = (SurfaceView)findViewById(R.id.surfaceview);
surHolder = surView.getHolder();
surHolder.addCallback(this);
surHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
bStart.setOnClickListener(this);
bStop.setOnClickListener(this);
bStop.setEnabled(false);
}
@Override
public void surfaceChanged(
SurfaceHolder holder, int format, int width, int height) { }
@Override
public void surfaceCreated(SurfaceHolder holder) { }
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (isCameraPreview) {
camera.stopPreview();
camera.release();
isCameraPreview = false;
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bStart:
try {
camera = Camera.open();
camera.setPreviewDisplay(surHolder);
camera.startPreview();
isCameraPreview = true;
bStart.setEnabled(!isCameraPreview);
bStop.setEnabled(isCameraPreview);
}
catch (IOException e) {
12.
231
. Start.
Start Stop .
. 12.5.
. 12.5.
, (), ,
,
.
V.
232
, . . , (. . 12.5), ,
.
XML- .
LayoutInflater, XML View. ,
, :
LayoutInflater inflater = LayoutInflater.from(getBaseContext());
// View (overlay.xml)
View overlay = inflater.inflate(R.layout.overlay, null);
LayoutParams params = new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
// Activity
addContentView(overlay, params);
// -
// findViewById()
ImageButton button = (ImageButton)overlay.findViewById(R.id.button1);
,
. . Android
New Android Project :
Project name: CameraOverlay;
Application name: Camera Overlay;
Package name: com.samples.camera.overlay;
Create Activity: CameraPreviewActivity.
-
Ch12_CameraOverlay.
,
Ch12_CameraOverlay/res/drawable.
overlay.xml 12.10.
12.10. overlay.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
12.
233
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="bottom|right">
<ImageButton
android:id="@+id/bStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/start"
android:layout_margin="1px"/>
<ImageButton
android:id="@+id/bStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/stop"
android:layout_margin="1px"/>
</LinearLayout>
CameraPreviewActivity
.
CameraPreviewActivity 12.11.
12.11. CameraPreviewActivity.java
package com.samples.camera.overlay;
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import
import
import
import
import
import
import
import
android.hardware.Camera;
android.view.LayoutInflater;
android.view.SurfaceHolder;
android.view.SurfaceView;
android.view.View;
android.view.ViewGroup.LayoutParams;
android.widget.ImageButton;
android.widget.Toast;
ImageButton bStart;
ImageButton bStop;
SurfaceView surView;
SurfaceHolder surHolder;
V.
234
12.
235
switch (v.getId()) {
case R.id.bStart:
try {
camera = Camera.open();
camera.setPreviewDisplay(surHolder);
camera.startPreview();
isCameraPreview = true;
bStart.setEnabled(!isCameraPreview);
bStop.setEnabled(isCameraPreview);
}
catch (IOException e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
break;
case R.id.bStop:
camera.stopPreview();
camera.release();
isCameraPreview = false;
bStart.setEnabled(!isCameraPreview);
bStop.setEnabled(isCameraPreview);
break;
}
}
}
. ,
, , . 12.6.
. 12.6.
236
V.
SurfaceView ,
, .
, . Camera takePicture(), :
takePicture(Camera.ShutterCallback shutter,
Camera.PictureCallback
Camera.PictureCallback
Camera.PictureCallback
takePicture(Camera.ShutterCallback
Camera.PictureCallback
Camera.PictureCallback
raw,
postview,
jpeg);
shutter,
raw,
jpeg).
.
takePicture() ,
,
. , :
Camera.ShutterCallback shutter ,
;
Camera.PictureCallback raw
;
Camera.PictureCallback jpeg
, JPEG;
Camera.PictureCallback postview (
).
, :
Camera.ShutterCallback ;
Camera.PictureCallback .
, takePicture()
null, .
, , Bitmap :
PictureCallback jpg = new PictureCallback() {
@Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
12.
237
Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
// , , Bitmap
//
// ,
camera.stopPreview();
camera.release();
}
};
. IDE Eclipse Android New Android Project:
Project name: CameraTakePicture;
Application name: Take Picture;
Package name: com.samples.camera.takepicture;
Create Activity: CameraPreviewActivity.
-
Ch12_CameraTakePicture.
overlay.xml
ImageButton bTake, . 12.12.
12.12. overlay.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="bottom|right">
<ImageButton
android:id="@+id/bStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/start"
android:layout_margin="1px"/>
<ImageButton
android:id="@+id/bTake"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
V.
238
android:src="@drawable/fix"
android:layout_margin="1px"/>
<ImageButton
android:id="@+id/bStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/stop"
android:layout_margin="1px"/>
</LinearLayout>
CameraPreviewActivity , .
CameraPreviewActivity 12.13.
12.13. CameraPreviewActivity.java
package com.samples.camera.takepicture;
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import
import
import
import
import
import
import
import
import
import
import
import
android.graphics.Bitmap;
android.graphics.BitmapFactory;
android.hardware.Camera;
android.hardware.Camera.PictureCallback;
android.hardware.Camera.ShutterCallback;
android.view.LayoutInflater;
android.view.SurfaceHolder;
android.view.SurfaceView;
android.view.View;
android.view.ViewGroup.LayoutParams;
android.widget.ImageButton;
android.widget.Toast;
12.
private boolean isCameraPreview = false;
private ShutterCallback shutter = new ShutterCallback(){
@Override
public void onShutter() { }
};
private PictureCallback raw = new PictureCallback(){
@Override
public void onPictureTaken(byte[] arg0, Camera arg1) { }
};
private PictureCallback jpg = new PictureCallback(){
@Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
camera.stopPreview();
camera.release();
isCameraPreview = false;
bStart.setEnabled(!isCameraPreview);
bStop.setEnabled(isCameraPreview);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surView = (SurfaceView)findViewById(R.id.surfaceview);
surHolder = surView.getHolder();
surHolder.addCallback(this);
LayoutInflater inflater = LayoutInflater.from(getBaseContext());
View overlay = inflater.inflate(R.layout.overlay, null);
LayoutParams params = new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
addContentView(overlay, params);
bStart = (ImageButton)overlay.findViewById(R.id.bStart);
bStop = (ImageButton)overlay.findViewById(R.id.bStop);
bTake = (ImageButton)overlay.findViewById(R.id.bTake);
bStart.setOnClickListener(this);
bStop.setOnClickListener(this);
239
V.
240
bTake.setOnClickListener(this);
bTake.setEnabled(!isCameraPreview);
bStop.setEnabled(!isCameraPreview);
}
@Override
public void surfaceChanged(
SurfaceHolder holder, int format, int width, int height) { }
@Override
public void surfaceCreated(SurfaceHolder holder) { }
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// ,
//
if (isCameraPreview) {
camera.stopPreview();
camera.release();
isCameraPreview = false;
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bStart:
try {
camera = Camera.open();
camera.setPreviewDisplay(surHolder);
camera.startPreview();
isCameraPreview = true;
bStart.setEnabled(!isCameraPreview);
bStop.setEnabled(isCameraPreview);
}
catch (IOException e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
break;
case R.id.bTake:
camera.takePicture(shutter, raw, jpg);
break;
case R.id.bStop:
12.
241
camera.stopPreview();
camera.release();
isCameraPreview = false;
bStart.setEnabled(!isCameraPreview);
bStop.setEnabled(isCameraPreview);
break;
}
}
}
.
.
. 12.7.
. 12.7.
, , , , .
, , .
AutoFocusCallback onAutoFocus():
AutoFocusCallback autoFocusCallback = new AutoFocusCallback(){
@Override
public void onAutoFocus(boolean arg0, Camera arg1) {
//
}
};
V.
242
AutoFocusCallback Camera
c autoFocus() :
Camera camera = Camera.open();
camera.autoFocus(autoFocusCallback);
.
, ,
.
IDE Eclipse Android New Android Project:
Project name: CameraAutoFocus;
Application name: com.samples.camera.autofocus;
Package name: Set Autofocus;
Create Activity: CameraPreviewActivity.
-
Ch12_CameraAutoFocus.
CameraPreviewActivity . CameraPreviewActivity
12.14.
12.14. CameraPreviewActivity.java
package com.samples.camera.autofocus;
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import
import
import
import
import
import
import
import
import
import
import
import
import
android.graphics.Bitmap;
android.graphics.BitmapFactory;
android.hardware.Camera;
android.hardware.Camera.AutoFocusCallback;
android.hardware.Camera.PictureCallback;
android.hardware.Camera.ShutterCallback;
android.view.LayoutInflater;
android.view.SurfaceHolder;
android.view.SurfaceView;
android.view.View;
android.view.ViewGroup.LayoutParams;
android.widget.ImageButton;
android.widget.Toast;
12.
private ImageButton bStart;
private ImageButton bStop;
private ImageButton bTake;
private SurfaceView surView;
private SurfaceHolder surHolder;
private Camera camera;
private boolean isCameraPreview = false;
private ShutterCallback shutter = new ShutterCallback(){
@Override
public void onShutter() { }
};
private PictureCallback raw = new PictureCallback(){
@Override
public void onPictureTaken(byte[] arg0, Camera arg1) { }
};
private PictureCallback jpg = new PictureCallback(){
@Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
camera.startPreview();
}
};
private AutoFocusCallback autoFocusCallback = new AutoFocusCallback(){
@Override
public void onAutoFocus(boolean arg0, Camera arg1) {
// ,
bTake.setEnabled(true);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surView = (SurfaceView)findViewById(R.id.surfaceview);
surHolder = surView.getHolder();
surHolder.addCallback(this);
surHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
243
V.
244
12.
245
bStart.setEnabled(!isCameraPreview);
bStop.setEnabled(isCameraPreview);
}
catch (IOException e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
break;
case R.id.bTake:
camera.takePicture(shutter, raw, jpg);
break;
case R.id.bStop:
camera.stopPreview();
camera.release();
isCameraPreview = false;
bStart.setEnabled(!isCameraPreview);
bStop.setEnabled(isCameraPreview);
break;
}
}
}
. ,
. ,
. , .
. 12.8.
. 12.8.
246
V.
. ,
Android , .
, Android,
.
13
, SMS.
Android
(), , , , .
.
. Android SDK API
.
Android . , Android 2.3.3
, , .
, . .
.
Android SDK android.hardware .
,
.
SensorManager. SensorManager getSystemService():
SensorManager sensors =
(SensorManager)getSystemService(Context.SENSOR_SERVICE);
SensorManager , , . .
248
V.
Sensor.
, , ,
, .
Sensor ,
. .
Android SDK 2.3.3 Sensor ,
:
TYPE_ACCELEROMETER ,
;
TYPE_GRAVITY ;
TYPE_GYROSCOPE ,
3D- ;
TYPE_LIGHT ;
TYPE_LINEAR_ACCELERATION ;
TYPE_MAGNETIC_FIELD ;
TYPE_ORIENTATION 3D- ;
TYPE_PRESSURE ;
TYPE_PROXIMITY ;
TYPE_ROTATION_VECTOR .
;
TYPE_TEMPERATURE ;
TYPE_ALL , .
, Sensor
:
getName() ;
getVendor() ;
getVersion() .
:
getMaximumRange() ;
getMinDelay() ;
getPower() , . , . .
;
getResolution() .
, , ,
Android SDK. , getMinDelay()
API Level 9.
,
Android. ,
Android SensorManager,
,
.
13.
249
, ,
. ,
, ,
. SensorManager :
getSensorList(int type);
getDefaultSensor(int type).
, ,
getSensorList() Sensor.TYPE_ALL:
SensorManager manager = (SensorManager)getSystemService(
Context.SENSOR_SERVICE);
...
List<Sensor> sensors = manager.getSensorList(Sensor.TYPE_ALL);
getSensorList(),
, ,
, :
SensorManager manager = (SensorManager)getSystemService(
Context.SENSOR_SERVICE);
...
List<Sensor> sensors = manager.getSensorList(Sensor.TYPE_ACCELEROMETER);
,
, . . .
getDefaultSensor():
Sensor defaultGyroscope =
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
. IDE Eclipse
Android New
Android Project:
Project name: GetDeviceSensors;
Application name: Get available sensors;
Package name: com.samples.hardware.getsensors;
Create Activity: GetSensorsActivity.
-
Ch13_GetDeviceSensors.
, AndroidManifest
.
TextView .
GetSensorsActivity . onCreate()
SensorManager getSensorList()
Sensor, .
GetSensorsActivity 13.1.
V.
250
13.1. GetSensorsActivity.java
package com.samples.hardware.getsensors;
import java.util.List;
import
import
import
import
import
import
android.app.Activity;
android.content.Context;
android.hardware.Sensor;
android.hardware.SensorManager;
android.os.Bundle;
android.widget.TextView;
. , HTC Wildfire
, . 13.1.
,
. 13.1.
. 13.1.
13.
251
android.hardware
SensorEventListener. :
onAccuracyChanged() onSensorChanged(),
.
onAccuracyChanged()
. Sensor,
, ,
. ,
Sensor:
SENSOR_STATUS_ACCURACY_HIGH ;
SENSOR_STATUS_ACCURACY_MEDIUM ;
SENSOR_STATUS_ACCURACY_LOW ;
SENSOR_STATUS_UNRELIABLE , ,
.
onSensorChanged()
, .
SensorEvent. , , :
accuracy ;
sensor Sensor, ;
timestamp , ;
values ,
, . 1
3. , ,
, . ,
,
(
X, Y, Z).
, SensorEventListener
:
SensorEventListener listener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
//
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
//
}
};
252
V.
,
SensorEventListener ,
. registerListener() SensorManager.
:
SensorEventListener, ;
Sensor, , ;
, .
:
SENSOR_DELAY_FASTEST ;
SENSOR_DELAY_NORMAL ,
;
SENSOR_DELAY_GAME ,
, ,
;
SENSOR_DELAY_UI
Portrait Landscape .
, ,
:
SensorManager manager = (SensorManager)getSystemService(
Context.SENSOR_SERVICE);
List<Sensor> sensors = manager.getSensorList(Sensor.TYPE_ORIENTATION);
//
if(sensors.size() != 0) {
manager.registerListener(listener,
sensors.get(0), SensorManager.SENSOR_DELAY_GAME);
}
, .
,
, .
, , .
,
. , (lux).
13.
253
-
, SensorManager ,
,
. ,
, , . .
(LIGHT_CLOUDY, LIGHT_FULLMOON, LIGHT_NO_MOON, LIGHT_OVERCAST, LIGHT_SHADE,
LIGHT_SUNLIGHT, LIGHT_SUNLIGHT_MAX, LIGHT_SUNRISE .).
, . IDE Eclipse Android
New Android Project:
Project name: LightSensor;
Application name: Light sensor;
Package name: com.samples.hardware.light;
Create Activity: SensorActivity.
-
Ch13_LightSensor.
, .
main.xml
TextView: Light level, . main.xml 13.2.
13.2. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<TextView
android:text="@string/name0"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginRight="5px"
android:textSize="24sp"/>
<TextView
android:id="@+id/text0"
android:text="0.0"
android:layout_height="wrap_content"
android:gravity="center"
V.
254
android:layout_width="wrap_content"
android:textSize="24sp"/>
</LinearLayout>
, ,
. strings.xml 13.3.
13.3. strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Light sensor</string>
<string name="error_msg">This sensor is not available on device</string>
<string name="name0">Light level:</string>
</resources>
SensorActivity , SensorEventListener
.
SensorActivity 13.4.
13.4. SensorActivity.java
package com.samples.hardware.light;
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.app.AlertDialog;
android.content.Context;
android.content.DialogInterface;
android.hardware.Sensor;
android.hardware.SensorEvent;
android.hardware.SensorEventListener;
android.hardware.SensorManager;
android.os.Bundle;
android.widget.TextView;
import java.util.List;
public class SensorActivity extends Activity {
private TextView text0;
private SensorManager manager;
private List<Sensor> sensors;
@Override
public void onCreate(Bundle savedInstanceState) {
13.
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text0 = (TextView)findViewById(R.id.text0);
}
@Override
public void onStart() {
super.onStart();
manager =
(SensorManager)getSystemService(Context.SENSOR_SERVICE);
sensors =
manager.getSensorList(Sensor.TYPE_LIGHT);
if(sensors.size() != 0) {
manager.registerListener(listener,
sensors.get(0), SensorManager.SENSOR_DELAY_NORMAL);
}
else {
// ,
//
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.app_name);
builder.setMessage(R.string.error_msg);
builder.setPositiveButton(
"OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
SensorActivity.this.finish();
}
});
builder.show();
}
}
private SensorEventListener listener = new SensorEventListener(){
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) { }
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
//
text0.setText(String.valueOf(sensorEvent.values[0]));
}
};
}
255
V.
256
. ,
, .
.
. 13.2.
, , ,
, . 13.4
,
OK .
Android. , , . 13.3.
. 13.2.
. 13.3.
,
.
, .
-
Ch13_ProximitySensor.
13.
257
onCreate() SensorActivity (. 13.4), 13.5.
13.5. SensorActivity.java
...
public void onStart() {
super.onStart();
manager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
sensors = manager.getSensorList(Sensor.TYPE_PROXIMITY);
...
strings.xml, 13.6.
13.6. strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Proximity sensor</string>
<string name="error_msg">This sensor is not available on device</string>
<string name="name0">Proximity:</string>
</resources>
. .
. 13.4.
. 13.4.
V.
258
,
.
, ,
:
Pitch , ( X);
Roll ,
( Y);
Azimuth ,
( Z).
-
Ch13_OrientationSensor_Azimuth.
. , ,
.
Azimuth , onSensorChanged(),
onSensorChanged() 13.4. ,
SensorActivity, 13.7.
13.7. SensorActivity
...
public void onStart() {
super.onStart();
manager = SensorManager)getSystemService(Context.SENSOR_SERVICE);
sensors = manager.getSensorList(Sensor.TYPE_ORIENTATION);
...
strings.xml, 13.8.
13.8. strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Azimuth Orientation sensor</string>
<string name="error_msg">This sensor is not available on device</string>
<string name="name0">Azimuth:</string>
</resources>
13.
259
. 13.5.
. , .
. 13.5.
, . .
-
Ch13_OrientationSensor_Horizont.
main.xml TextView
. main.xml 13.9.
13.9. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
260
V.
android:orientation="horizontal"
android:layout_margin="10px"
android:gravity="center">
<TextView
android:text="@string/name1"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginRight="5px"
android:textSize="24sp"/>
<TextView
android:id="@+id/text1"
android:text="0.0"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_width="wrap_content"
android:textSize="24sp"/>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_margin="10px"
android:gravity="center">
<TextView
android:text="@string/name2"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginRight="5px"
android:textSize="24sp"/>
<TextView
android:id="@+id/text2"
android:text="0.0"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_width="wrap_content"
android:textSize="24sp"/>
</LinearLayout>
</LinearLayout>
strings.xml , 13.10.
13.
261
13.10. strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Horizontal orientation sensor</string>
<string name="error_msg">This sensor is not available on device</string>
<string name="name1">Pitch:</string>
<string name="name2">Roll:</string>
</resources>
13.11. SensorActivity.java
package com.samples.hardware.horizont;
import
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.app.AlertDialog;
android.content.Context;
android.content.DialogInterface;
android.hardware.Sensor;
android.hardware.SensorEvent;
android.hardware.SensorEventListener;
android.hardware.SensorManager;
android.os.Bundle;
android.widget.TextView;
java.util.List;
V.
262
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text1 = (TextView)findViewById(R.id.text1);
text2 = (TextView)findViewById(R.id.text2);
}
@Override
public void onStart() {
super.onStart();
manager =
(SensorManager)getSystemService(Context.SENSOR_SERVICE);
sensors =
manager.getSensorList(Sensor.TYPE_ORIENTATION);
if(sensors.size() != 0) {
manager.registerListener(listener,
sensors.get(0), SensorManager.SENSOR_DELAY_NORMAL);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.app_name);
builder.setMessage(R.string.error_msg);
builder.setPositiveButton(
"OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
SensorActivity.this.finish();
}
});
builder.show();
}
}
}
.
. . 13.6.
13.
263
. 13.6.
, ,
.
:
Longitudinal , ;
Lateral , ;
Vertical .
/2.
, ,
, - .
, .
SensorManager
STANDARD_GRAVITY,
. , ,
(GRAVITY_MERCURY, GRAVITY_VENUS .), (GRAVITY_MOON),
(GRAVITY_SUN) GRAVITY_DEATH_STAR_I!
.
-
Ch13_Accelerometer3DSensor.
. main.xml 13.12.
264
V.
13.12. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_margin="10px"
android:gravity="center">
<TextView
android:text="@string/name0"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginRight="5px"
android:textSize="24sp"/>
<TextView
android:id="@+id/text0"
android:text="0.0"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_width="wrap_content"
android:textSize="24sp"/>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_margin="10px"
android:gravity="center">
<TextView
android:text="@string/name1"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginRight="5px"
android:textSize="24sp"/>
13.
265
<TextView
android:id="@+id/text1"
android:text="0.0"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_width="wrap_content"
android:textSize="24sp"/>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_margin="10px"
android:gravity="center">
<TextView
android:text="@string/name2"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginRight="5px"
android:textSize="24sp"/>
<TextView
android:id="@+id/text2"
android:text="0.0"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_width="wrap_content"
android:textSize="24sp"/>
</LinearLayout>
</LinearLayout>
, 13.13.
13.13. strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">3D Accelerometer sensor</string>
<string name="error_msg">This sensor is not available on device</string>
<string name="name0">X axis:</string>
<string name="name1">Y axis:</string>
<string name="name2">Z axis:</string>
</resources>
V.
266
SensorActivity 13.14.
13.14. SensorActivity.java
public class SensorActivity extends Activity {
private TextView text0;
private TextView text1;
private TextView text2;
private SensorManager manager;
private List<Sensor> sensors;
private SensorEventListener listener = new SensorEventListener() {
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) { }
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
text0.setText(String.valueOf(sensorEvent.values[0]));
text1.setText(String.valueOf(sensorEvent.values[1]));
text2.setText(String.valueOf(sensorEvent.values[2]));
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text0 = (TextView)findViewById(R.id.text0);
text1 = (TextView)findViewById(R.id.text1);
text2 = (TextView)findViewById(R.id.text2);
}
@Override
public void onStart() {
...
sensors = manager.getSensorList(Sensor.TYPE_ACCELEROMETER);
...
}
}
. . 13.7.
13.
267
. 13.7.
,
Z,
, X Y
.
, .
,
.
, : Lateral, Longitudinal, Vertical.
T ().
Sensor :
MAGNETIC_FIELD_EARTH_MAX MAGNETIC_FIELD_EARTH_MIN,
. , .
.
-
Ch13_MagneticField3DSensor.
13.15.
268
V.
13.15. strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">3D Magnetic field sensor</string>
<string name="error_msg">This sensor is not available on device</string>
<string name="name0">X axis:</string>
<string name="name1">Y axis:</string>
<string name="name2">Z axis:</string>
</resources>
getSensorList(),
13.16.
13.16. SensorActivity
...
@Override
public void onStart() {
...
sensors = manager.getSensorList(Sensor.TYPE_MAGNETIC_FIELD);
...
. , , . , , ,
. , , . 13.8.
. 13.8.
13.
269
,
Android
,
: ,
, , , , .
,
,
, .
Android
. , . , ,
.
openintents.org,
Android. ,
Android Sensor Simulator.
:
http://code.google.com/p/openintents/wiki/SensorSimulator
, Android.
( )
, . 13.9.
Sensor Simulator,
Android, . Settings IP- , . 13.10. IP-
Sensor Simulator (. . 13.9).
Testing Sensor Simulator
Android , Connect (. 13.11).
Sensor Simulator Android, .
,
, ,
,
.
270
V.
. 13.10. IP-
. 13.11.
13.
271
Android , .
,
Android,
.
, , Android ,
,
.
14
.
,
.
. ,
, .
Android Window Service.
, , .
WindowManager android.view.
WindowManager getSystemService(),
Context.WINDOW_SERVICE:
WindowManager manager =
(WindowManager)getSystemService(Context.WINDOW_SERVICE);
, , WindowManager
, . WindowManager
getDefaultDisplay(), Display, .
Display ,
:
getDisplayId() ;
14.
273
getRefreshRate()
, ;
getHeight() ;
getWidth() .
Display . getRotation(), .
, Surface:
ROTATION_0;
ROTATION_180;
ROTATION_90;
ROTATION_270.
, ,
ROTATION_90 ROTATION_270,
.
getMetrics()
Display. out- DisplayMetrics.
DisplayMetrics
, .
DisplayMetrics ,
, :
heightPixels ;
widthPixels ;
scaledDensity ,
;
xdpi X (
);
ydpi Y (
);
densityDpi dpi (dots-per-inch,
).
densityDpi, xdpi ydpi, , , .
4- , , :
DENSITY_LOW ;
DENSITY_MEDIUM ;
DENSITY_HIGH ;
DENSITY_XHIGH .
, , ,
.
, .
V.
274
,
, :
WindowManager manager =
(WindowManager)getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
, , .
IDE Eclipse Android
New Android Project:
Project name: Window_DisplayInfo;
Application name: Window manager info;
Package name: com.samples.windowmanagerinfo;
Create Activity: WindowInfoActivity
-
Ch14_Window_DisplayInfo.
main.xml text, .
WindowInfoActivity onCreate() WindowManager,
. 14.1.
14.1. WindowInfoActivity.java
package com.samples.windowmanagerinfo;
import
import
import
import
import
import
import
android.app.Activity;
android.content.Context;
android.os.Bundle;
android.util.DisplayMetrics;
android.view.Display;
android.view.WindowManager;
android.widget.TextView;
14.
275
setContentView(R.layout.main);
TextView text = (TextView)findViewById(R.id.text);
WindowManager manager =
(WindowManager)getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
text.append("Density:\t" + metrics.density);
text.append("\nWidth pixels:\t" + metrics.widthPixels);
text.append("\nHeight pixels:\t" + metrics.heightPixels);
text.append("\nDensity dpi:\t" + metrics.densityDpi);
text.append("\nX dpi:\t" + metrics.xdpi);
text.append("\nY dpi:\t" + metrics.ydpi);
text.append("\nScaled density:\t" + metrics.scaledDensity);
}
}
Android . , . . 14.1.
. 14.1.
276
V.
Android ,
, ,
, ( )
.
, , ,
, , . .
WindowManager LayoutParams.
Android,
, .
LayoutParams ,
.
,
.
screenBrightness. float, 0 ( ) 1 ( ).
, , Settings.System.SCREEN_
BRIGHTNESS Settings.System.getInt() :
int brightness = android.provider.Settings.System.getInt(
getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS);
Settings.System.putInt(), :
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS, brightness);
, , , 0
( ) 255 ( ),
screenBrightness float 0 1,
.
screenBrightness LayoutParams
,
WindowManager.LayoutParams. getWindow()
Activity, Window, ,
getAttributes()
14.
277
WindowManager.LayoutParams.
screenBrightness , setAttributes():
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 0.7;
getWindow().setAttributes(params);
,
. IDE Eclipse Android
New Android Project:
Project name: Window_Brightness;
Application name: Set screen brightness;
Package name: com.samples.window.setscreenbright;
Create Activity: ScreenBrightnessActivity.
-
Ch14_Window_Brightness.
AndroidManifest.xml
, .
AndroidManifest.xml 14.2.
android.permission.WRITE_SETTINGS.
14.2. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.window.setscreenbright"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".ScreenBrightnessActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
</manifest>
V.
278
main.xml :
SeekBar seek ;
TexView text;
Button bSetBright.
14.3.
14.3. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SeekBar
android:id="@+id/seek"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10px"
android:max="100"
android:progress="50"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/text"
android:text="0.50"/>
<Button
android:id="@+id/bSetBright"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Set Brightness Preference"/>
</LinearLayout>
ScreenBrightessActivity
, , , .
ScreenBrightessActivity 14.4.
14.4. ScreenBrightessActivity.java
package com.samples.window.setscreenbright;
import android.app.Activity;
14.
import
import
import
import
import
import
import
import
import
android.os.Bundle;
android.provider.Settings.SettingNotFoundException;
android.view.View;
android.view.View.OnClickListener;
android.view.WindowManager;
android.widget.Button;
android.widget.SeekBar;
android.widget.SeekBar.OnSeekBarChangeListener;
android.widget.TextView;
279
V.
280
text.setText(percBrigh + "%");
bSetBright.setOnClickListener(this);
seek.setOnSeekBarChangeListener(this);
}
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
text.setText(arg1 + "%");
// ,
WindowManager.LayoutParams params = getWindow().getAttributes();
// screenBrightness,
// % (0...100)
// screenBrightness (0...1)
params.screenBrightness = (float)arg1 / 100;
//
getWindow().setAttributes(params);
brightness = arg1 * 255 / 100;
}
@Override
public void onStartTrackingTouch(SeekBar arg0) { }
@Override
public void onStopTrackingTouch(SeekBar arg0) { }
@Override
public void onClick(View arg0) {
//
android.provider.Settings.System.putInt(
getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS,
brightness);
}
}
Android . ,
, Set Brightness Preference.
. 14.2.
14.
281
. 14.2. ,
Window Service
.
, ,
.
, .
, Window
Service .
.
Android.
15
.
, , .
BatteryManager. , , getSystemService(),
, , .
Android Broadcast Intent ,
.
, BroadcastReceiver,
Intent.ACTION_BATTERY_CHANGED. ,
,
registerReceiver() Context.
Intent, onReceive() BroadcastReceiver, ,
Extra-, BatteryManager.
Extra-
:
EXTRA_SCALE ;
EXTRA_LEVEL , 0 EXTRA_SCALE. EXTRA_LEVEL EXTRA_SCALE , ;
EXTRA_TEMPERATURE ;
EXTRA_VOLTAGE ;
EXTRA_PRESENT boolean,
;
15.
283
EXTRA_TECHNOLOGY (, "Li-Ion",
);
EXTRA_ICON_SMALL ,
. . , .
Intent Extra-,
: EXTRA_HEALTH, EXTRA_STATUS EXTRA_PLUGGED.
EXTRA_HEALTH . :
BATTERY_HEALTH_GOOD ;
BATTERY_HEALTH_OVER_VOLTAGE (, );
BATTERY_HEALTH_OVERHEAT , ( );
BATTERY_HEALTH_UNSPECIFIED_FAILURE -
;
BATTERY_HEALTH_DEAD ;
BATTERY_HEALTH_UNKNOWN .
EXTRA_STATUS . , :
BATTERY_STATUS_CHARGING ;
BATTERY_STATUS_FULL ;
BATTERY_STATUS_NOT_CHARGING ;
BATTERY_STATUS_DISCHARGING ;
BATTERY_STATUS_UNKNOWN .
EXTRA_PLUGGED :
BATTERY_PLUGGED_AC ;
BATTERY_PLUGGED_USB USB.
, , BroadcastReceiver:
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Extra- Intent
...
}
}
BroadcastReceiver registerReceiver(), ,
, , "" Intent,
registerReceiver(receiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
V.
284
unregisterReceiver():
unregisterReceiver(receiver);
BatteryManager
android.permission.BATTERY_STATS.
, , , :
ACTION_BATTERY_LOW . Broadcast Intent
Low battery warning;
ACTION_BATTERY_OKAY . Broadcast Intent ;
ACTION_POWER_CONNECTED
;
ACTION_POWER_DISCONNECTED .
, . Android IDE Eclipse
New Android Project:
Project name: BatteryManagerInfo
Application name: Battery Manager
Package name: com.samples.hardware.batterymanager;
Create Activity: BatteryManagerActivity.
-
Ch15_BatteryManagerInfo.
AndroidManifest.xml
android.permission.BATTERY_STATS. AndroidManifest.xml
15.1.
15.1. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.hardware.batterymanager"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".BatteryManagerActivity"
android:label="@string/app_name">
15.
285
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission
android:name="android.permission.BATTERY_STATS" />
<uses-sdk android:minSdkVersion="10" />
</manifest>
main.xml
Button bStart, bStop Start Stop
TextView
text .
15.2.
15.2. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<Button
android:id="@+id/bStart"
android:layout_height="wrap_content"
android:text="Start"
android:layout_width="fill_parent"
android:layout_weight="1"/>
<Button
android:id="@+id/bStop"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="Stop"
android:layout_weight="1"/>
</LinearLayout>
<TextView
V.
286
android:id="@+id/text"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_margin="10px"/>
</LinearLayout>
android.app.Activity;
android.content.BroadcastReceiver;
android.content.Context;
android.content.Intent;
android.content.IntentFilter;
android.os.BatteryManager;
android.os.Bundle;
android.view.View;
android.widget.Button;
android.widget.TextView;
Button bStart;
Button bStop;
BroadcastReceiver receiver;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bStart = (Button)findViewById(R.id.bStart);
bStop = (Button)findViewById(R.id.bStop);
15.
text = (TextView)findViewById(R.id.text);
bStart.setOnClickListener(this);
bStop.setOnClickListener(this);
InitReceiver();
}
private void InitReceiver()
{
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(
BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(
BatteryManager.EXTRA_SCALE, -1);
int status = intent.getIntExtra(
BatteryManager.EXTRA_STATUS, -1);
int healt = intent.getIntExtra(
BatteryManager.EXTRA_HEALTH, -1);
int plugged = intent.getIntExtra(
BatteryManager.EXTRA_PLUGGED, -1);
String technology = intent.getStringExtra(
BatteryManager.EXTRA_TECHNOLOGY);
int icon = intent.getIntExtra(
BatteryManager.EXTRA_ICON_SMALL, -1);
float voltage = (float)intent.getIntExtra(
BatteryManager.EXTRA_VOLTAGE, -1) / 1000;
boolean present = intent.getBooleanExtra(
BatteryManager.EXTRA_PRESENT, false);
float temperature = (float)intent.getIntExtra(
BatteryManager.EXTRA_TEMPERATURE, -1) / 10;
//
String shealth = "Not reported";
switch (healt) {
case BatteryManager.BATTERY_HEALTH_DEAD:
shealth = "Dead";
break;
case BatteryManager.BATTERY_HEALTH_GOOD:
shealth = "Good";
break;
case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
shealth = "Over voltage";
break;
287
288
V.
case BatteryManager.BATTERY_HEALTH_OVERHEAT:
shealth = "Over heating";
break;
case BatteryManager.BATTERY_HEALTH_UNKNOWN:
shealth = "Unknown";
break;
case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
shealth = "Unspecified failure";
break;
}
//
String sStatus = "Not reported";
switch (status) {
case BatteryManager.BATTERY_STATUS_CHARGING:
sStatus = "Charging";
break;
case BatteryManager.BATTERY_STATUS_DISCHARGING:
sStatus = "Discharging";
break;
case BatteryManager.BATTERY_STATUS_FULL:
sStatus = "Full";
break;
case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
sStatus = "Not Charging";
break;
case BatteryManager.BATTERY_STATUS_UNKNOWN:
sStatus = "Unknown";
break;
}
//
String splugged = "Not Reported";
switch (plugged) {
case BatteryManager.BATTERY_PLUGGED_AC:
splugged = "On AC";
break;
case BatteryManager.BATTERY_PLUGGED_USB:
splugged = "On USB";
break;
}
int chargedPct = (level * 100) / scale;
String batteryInfo = "Battery Info:" +
"\nHealth: " + shealth +
"\nStatus: " + sStatus +
15.
289
.
Start ,
. -
. . 15.1.
V.
290
. 15.1.
, Activity, .
Intent ACTION_POWER_USAGE_SUMMARY,
, :
Intent intent = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);
startActivity(intent);
Activity
, . IDE Eclipse
Android New Android Project :
Project name: BatteryUsageSummary;
Application name: Battery Usage;
Package name: com.samples.hardware.batteryusage;
Create Activity: BatteryUsageActivity.
-
Ch15_BatteryUsageSummary.
main.xml
Battery Usage bBatteryUsage
Activity, . 15.4.
15.
291
15.4. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Battery Usage"
android:id="@+id/bBatteryUsage"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_margin="5px"/>
</LinearLayout>
onClick() , Intent
Activity. 15.5.
15.5. BatteryUsageActivity.java
package com.samples.hardware.batteryusage;
import
import
import
import
import
import
android.app.Activity;
android.content.Intent;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
V.
292
. 15.2. Activity,
Battery Manager, , .
:
, , .
Android
,
.
16
. Power Service.
,
. , , ,
,
. ,
,
.
Android.
.
getSystemService() Context.POWER_SERVICE:
PowerManager manager =
(PowerManager)getSystemService(Context.POWER_SERVICE);
, PowerManager:
goToSleep(long time) .
;
isScreenOn() true, -
;
reboot(String reason) .
,
.
294
V.
,
(Wake Lock).
,
.
.
PowerManager newWakeLock(int
flags, String tag), :
, ;
, ( , ).
, . , . .
:
PARTIAL_WAKE_LOCK , , ,
;
SCREEN_BRIGHT_WAKE_LOCK , , , ;
SCREEN_DIM_WAKE_LOCK , ,
( ) ;
FULL_WAKE_LOCK ,
.
PARTIAL_WAKE_LOCK .
.
, , :
ACQUIRE_CAUSES_WAKEUP ,
;
ON_AFTER_RELEASE . , , , ,
. SCREEN_
BRIGHT_WAKE_LOCK,
.
newWakeLock() WakeLock,
. , :
acquire() ;
PowerManager
16.
295
acquire(long timeout)
, timeout,
;
release() ;
setReferenceCounted(boolean value) . ,
true, . aquire() release(). aquire() 1, release(), , .
android.permission.WAKE_LOCK .
PowerManager,
getSystemService() Context.POWER_SERVICE. newWakeLock() PowerManager.
WakeLock acquire() release()
, , . :
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
WakeLock wl = pm.newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "Screen Bright Wake Lock");
// Wake Lock
wl.acquire();
...
// Wake Lock
wl.release();
-
Ch16_PowerManager.
AndroidManifest.xml
16.1.
android.permission.WAKE_LOCK,
296
V.
16.1. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.hardware.powermanager"
android:versionCode="1"
android:versionName="1.0">
<application
android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".PowerManagerActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
</manifest>
main.xml
, , strings.xml 16.2.
16.2. strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, PowerManagerActivity!</string>
<string name="app_name">Power Manager</string>
<string name="partial_wake_lock">Partial Wake Lock</string>
<string name="screen_bright_wake_lock">Screen Bright Wake Lock</string>
<string name="screen_dim_wake_lock">Screen Dim Wake Lock</string>
<string name="full_wake_lock">Full Wake Lock</string>
</resources>
main.xml 16.3.
16.3. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
16.
297
android:layout_height="fill_parent">
<Button
android:text="@string/partial_wake_lock"
android:id="@+id/bPartialWL"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_margin="5px"/>
<Button
android:text="@string/screen_bright_wake_lock"
android:id="@+id/bScreenBrightWL"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_margin="5px"/>
<Button
android:text="@string/screen_dim_wake_lock"
android:id="@+id/bScreenDimWL"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_margin="5px"/>
<Button
android:text="@string/full_wake_lock"
android:id="@+id/bFullWL"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_margin="5px"/>
</LinearLayout>
PowerManagerActivity
PowerManager. onCLick(), , .
PowerManagerActivity 16.4.
onCreate()
16.4. PowerManagerActivity.java
package com.samples.hardware.powermanager;
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.content.Context;
android.os.Bundle;
android.os.PowerManager;
android.os.PowerManager.WakeLock;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.Toast;
V.
298
16.
299
wakeLock = manager.newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK, wlName);
break;
case R.id.bScreenDimWL:
wlName = getResources().getString(
R.string.screen_dim_wake_lock);
wakeLock = manager.newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK, wlName);
break;
case R.id.bFullWL:
wlName = getResources().getString(
R.string.full_wake_lock);
wakeLock = manager.newWakeLock(
PowerManager.FULL_WAKE_LOCK, wlName);
break;
}
Toast.makeText(this, wlName + " ON", Toast.LENGTH_LONG).show();
wakeLock.acquire();
}
}
.
. 16.1.
. 16.1.
300
V.
, .
, , .
, . ,
, .
, Android .
VI
17
, , , , Activity. , .
,
Android , .
ActivityManager
Activity
ActivityManager, android.app.
ActivityManager , Android, getSystemService(),
ACTIVITY_SERVICE, Context:
ActivityManager manager =
(ActivityManager)getSystemService(ACTIVITY_SERVICE);
, ActivityManager
, ActivityManager Activity,
.
. , , .
ActivityManager . ,
,
Android,
,
.
VI.
304
,
. , . IDE Eclipse Android New Android Project:
Project name: ActivityManager;
Application name: Activity Manager Info;
Package name: com.samples.os.activitymanager;
Create Activity: SystemInfoListActivity.
-
Ch17_ActivityManager.
Activity
SystemInfoListActivity, , SystemInfoItemActivity
, .
AndroidManifest.xml 17.1.
17.1. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.os.activitymanager"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".SystemInfoListActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SystemInfoItemActivity"
android:label="@string/app_name">
</activity>
</application>
<uses-permission
android:name="android.permission.GET_TASKS">
</uses-permission>
<uses-sdk android:minSdkVersion="10" />
</manifest>
17.
305
, . . , android.R.layout.simple_list_item_1.
7 :
Device Configuration Info ;
Memory Info ;
Running Processes ;
Running Services ;
Running Tasks ;
Recent Tasks ;
Processes in Error State , .
,
strings.xml ( res/values), 17.2.
17.2. strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">
Activity Manager Info</string>
<string name="itemDeviceConfigInfo">
Device Configuration Info</string>
<string name="itemMemoryInfo">
Memory Info</string>
<string name="itemRecentTasks">
Recent Tasks</string>
<string name="itemRunningAppProcesses">
Running Processes</string>
<string name="itemProcessesInErrorState">
Processes in Error State</string>
<string name="itemRunningServices">
Running Services</string>
<string name="itemRunningTasks">
Running Tasks</string>
</resources>
SystemInfoListActivity,
ListActivity, onListItemClick(). Intent,
, SystemInfoItemActivity .
SystemInfoListActivity 17.3.
VI.
306
17.3. SystemInfoListActivity.java
package com.samples.os.activitymanager;
import
import
import
import
import
import
import
android.app.ListActivity;
android.content.Intent;
android.os.Bundle;
android.view.View;
android.widget.ArrayAdapter;
android.widget.ListView;
android.widget.Toast;
17.
307
, , , item.xml.
TextView, .
item.xml 17.4.
17.4. item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_margin="5px"/>
</LinearLayout>
SystemInfoItemActivity
, , if...else
.
.
SystemInfoItemActivity 17.5.
17.5. SystemInfoItemActivity.java
package com.samples.os.activitymanager;
import java.util.List;
import
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.app.ActivityManager;
android.app.ActivityManager.ProcessErrorStateInfo;
android.app.ActivityManager.RecentTaskInfo;
android.app.ActivityManager.RunningAppProcessInfo;
android.app.ActivityManager.RunningServiceInfo;
android.app.ActivityManager.RunningTaskInfo;
android.content.pm.ConfigurationInfo;
android.content.res.Configuration;
android.os.Bundle;
android.widget.TextView;
VI.
308
17.
309
, ,
Android.
, . 17.1.
. 17.1.
,
, .
ActivityManager getDeviceConfigurationInfo(), , .
ConfigurationInfo,
android.content.pm.
ConfigurationInfo . ,
, , QWERTY- .
ConfigurationInfo ,
. , , reqGlEsVersion
OPEN GL. reqInputFeatures
310
VI.
, , :
INPUT_FEATURE_FIVE_WAY_NAV , ;
INPUT_FEATURE_HARD_KEYBOARD ,
.
ConfigurationInfo , , :
reqKeyboardType ;
reqNavigation ;
reqTouchScreen .
reqKeyboardType, , :
KEYBOARD_12KEY
12 ;
KEYBOARD_QWERTY (QWERTY);
KEYBOARD_NOKEYS ;
KEYBOARD_UNDEFINED .
reqNavigation , . ,
, 4
, -. reqNavigation, , :
NAVIGATION_NONAV ;
NAVIGATION_DPAD ;
NAVIGATION_TRACKBALL ;
NAVIGATION_WHEEL ;
NAVIGATION_UNDEFINED .
reqTouchScreen .
, , .
. : .
, PC.
.
, . .
,
.
, .
, . . ,
17.
311
, , , .
, reqTouchScreen :
TOUCHSCREEN_STYLUS ;
TOUCHSCREEN_FINGER ;
TOUCHSCREEN_NOTOUCH ;
TOUCHSCREEN_UNDEFINED .
ConfigurationInfo 17.6 ( SystemInfoItemActivity 17.5).
17.6. SystemInfoItemActivity
if (action.equals(
getResources().getString(R.string.itemDeviceConfigInfo))) {
ConfigurationInfo config = manager.getDeviceConfigurationInfo();
text.append("GlEs Version:\t" + config.getGlEsVersion());
int keyType = config.reqKeyboardType;
text.append("\nKeyboard Type:\t");
switch (keyType) {
case Configuration.KEYBOARD_UNDEFINED:
text.append("Undefined");
break;
case Configuration.KEYBOARD_NOKEYS:
text.append("No keys");
break;
case Configuration.KEYBOARD_QWERTY:
text.append("QWERTY");
break;
case Configuration.KEYBOARD_12KEY:
text.append("12 Key");
break;
}
int nav = config.reqNavigation;
text.append("\nNavigation:\t");
switch (nav) {
case Configuration.NAVIGATION_DPAD:
text.append("D pad");
break;
case Configuration.NAVIGATION_TRACKBALL:
text.append("Trackball");
break;
VI.
312
case Configuration.NAVIGATION_WHEEL:
text.append("Wheel");
break;
case Configuration.NAVIGATION_UNDEFINED:
text.append("Undefined");
break;
}
int touch = config.reqTouchScreen;
text.append("\nTouch Screen:\t");
switch (touch) {
case Configuration.TOUCHSCREEN_FINGER:
text.append("Finger");
break;
case Configuration.TOUCHSCREEN_NOTOUCH:
text.append("Notouch");
break;
case Configuration.TOUCHSCREEN_STYLUS:
text.append("stylus");
break;
case Configuration.TOUCHSCREEN_UNDEFINED:
text.append("Undefined");
break;
}
}
. 17.2.
17.
313
Android.
Devices Configuration Info.
, :
OPEN GL, , , .
. 17.2.
, ,
android.app :
MemoryInfo ;
RecentTaskInfo ;
RunningAppProcessInfo ;
RunningServiceInfo
;
RunningTaskInfo ;
ProcessErrorStateInfo , .
ActivityManager,
.
ActivityManager :
getMemoryInfo() MemoryInfo ;
getProcessMemoryInfo()
ActivityManager.MemoryInfo .
,
.
ActivityManager.MemoryInfo , :
availMem , ;
threshold ,
"" , ;
lowMemory , true, .
, MemoryInfo,
getMemoryInfo(), out-
ActivityManager.MemoryInfo. getMemoryInfo()
VI.
314
,
.
ActivityManager.MemoryInfo SystemInfoItemActivity 17.7.
ActivityManager.MemoryInfo
17.7. SystemInfoItemActivity
else if (action.equals(
getResources().getString(R.string.itemMemoryInfo))) {
// ActivityManager.MemoryInfo
MemoryInfo memInfo =
new ActivityManager.MemoryInfo();
// memInfo
// getMemoryInfo()
manager.getMemoryInfo(memInfo);
text.append("Available Memory:\t" + memInfo.availMem + " B");
text.append("\nTreshold Memory:\t" + memInfo.threshold + " B");
}
. 17.3.
17.
315
RunningAppProcessInfo . , .
, , . , .
Android
[1].
, ,
getRunningAppProcesses(), ,
RunningAppProcessInfo.
RunningAppProcessInfo , : processName , pid
PID (Process ID), pkgList
.
RunningAppProcessInfo 17.8.
ActivityManager
17.8. SystemInfoItemActivity
else if (action.equals(
getResources().getString(R.string.itemRunningAppProcesses))) {
List<RunningAppProcessInfo> runningAppProcesses =
manager.getRunningAppProcesses();
text.append("Running Processes:");
for (int i = 0; i < runningAppProcesses.size(); i++) {
text.append("\n\t" + runningAppProcesses.get(i).processName);
}
}
,
Running Processes. . 17.4.
, .
- , ,
, , ,
, .
VI.
316
. 17.4.
RunningServiceInfo ,
.
ActivityManager getRunningServices(), , ,
RunningServiceInfo. , getRunningAppProcesses(), getRunningServices() , .
RunningServiceInfo ,
RunningAppProcessInfo, , ,
clientCount , , foreground
.
RunningServiceInfo 17.9.
17.9. SystemInfoItemActivity
else if (action.equals(
getResources().getString(R.string.itemRunningServices))){
List<RunningServiceInfo> runningServices =
manager.getRunningServices(20);
text.append("Running Services:");
for (int i = 0; i < runningServices.size(); i++) {
text.append("\n\t" + runningServices.get(i).process);
}
}
17.
317
. 17.5.
Running Services, ,
, , . 17.5.
RunningTaskInfo , .
, ,
ActivityManager getRunningTasks(),
RunningTaskInfo.
,
.
RunningTaskInfo , :
id ;
baseActivity , ;
description ;
numActivities Activity ;
numRunning Activity, ;
topActivity ,
.
.
VI.
318
AndroidManifest.xml
.
RunningTaskInfo 17.10.
android.permission.GET_TASKS.
17.10. SystemInfoItemActivity
else if (action.equals(
getResources().getString(R.string.itemRunningTasks))) {
List<RunningTaskInfo> runTasks = manager.getRunningTasks(10);
text.append("Running Tasks:");
for (int i = 0; i < runTasks.size(); i++) {
RunningTaskInfo runTask = runTasks.get(i);
text.append("\nTask ID:\t" + runTask.id);
text.append("\n\tBase Activity:\n\t\t" +
runTask.baseActivity.getShortClassName());
text.append("\n\tNum Activities: " + runTask.numActivities);
text.append("\n\tNum Running: " + runTask.numRunning);
}
}
Running Tasks ,
, . 17.6.
. 17.6.
17.
319
RecentTaskInfo , .
ActivityManager getRecentTasks(), RecentTaskInfo. getRunningTasks(),
getRecentTasks() .
,
:
RECENT_WITH_EXCLUDED ;
RECENT_IGNORE_UNAVAILABLE , , .
API Level 11 (Android SDK 3.0).
RecentTaskInfo :
id , ;
description ;
baseIntent Intent, ;
origActivity , .
RecentTaskInfo 17.11.
17.11. SystemInfoItemActivity
else if (action.equals(
getResources().getString(R.string.itemRecentTasks))) {
List<RecentTaskInfo> recTasks = manager.getRecentTasks(10, 0);
text.append("Recent Tasks:");
for (int i = 0; i < recTasks.size(); i++) {
RecentTaskInfo recTask = recTasks.get(i);
text.append("\n\tTask ID:\t" + recTask.id);
text.append("\n\tBase Intent:\t" + recTask.baseIntent.getAction());
if (recTask.origActivity != null) {
text.append("Orig Activity:\t" +
recTask.origActivity.getShortClassName());
}
}
}
VI.
320
. 17.7.
Recent Tasks,
,
Intent, . . 17.7.
.
ProcessErrorStateInfo.
, ,
ActivityManager getProcessesInErrorState(), ProcessErrorStateInfo.
ProcessErrorStateInfo , RunningAppProcessInfo. , , :
processName , ;
pid , , 0;
uid (User ID),
. , . . UID;
tag Activity, , ;
condition , - ;
shortMsg ;
17.
321
longMsg ;
stackTrace , .
ProcessErrorStateInfo
17.12.
17.12. SystemInfoItemActivity
else if (action.equals(
getResources().getString(R.string.itemProcessesInErrorState))) {
List<ProcessErrorStateInfo> procError =
manager.getProcessesInErrorState();
text.append("ProcessesInErrorState:");
if (procError != null) {
for (int i = 0; i < procError.size(); i++) {
text.append("\n\t" + procError.get(i).processName);
}
}
else {
text.append("\tNone");
}
}
Processes in Error
State. ,
. . 17.8.
. 17.8.
VI.
322
, getProcessesInErrorState()
null, .
Android
Android, Linux-,
. , , Development Tools
Terminal Emulator, . 17.9.
. 17.9. Android
. 17.10. Android
17.
323
Linux- df ,
.
.
IDE Eclipse Android New Android Project:
Project name: AndroidOSInfo;
Application name: Read Android OS Info;
Package name: com.samples.hardware.osinfo;
Create Activity: OsInfoListActivity.
-
Ch17_AndroidOSInfo.
, .
Activity OsInfoListActivity,
, OsInfoItemActivity
, .
17.13.
17.13. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.hardware.osinfo"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />
<application
324
VI.
android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".OsInfoListActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OsInfoItemActivity"
android:label="@string/app_name">
</activity>
</application>
</manifest>
OsInfoListActivity , 4 :
OS Version Information ;
CPU Information ;
Memory Information ;
Disc Space Information .
,
strings.xml, res/values .
strings.xml 17.14.
17.14. strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Read Android OS Info</string>
<string name="os_version_info">OS Version Information</string>
<string name="cpu_info">CPU Information</string>
<string name="memory_info">Memory Information</string>
<string name="disc_space_info">Disc Space Information</string>
</resources>
,
. OsInfoListActivity
17.15.
17.15. OsInfoListActivity.java
package com.samples.hardware.osinfo;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
17.
import
import
import
import
325
android.view.View;
android.widget.ArrayAdapter;
android.widget.ListView;
android.widget.Toast;
VI.
326
17.16. OsInfoItemActivity.java
package com.samples.hardware.osinfo;
import java.io.IOException;
import java.io.InputStream;
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.widget.TextView;
android.widget.Toast;
17.
327
}
//
private void PrintInfo(String[] args)
{
try{
ProcessBuilder builder = new ProcessBuilder(args);
Process process = builder.start();
InputStream inputStream = process.getInputStream();
byte[] b = new byte[4096];
while(inputStream.read(b) != -1){
text.append(new String(b));
}
inputStream.close();
}
catch(IOException e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
Android. , . , ,
. 17.11.
. 17.11.
328
VI.
. , ,
Android, . , Android ARM .
Android
, , ""
Android Android 3.0
2 .
, Android
SDK . , ,
. , Linux , .
,
.
18
Notification Service
, - , .
.
, ,
.
- , , SMS, .
.
Android
Notification Service. NotificationManager. NotificationManager
, getSystemService()
Context.NOTIFICATION_SERVICE:
NotificationManager manager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
:
;
;
;
;
.
NotificationManager
:
notify() ;
cancel() ;
cancelAll() .
VI.
330
, cancelAll(), id,
, tag
String. ,
, . , .
, notify(), , , Notification, .
Notification, notify() NotificationManager.
Notification .
Notification ,
:
icon , ;
sound ;
tickerText , "" ;
when .
. Notification :
ledARGB ;
ledOnMS
;
ledOffMS
.
Notification default
. :
DEFAULT_LIGHTS ;
DEFAULT_SOUND ;
DEFAULT_VIBRATE ;
DEFAULT_ALL .
Notification . ,
18.
331
flags, :
FLAG_AUTO_CANCEL , ,
;
FLAG_FOREGROUND_SERVICE , , , ;
FLAG_HIGH_PRIORITY , ,
;
FLAG_INSISTENT ,
,
;
FLAG_NO_CLEAR , , Clear;
FLAG_ONGOING_EVENT , ,
(, , , );
FLAG_ONLY_ALERT_ONCE ,
;
FLAG_SHOW_LIGHTS ,
.
, ,
.
, :
Notification notification = new Notification();
//
notification.icon = android.R.drawable.ic_notification_overlay;
//
notification.tickerText = "New Notification";
//
notification.when = System.currentTimeMillis();
//
notification.flags =
Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_AUTO_CANCEL;
, , . Notification
setLatestEventInfo(), :
Context Activity;
;
;
PendingIntent, , .
VI.
332
:
Intent intent = new Intent(
getApplicationContext, NotificationActivity.class);
PendingIntent pendIntent = PendingIntent.getActivity(
getApplicationContext(), 0, intent, 0);
notification.setLatestEventInfo(this, "Notification!",
"Notification from app", pendIntent);
.
notify() NotificationManager.
, , Notification:
NotificationManager manager = (NotificationManager)getSystemService(
Context.NOTIFICATION_SERVICE);
manager.notify(1, notification);
-
Ch18_NotificationManager.
main.xml
:
Create Notification c bCreate ;
Clear Notification c bClear .
main.xml 18.1.
18.1. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:gravity="center">
<Button
android:id="@+id/bCreate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Create Notification"/>
18.
333
<Button
android:id="@+id/bClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Clear Notification"/>
</LinearLayout>
NotificationActivity ,
Notification . NotificationActivity 18.2.
18.2. NotificationActivity.java
package com.samples.notificationmanager;
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.app.Notification;
android.app.NotificationManager;
android.app.PendingIntent;
android.content.Context;
android.content.Intent;
android.os.Bundle;
android.view.View;
android.widget.Button;
VI.
334
bClear.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bCreate:
//
manager = (NotificationManager)getSystemService(
Context.NOTIFICATION_SERVICE);
//
Notification notification = new Notification();
//
notification.icon = android.R.drawable.ic_notification_overlay;
notification.tickerText = "New Notification";
notification.when = System.currentTimeMillis();
//
//
Intent intent = new Intent(this, NotificationActivity.class);
PendingIntent pendIntent = PendingIntent.getActivity(
getApplicationContext(), 0, intent, 0);
notification.setLatestEventInfo(this, "Notification!",
"Notification from app", pendIntent);
//
manager.notify(ID_NOTIFY, notification);
break;
case R.id.bClear:
//
manager.cancel(ID_NOTIFY);
break;
}
}
}
18.
335
. 18.1. ,
. , , .
, .
. Notification Service .
Alarm Service
,
.
19
Alarm Service
, .
Alarm Service .
, , , . . .
Alarm Service
AlarmManager, :
AlarmManager manager = (AlarmManager)getSystemService(
Context.ALARM_SERVICE);
AlarmManager ,
, , .
AlarmManager , .
AlarmManager :
cancel() ;
setTime() ;
setTimeZone() ;
set() ;
setRepeating() ;
setInexactRepeating() . , , , , ,
.
19.
337
, . . , Service:
public class AlarmService extends Service { ... }
Intent, , :
public class AlarmManagerActivity extends Activity
{
...
Intent intent = new Intent(
AlarmManagerActivity.this, AlarmService.class);
PendingIntent pendingIntent = PendingIntent.getService(
getApplicationContext(), 0, intent, 0);
...
VI.
338
}
. ,
, 5 .
:
long time = SystemClock.elapsedRealtime() + 5000;
Calendar.
. , ,
10 , . :
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
long time = calendar.getTimeInMillis();
manager.setRepeating(AlarmManager.RTC_WAKEUP, time,
AlarmManager.INTERVAL_HOUR, pendingIntent);
,
. IDE Eclipse Android New
Android Project:
Project name: AlarmManager;
Application name: Alarm Manager;
Package name: com.samples.alarm.alarmmanager;
Create Activity: AlarmManagerActivity.
AlarmManager
-
Ch19_AlarmManager.
, AlarmManagerActivity, AlarmService.
AndroidManifest.xml <service>
, .
AndroidManifest.xml 19.1.
19.1. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples.alarm.alarmmanager"
android:versionCode="1"
android:versionName="1.0">
<application
19.
339
android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AlarmManagerActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".AlarmService">
</service>
</application>
</manifest>
main.xml
:
Start bStart;
Cancel bCancel;
Stop bStop.
main.xml 19.2.
19.2. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:gravity="center">
<Button
android:id="@+id/bStart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start"/>
<Button
android:id="@+id/bCancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Cancel"/>
<Button
android:id="@+id/bStop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Stop"/>
VI.
340
</LinearLayout>
AlarmManagerActivity
, . AlarmManagerActivity 19.3.
19.3. AlarmManagerActivity.java
package com.samples.alarm.alarmmanager;
import java.util.Calendar;
import
import
import
import
import
import
import
android.app.Activity;
android.app.AlarmManager;
android.app.PendingIntent;
android.content.Intent;
android.os.Bundle;
android.view.View;
android.widget.Button;
19.
341
switch (v.getId()) {
case R.id.bStart:
pendingIntent = PendingIntent.getService(
getApplicationContext(), 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 5);
manager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
5000,
pendingIntent);
break;
case R.id.bCancel:
manager.cancel(pendingIntent);
break;
case R.id.bStop:
this.stopService(intent);
break;
}
}
}
AlarmService, , (Toast
Notificaton). count
. onStart()
,
.
, . ,
. AlarmService 19.4.
19.4. AlarmService.java
package com.samples.alarm.alarmmanager;
import
import
import
import
android.app.Service;
android.content.Intent;
android.os.IBinder;
android.widget.Toast;
VI.
342
private int count;
@Override
public void onCreate() {
count = 0;
Toast.makeText(this, "Create service",
Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent intent) {
Toast.makeText(this, "Bind service",
Toast.LENGTH_LONG).show();
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Destroy service",
Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
count++;
Toast.makeText(this, "Notify from AlarmManager #" + count,
Toast.LENGTH_LONG).show();
}
@Override
public boolean onUnbind(Intent intent) {
Toast.makeText(this, "Unbind service",
Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
}
Android. Start . 5
, . 19.1.
.
Cancel, AlarmManagerActivity
AlarmManager.cancel() , , . .
onDestroy() . Start,
, .
19.
343
. 19.1.
Stop stopService()
. AlarmManager
cancel(), ,
. , AlarmManagerActivity
cancel() stopService().
, , , .
. Alarm Service .
, , , Android:
.
20
API
Android : Clipboard Service Text To Speech.
, Clipboard Service .
Clipboard Service
ClipboardManager, android.text.
.
ClipboardManager , , ,
getSystemService(), CLIPBOARD_SERVICE:
ClipboardManager manager =
(ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
ClipboardManager , , .
ClipboardManager :
getText() , ;
setText() , , ;
hasText() true, , false
.
20. API
345
,
. IDE Eclipse Android
New Android Project:
Project name: ClipboardManager;
Application name: Clipboard Service;
Package name: com.samples.clipboardmanager;
Create Activity: ClipboardManagerActivity.
-
Ch20_ClipboardManager.
main.xml :
EditText textCopy ;
Button bCopy Copy
;
Button bPaste Paste ;
TextView textPaste
.
main.xml 20.1.
20.1. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:id="@+id/textCopy"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter text"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<Button
android:id="@+id/bCopy"
android:layout_height="wrap_content"
android:text="Copy"
android:layout_width="fill_parent"
android:layout_weight="1"/>
<Button
android:id="@+id/bPaste"
android:layout_height="wrap_content"
VI.
346
android:layout_width="fill_parent"
android:fadeScrollbars="false"
android:layout_weight="1" android:text="Paste"/>
</LinearLayout>
<TextView
android:id="@+id/textPaste"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"/>
</LinearLayout>
ClipboardManagerActivity
: onCreate() ClipboardManager.
onClick()
setText(), ,
getText() ClipboardManager.
20.2.
20.2. ClipboardManagerActivity.java
package com.samples.clipboardmanager;
import
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.text.ClipboardManager;
android.view.View;
android.widget.Button;
android.widget.EditText;
android.widget.TextView;
20. API
347
Android.
, . . 20.1.
. 20.1.
VI.
348
Android Text To Speech (TTS),
.
,
.
,
Android TTS, ,
Android 1.6 (API Level 4).
.
. ,
Settings | Text-to-speech | Install voice data (. 20.2),
.
. 20.2.
20. API
349
.
speak() : , . ,
TTS , . TTS
, . TextToSpeech
:
QUEUE_ADD ,
;
QUEUE_FLUSH , ,
, .
TTS , , TextToSpeech
:
getLanguage() Locale, , TTS;
setLanguage() ,
Locale, TTS;
isLanguageAvailable() , ,
TTS.
,
, .
TextToSpeech .
Text To
Speech, OnInitListener. onInit(),
Text To Speech.
TextToSpeech :
ERROR;
SUCCESS.
TextToSpeech ,
. TextToSpeech
:
TextToSpeech.OnInitListener.
TextToSpeech.OnInitListener :
public class TtsActivity extends Activity implements OnInitListener {
@Override
public void onCreate(Bundle savedInstanceState) {
...
VI.
350
// TextToSpeech
// OnInitListener
tts = new TextToSpeech(getApplicationContext(), this);
...
}
// onInit OnInitListener
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
//
}
...
}
speak(), , :
String text = "Hello";
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
, TextToSpeech
shutdown(), .
.
IDE Eclipse Android New Android Project:
Project name: TextToSpeech;
Application name: Text to speech;
Package name: com.samples.api.tts;
Create Activity: TtsActivity.
-
Ch20_TextToSpeech.
main.xml :
Button c bSpeech;
EditText c text, .
main.xml 20.3.
20.3. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Speech"
20. API
351
android:id="@+id/bSpeech"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/hello"/>
</LinearLayout>
TtsActivity . onCreate()
TextToSpeech. onClick() speak(), ,
EditText.
20.4.
20.4. TtsActivity.java
package com.samples.api.tts;
import
import
import
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.speech.tts.TextToSpeech;
android.speech.tts.TextToSpeech.OnInitListener;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.EditText;
VI.
352
Android . . 20.3.
20. API
353
Speak.
. ,
, Text To Speech,
!
ftp://85.249.45.166/9785977506663.zip1
, .
, IDE Eclipse . File | Switch Workspace | Other
Workspace Launcher , (. 1.1).
Android SDK. Window |
Preferences. Preferences Android . SDK Location ,
Android SDK. Browse Android SDK, . 1.2.
, ,
-. File |
Import Import General | Existing
Projects into Workspace, . 1.3. Next.
. 1.1. Eclipse
1
www.bhv.ru.
356
. 1.3.
. 1.4.
. 1.5.
357
358
. Google Android: .
Accessibility Service 16
Account Service 17
Activity Action Intent 18
Activity Service 16
Alarm Service 16
Android Virtual Device 197
Audio Service 17
Battery Manager 17
Broadcast Intent 18, 282
Power Service 17
Clipboard Service 16
Connectivity Service 17
D
DDMS (Dalvik Debug Monitor Server) 12, 46,
49, 198
Device_policy Service 18
Download Service 17
Dropbox Service 17
F
N
NFC Servic 17
Notification Service 16
Search Service 16
Sensor Service 17
Sensor Simulator 269
SMS (Short Message Service) 62
Storage Service 17
T
Telephony Service 17
Text To Speech 348
UI Mode Service 16
Vibrator Service 17
W
I, K
Input Method Service 16
Keyguard Service 16
Wallpaper Service 16
Wifi Service 17
Window Service 16
362
:
Browser 19
CallLog 19
ContactsContract 19
Mediastore 19
Settings 19
SQLite 19
UserDictionary 19
27
:
Android SDK 9
Google API 9, 141, 176
Text To Speech 348
WebKit 85, 92
:
BSSID 109, 118
SSID 118
WEP 124
:
Camera.PictureCallback 236
Camera.ShutterCallback 236
LocationListener 153
OnInitListener 349
SensorEventListener 251
SurfaceHolder 224
TextBasedSmsColumns 79
WindowManager 272
:
ACTION_BATTERY_LOW 284
ACTION_BATTERY_OKAY 284
ACTION_CALL 53
ACTION_CALL_BUTTON 53
ACTION_DIAL 53
ACTION_IMAGE_CAPTURE 221
ACTION_PICK_WIFI_NETWORK 115
ACTION_POWER_CONNECTED 284
ACTION_POWER_
DISCONNECTED 284
ACTION_POWER_USAGE_
SUMMARY 290
ACTION_VIDEO_CAPTURE 221
ACTION_WIFI_IP_SETTINGS 115
ACTION_WIFI_SETTINGS 115
ACTION_WIRELESS_SETTINGS 115
INTENT_ACTION_STILL_IMAGE_
CAMERA 221
INTENT_ACTION_VIDEO_
CAMERA 221
NETWORK_STATE_CHANGED_
ACTION 108
SCAN_RESULTS_AVAILABLE_
ACTION 128
SUPPLICANT_CONNECTION_
CHANGE_ACTION 109
SUPPLICANT_STATE_CHANGED_
ACTION 109
WIFI_STATE_CHANGED_
ACTION 108
197
:
Conversations 74
Draft 74
Failed 74
Inbox 74
Outbox 74
Queued 74
Sent 74
Undelivered 74
174
:
ActivityManager 303
AlarmManager 336
AutoFocusCallback 241
BatteryManager 282
BroadcastReceiver 58, 128, 282
Camera 213
Camera.Parameters 214
CdmaCellLocation 28
CellLocation 27
ClipboardManager 344
ConfigurationInfo 309
ConnectivityManager 85
Criteria 143, 147
Cursor 79
Display 272
DisplayMetrics 273
Environment 199
File 199
GeoPoint 179
GsmCellLocation 27
IntentFilter 128
LayoutInflater 232
Locale 159
Location 152
LocationManager 141
LocationProvider 143
MapActivity 178
MapController 178
MapView 177
MemoryInfo 313
NetworkInfo 86
Notification 330
Notification.Builder 330
NotificationManager 329
PhoneStateListener 37
PowerManager 294
Preference 97
Process 323
ProcessBuilder 323
ProcessErrorStateInfo 313, 320
RecentTaskInfo 313, 319
RunningAppProcessInfo 313
RunningServiceInfo 313, 316
RunningTaskInfo 313, 317
SeekBar 187
Sensor 248
SensorManager 249
Service 337
ServiceState 41
Settings 115
SmsManager 64
SmsMessage 70
SurfaceView 224
TelephonyManager 25
TextToSpeech 348
TrafficStats 89
WakeLock 294
WebView 93
WifiConfiguration 123
WifiInfo 118
WifiManager 107
Maps API Key 174
Linux 323
:
Activity 15
Broadcast Receiver 15
Content Provider 15
Service 15
363
:
ACCURACY_COARSE 147
ACCURACY_FINE 147
ACCURACY_HIGH 147
ACCURACY_LOW 147
ACCURACY_MEDIUM 147
ACQUIRE_CAUSES_WAKEUP 294
BATTERY_HEALTH_DEAD 283
BATTERY_HEALTH_GOOD 283
BATTERY_HEALTH_OVER_
VOLTAGE 283
BATTERY_HEALTH_OVERHEAT 283
BATTERY_HEALTH_UNKNOWN 283
BATTERY_HEALTH_UNSPECIFIED_
FAILURE 283
BATTERY_PLUGGED_AC 283
BATTERY_PLUGGED_USB 283
BATTERY_STATUS_CHARGING 283
BATTERY_STATUS_
DISCHARGING 283
BATTERY_STATUS_FULL 283
BATTERY_STATUS_NOT_
CHARGING 283
BATTERY_STATUS_UNKNOWN 283
CALL_STATE_IDLE 28
CALL_STATE_OFFHOOK 28
CALL_STATE_RINGING 28
CLIPBOARD_SERVICE 344
CONNECTIVITY_SERVICE 85
DEFAULT_ALL 330
DEFAULT_LIGHTS 330
DEFAULT_SOUND 330
DEFAULT_VIBRATE 330
DENSITY_HIGH 273
DENSITY_LOW 273
DENSITY_MEDIUM 273
DENSITY_XHIGH 273
DIRECTORY_ALARMS 200
DIRECTORY_DCIM 200
DIRECTORY_DOWNLOADS 200
DIRECTORY_MOVIES 200
DIRECTORY_MUSIC 200
DIRECTORY_NOTIFICATIONS 200
DIRECTORY_PICTURES 200
DIRECTORY_PODCASTS 200
DIRECTORY_RINGTONES 200
ELAPSED_REALTIME 337
( . . 364)
364
():
ELAPSED_REALTIME_WAKEUP 337
ERROR 349
FULL_WAKE_LOCK 294
GPS_PROVIDER 143
GRAVITY_DEATH_STAR_I 263
GRAVITY_MERCURY 263
GRAVITY_MOON 263
GRAVITY_VENUS 263
INTERVAL_DAY 337
INTERVAL_FIFTEEN_MINUTES 337
INTERVAL_HALF_DAY 337
INTERVAL_HALF_HOUR 337
INTERVAL_HOUR 337
KEYBOARD_12KEY 310
KEYBOARD_NOKEYS 310
KEYBOARD_QWERTY 310
KEYBOARD_UNDEFINED 310
LIGHT_CLOUDY 253
LIGHT_FULLMOON 253
LIGHT_NO_MOON 253
LIGHT_OVERCAST 253
LIGHT_SHADE 253
LIGHT_SUNLIGHT 253
LIGHT_SUNLIGHT_MAX 253
LIGHT_SUNRISE 253
LISTEN_CALL_FORWARDING_
INDICATOR 39
LISTEN_CALL_STATE 39
LISTEN_CELL_LOCATION 39
LISTEN_DATA_ACTIVITY 39
LISTEN_DATA_CONNECTION_
STATE 39
LISTEN_MESSAGE_WAITING_
INDICATOR 39
LISTEN_NONE 39
LISTEN_SERVICE_STATE 39
LISTEN_SIGNAL_STRENGTHS 39
LOCATION_SERVICE 141
MAGNETIC_FIELD_EARTH_
MAX 267
MAGNETIC_FIELD_EARTH_MIN 267
MEDIA_BAD_REMOVAL 202
MEDIA_CHECKING 202
MEDIA_MOUNTED 202
MEDIA_MOUNTED_READ_
ONLY 202
MEDIA_NOFS 202
MEDIA_REMOVED 202
MEDIA_SHARED 202
MEDIA_UNMOUNTABLE 202
MEDIA_UNMOUNTED 202
NAVIGATION_DPAD 310
NAVIGATION_NONAV 310
NAVIGATION_TRACKBALL 310
NAVIGATION_UNDEFINED 310
NAVIGATION_WHEEL 310
NETWORK_PROVIDER 143
NETWORK_TYPE_1xRTT 26
NETWORK_TYPE_CDMA 26
NETWORK_TYPE_EDGE 26
NETWORK_TYPE_EHRPD 26
NETWORK_TYPE_EVDO_0 26
NETWORK_TYPE_EVDO_A 26
NETWORK_TYPE_EVDO_B 26
NETWORK_TYPE_GPRS 26
NETWORK_TYPE_HSDPA 27
NETWORK_TYPE_HSPA 27
NETWORK_TYPE_HSUPA 27
NETWORK_TYPE_IDEN 27
NETWORK_TYPE_LT 26
NETWORK_TYPE_UMTS 27
NETWORK_TYPE_UNKNOWN 27
NO_REQUIREMENT 147
ON_AFTER_RELEASE 294
PARTIAL_WAKE_LOCK 294
PASSIVE_PROVIDER 144
PHONE_TYPE_CDMA 26
PHONE_TYPE_GSM 26
PHONE_TYPE_NONE 26
PHONE_TYPE_SIP 26
POWER_HIGH 147
POWER_LOW 147
POWER_MEDIUM 147
QUEUE_ADD 349
QUEUE_FLUSH 349
RECENT_IGNORE_
UNAVAILABLE 319
RECENT_WITH_EXCLUDED 319
RESULT_ERROR_GENERIC_
FAILURE 64
RESULT_ERROR_NO_SERVICE 64
RESULT_ERROR_NULL_PDU 64
RESULT_ERROR_RADIO_OFF 64
RESULT_OK 64
ROTATION_0 273
ROTATION_180 273
ROTATION_270 273
ROTATION_90 273
RTC 337
RTC_WAKEUP 337
SCREEN_BRIGHT_WAKE_LOCK 294
SCREEN_DIM_WAKE_LOCK 294
SENSOR_DELAY_FASTEST 252
SENSOR_DELAY_GAME 252
SENSOR_DELAY_NORMAL 252
SENSOR_DELAY_UI 252
SENSOR_STATUS_ACCURACY_
HIGH 251
SENSOR_STATUS_ACCURACY_
LOW 251
SENSOR_STATUS_ACCURACY_
MEDIUM 251
SENSOR_STATUS_UNRELIABLE 251
SIM_STATE_ABSENT 35
SIM_STATE_NETWORK_LOCKED 35
SIM_STATE_PIN_REQUIRED 35
SIM_STATE_PUK_REQUIRED 35
SIM_STATE_READY 35
SIM_STATE_UNKNOWN 35
STANDARD_GRAVITY 263
STATE_EMERGENCY_ONLY 41
STATE_IN_SERVICE 41
STATE_OUT_OF_SERVICE 41
STATE_POWER_OFF 41
STATUS_ON_ICC_FREE 71
STATUS_ON_ICC_READ 71
STATUS_ON_ICC_SEND 71
STATUS_ON_ICC_UNREAD 71
STATUS_ON_ICC_UNSENT 71
SUCCESS 349
TOUCHSCREEN_FINGER 311
TOUCHSCREEN_NOTOUCH 311
TOUCHSCREEN_STYLUS 311
TOUCHSCREEN_UNDEFINED 311
TYPE_ACCELEROMETER 248
TYPE_ALL 248
TYPE_GRAVITY 248
TYPE_GYROSCOPE 248
TYPE_LIGHT 248
TYPE_LINEAR_ACCELERATION 248
TYPE_MAGNETIC_FIELD 248
TYPE_ORIENTATION 248
TYPE_PRESSURE 248
365
TYPE_PROXIMITY 248
TYPE_ROTATION_VECTOR 248
TYPE_TEMPERATURE 248
WIFI_STATE_DISABLED 108
WIFI_STATE_DISABLING 108
WIFI_STATE_ENABLED 108
WIFI_STATE_ENABLING 108
WIFI_STATE_UNKNOWN 108
WINDOW_SERVICE 272
- 19
:
acquire(), PowerManager 294
allowedAuthAlgorithms() 124
allowedGroupCiphers() 124
allowedKeyManagement() 124
allowedPairwiseCiphers() 124
allowedProtocols() 124
animateTo() 178
calculateSignalLevel() 134
cancel(), AlarmManager 336
cancel(), NotificationManager 329
cancelAll(),
NotificationManager 329
compareSignalLevel() 134
displayZoomControls() 185
getAccuracy() 143, 147, 153
getActiveNetworkInfo() 85
getAddressLine() 159
getAllNetworkInfo() 85
getAllProviders() 143
getAltitude() 153
getBaseStationId() 28
getBaseStationLatitude() 28
getBaseStationLongitude() 28
getBearingAccuracy() 147
getBestProvider() 147
getBSSID() 118
getCallState() 28
getCdmaDbm() 40
getCdmaEcio() 40
getCellLocation() 27
getCid() 27
getColumnName() 79
getCountry() 159
getCountryCode() 158
( . . 366)
366
():
getCountryName() 158
getDataDirectory() 199
getDefault() 64
getDefaultDisplay() 272
getDefaultSensor() 249
getDeviceConfigurationInfo() 309
getDhcpInfo() 118
getDisplayCountry() 159
getDisplayId() 272
getDisplayLanguage() 159
getDisplayMessageBody() 70
getDisplayName() 159
getDisplayOriginatingAddress() 70
getDownloadCacheDirectory() 199
getEvdoDbm() 40
getEvdoEcio() 40
getEvdoSnr() 40
getExternalStorageDirectory() 199
getExternalStorageState() 202
getFeatureName() 159
getFromLocationName() 168
getGsmBitErrorRate() 40
getGsmSignalStrength() 40
getHeight() 273
getHolder() 224
getHorizontalAccuracy() 147
getIndexOnIcc() 70
getIsManualSelection() 41
getISO3Country() 159
getISO3Language() 159
getLac() 27
getLanguage() 159, 349
getLastKnownLocation() 152
getLatitude() 152
getLatitudeE6() 179
getLinkSpeed() 118
getLocality() 159
getLongitude() 152
getLongitudeE6() 179
getMaximumRange() 248
getMaxZoomLevel() 177
getMemoryInfo() 313
getMessageBody() 70
getMessageClass() 70
getMinDelay() 248
getMobileRxBytes() 89
getMobileRxPackets() 89
getMobileTxBytes() 89
getMobileTxPackets() 89
getName() 143, 248
getNetworkId() 28
getNetworkInfo() 85
getNetworkType() 26
getOperatorAlphaLong() 41
getOperatorAlphaShort() 41
getOperatorNumeric() 41
getOriginatingAddress() 70
getParameters(), Camera 214
getPdu() 70
getPhone() 159
getPhoneType() 26
getPostalCode() 159
getPower() 248
getPowerRequirement() 143, 147
getProcessesInErrorState() 320
getProcessMemoryInfo() 313
getProtocolIdentifier() 70
getProvider() 143
getProviders() 143
getPsc() 27
getRefreshRate() 273
getResolution() 248
getRoaming() 41
getRootDirectory() 199
getRssi() 133
getRunningAppProcesses() 315
getRunningServices() 316
getRunningTasks() 317
getSensorList() 249
getServiceCenterAddress() 70
getSimCountryIso() 34
getSimOperator() 34
getSimOperatorName() 34
getSimSerialNumber() 34
getSimState() 34, 35
getSpeedAccuracy() 147
getSSID() 118
getState() 41
getStatus() 70
getStatusOnIcc() 71
getSubAdminArea() 158
getSubtype() 86
getSubtypeName() 86
getSupportedColorEffects() 217
getSupportedFlashModes() 217
getSupportedFocusModes() 217
getSupportedJpegThumbnailSizes() 217
getSupportedPictureFormats() 217
getSupportedPictureSizes() 217
getSupportedPreviewFormats() 217
getSupportedPreviewFpsRange() 217
getSupportedPreviewSizes() 217
getSupportedSceneModes() 217
getSupportedVideoSizes() 217
getSupportedWhiteBalance() 217
getSystemId() 28
getSystemService() 25
getText(), ClipboardManager 344
getTimestampMillis() 70
getTotalRxBytes() 89
getTotalTxBytes() 89
getTotalTxPackets() 89
getType() 86
getTypeName() 86
getUidRxBytes() 90
getUidTxBytes() 90
getUserData() 71
getVendor() 248
getVersion() 248
getVerticalAccuracy() 147
getWidth() 273
getZoomLevel() 177
goToSleep() 293
hasMonetaryCost() 143
hasText(), ClipboardManager 344
isAltitudeRequired() 148
isAvailable() 86
isBearingRequired() 148
isConnected() 86
isConnectedOrConnecting() 86
isCostAllowed() 148
isDirectory() 199
isFile() 199
isLanguageAvailable() 349
isNetworkRoaming() 28
isRoaming() 86
isSatellite() 177
isScreenOn() 293
isSpeaking() 349
isSpeedRequired() 148
isStreetView() 177
isTraffic() 177
loadData() 95
loadDataWithBaseURL() 95
loadUrl() 93
meetsCriteria() 143
367
newWakeLock() 294
notify(), NotificationManager 329
onCallForwardingIndicatorChanged() 38
onCallStateChanged() 38
onCellLocationChanged() 38, 40
onDataActivity() 38
onDataConnectionStateChanged() 38
onListItemClick() 80
onLocationChanged() 153
onMessageWaitingIndicatorChanged() 38
onProviderDisabled() 153
onProviderEnabled() 153
onSensorChanged() 251
onServiceStateChanged() 38, 41
onSignalStrengthsChanged() 38, 39
onStatusChanged() 153
open(), Camera 213
preSharedKey() 124
reboot() 293
registerListener() 252
release(), Camera 213
release(), PowerManager 295
requestLocationUpdates() 154
requestSingleUpdate() 154
requiresCell() 143
requiresNetwork() 143
requiresSatellite() 143
sendMultipartTextMessage() 65
set(), AlarmManager 336
setAccuracy() 147
setBuiltInZoomControls() 97, 185
setCenter() 178
setCursiveFontFamily() 97
setDefaultFixedFontSize() 97
setDefaultFontSize() 97
setDefaultZoom() 97
setDisplayZoomControls() 97
setFixedFontFamily() 97
setInexactRepeating() 336
setLanguage() 349
setMinimumFontSize() 97
setMinimumLogicalFontSize() 97
setParameters(), Camera 214
setPowerRequirement() 147
setReferenceCounted(),
PowerManager 295
setRepeating() 336
( . . 366)
368
():
setSatellite() 177
setStreetView() 177
setSupportZoom() 97
setText(), ClipboardManager 344
setTextSize() 97
setTime(), AlarmManager 336
setTimeZone(), AlarmManager 336
setTraffic() 177
setZoom() 178
shutdown(), TextToSpeech 348
speak() 348
startActivity() 163
startScan() 128
stop(), TextToSpeech 348
stopAnimation() 178
supportsAltitude() 143
supportsSpeed() 143
surfaceChanged() 224
surfaceCreated() 224
surfaceDestroyed() 224
synthesizeToFile() 348
takePicture() 236
wepKeys() 124
wepTxKeyIndex() 124
zoomIn() 178
zoomInFixing() 178
zoomOutFixing() 178
zoomToSpan() 179
273
Intent 18, 53
:
Android Device Chooser 13
Android SDK and AVD Manager 9
:
android.app 303
android.location 141, 153
android.net 85
android.net.http 85
android.net.wifi 107
android.os 199
android.provider 19
android.telephony 25
android.view 272
java.io.File 199
java.net 85
:
Azimuth 258
EXTRA_BSSID 109
EXTRA_HEALTH 283
EXTRA_ICON_SMALL 283
EXTRA_LEVEL 282
EXTRA_NETWORK_INFO 108
EXTRA_NEW_STATE 109
EXTRA_PRESENT 282
EXTRA_PREVIOUS_WIFI_STATE 108
EXTRA_SCALE 282
EXTRA_SUPPLICANT_
CONNECTED 109
EXTRA_SUPPLICANT_ERROR 109
EXTRA_TECHNOLOGY 283
EXTRA_TEMPERATURE 282
EXTRA_VOLTAGE 282
Lateral 263
Longitudinal 263
Pitch 258
Roll 258
Vertical 263
273
:
_id,
TextBasedSmsColumns 79
address,
TextBasedSmsColumns 79
availMem 313
baseActivity 317
baseIntent 319
body,
TextBasedSmsColumns 79
condition,
ProcessErrorStateInfo 320
date,
TextBasedSmsColumns 79
densityDpi 273
description, RecentTaskInfo 319
description, RunningTaskInfo 317
dns1 118
dns2 118
error_code,
TextBasedSmsColumns 79
flags, Notification 331
frequency 128
gateway 118
heightPixels 273
id, RecentTaskInfo 319
id, RunningTaskInfo 317
interval 337
ipAddress 118
level 128
locked,
TextBasedSmsColumns 79
longMsg,
ProcessErrorStateInfo 321
lowMemory 313
netmask 118
numActivities 317
numRunning 317
operation 337
origActivity 319
person,
TextBasedSmsColumns 79
pid, ProcessErrorStateInfo 320
priority, WifiConfiguration 124
processName,
ProcessErrorStateInfo 320
protocol,
TextBasedSmsColumns 79
read,
TextBasedSmsColumns 79
reply_path_present 79
reqGlEsVersion 309
reqInputFeatures 309
reqKeyboardType 310
reqNavigation 310
reqTouchScreen 310
scaledDensity 273
serverAddress 118
service_center,
TextBasedSmsColumns 79
shortMsg,
ProcessErrorStateInfo 320
stackTrace 321
status,
TextBasedSmsColumns 79
status, WifiConfiguration 124
subject 79
tag, ProcessErrorStateInfo 320
thread_id,
TextBasedSmsColumns 79
369
threshold 313
topActivity 317
triggerAtTime 337
type,
TextBasedSmsColumns 79
uid, ProcessErrorStateInfo 320
widthPixels 273
xdpi 273
ydpi 273
apabilities 128
:
124
124
:
ACCESS_COARSE_
LOCATION 29, 40, 144
ACCESS_FINE_LOCATION 144
ACCESS_WIFI_STATE 108
BATTERY_STATS 284
CALL_PHONE 52
CALL_PRIVILEGED 52
CAMERA 214
CHANGE_WIFI_STATE 108
GET_TASKS 318
INTERNET 93
MODIFY_PHONE_STATE 52
PROCESS_OUTGOING_CALLS 52, 59
READ_PHONE_STATE 29, 35, 52
RECEIVE_SMS 65
SEND_SMS 65
WAKE_LOCK 295
WRITE_SETTINGS 277
WRITE_SMS 65
20
USB 11
28
:
Geocoding 158
Google Maps 174
142
128
108
Eclipse 9
370
322
1xRTT 26
CDMA 26
EDGE 26
EHRPD 26
EVDO_0 26
GPRS 26
GSM 26
HSDPA 27
HSPA 27
HSUPA 27
IDEN 27
LTE 26
SIP 26
UMTS 27
310
107
,
39
29
:
DEFAULT_LIGHTS 330
DEFAULT_SOUND 330
DEFAULT_VIBRATE 330
FLAG_AUTO_CANCEL 331
FLAG_FOREGROUND_SERVICE 331
FLAG_HIGH_PRIORITY 331
FLAG_INSISTENT 331
FLAG_NO_CLEAR 331
FLAG_ONGOING_EVENT 331
FLAG_ONLY_ALERT_ONCE 331
FLAG_SHOW_LIGHTS 331
INPUT_FEATURE_FIVE_WAY_
NAV 310
INPUT_FEATURE_HARD_
KEYBOARD 310
,
AES 124
:
310
310
311
Android 10, 13, 33, 49